使用dart:js_interop如何直接读取JSObject属性无需扩展类型转换?
dart:js_interop 读取JS JSON对象属性的方案
可以直接通过JSObject操作,无需额外扩展类型转换,具体方式如下:
从JavaScript获取的JSON对象,在Dart中会自动包装为
JSObject实例(未指定扩展类型时)。读取属性有两种常用方式:
- 调用
getProperty方法:import 'dart:js_interop'; JSObject jsJson = jsGetJsonObject().toJS; // 假设这是从JS获取对象的方法 String username = jsJson.getProperty('username').toDartString; int userAge = jsJson.getProperty('age').toDartInt; - 使用下标操作符
[],写法更简洁:dynamic userEmail = jsJson['email']; bool isVerified = jsJson['isVerified'].toDartBool;
- 调用
注意事项:
- 读取的属性默认是
JSAny?类型,可通过toDartString/toDartInt等方法转为Dart基础类型;嵌套对象会返回JSObject。 - 不确定属性是否存在时,可用
hasProperty判断:if (jsJson.hasProperty('profile')) { JSObject profile = jsJson['profile'] as JSObject; String bio = profile['bio'].toDartString; }
- 读取的属性默认是
这种方式直接基于JSObject的原生API操作,无需定义扩展类型就能读取任意JSON对象的属性。
内容的提问来源于stack exchange,提问作者Олександр Бабіч
相关产品推荐
相关产品推荐

