You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用dart:js_interop如何直接读取JSObject属性无需扩展类型转换?

dart:js_interop 读取JS JSON对象属性的方案

可以直接通过JSObject操作,无需额外扩展类型转换,具体方式如下:

  • 从JavaScript获取的JSON对象,在Dart中会自动包装为JSObject实例(未指定扩展类型时)。

  • 读取属性有两种常用方式:

    1. 调用getProperty方法:
      import 'dart:js_interop';
      
      JSObject jsJson = jsGetJsonObject().toJS; // 假设这是从JS获取对象的方法
      String username = jsJson.getProperty('username').toDartString;
      int userAge = jsJson.getProperty('age').toDartInt;
      
    2. 使用下标操作符[],写法更简洁:
      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,提问作者Олександр Бабіч

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 03:42:35