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

Flutter JSON转对象报错:类型不匹配与Future调用异常

Flutter JSON加载错误解决方案

1. 类型转换错误:type 'int' is not a subtype of type 'String'

  • 问题根源:games.json里的wished字段是整数类型(值为1),但代码中错误调用int.parse()解析该字段——int.parse()仅支持字符串输入,直接传入整数会触发类型不匹配。
  • 修复代码(修改game.dart中wished的赋值逻辑):
Game.fromJson(Map<String, dynamic> json) {
  id = int.parse(json['id']);
  ownerId = int.parse(json['ownerId']);
  name = json['name'];
  editor = json['editor'];
  wished = json['wished']; // 移除int.parse(),直接赋值整数
}

2. Future对象访问错误:Class Future<dynamic> has no instance getter 'popularGames'

  • 问题根源:loadJsonData()是异步函数(带async关键字),调用后返回的是Future对象而非直接返回加载完成的allGames数据。若在UI中直接把这个Future对象当作数据访问popularGames(推测为allGames的别名),就会触发该错误。

  • 两种修复方案:

    方案一:用await等待异步操作完成

    在异步函数内调用loadJsonData()时,通过await等待数据加载完毕后再使用:

    // 示例:在StatefulWidget的initState中调用
    @override
    void initState() {
      super.initState();
      _loadLibraryData();
    }
    
    Future<void> _loadLibraryData() async {
      final library = Library();
      await library.loadJsonData(); // 等待数据加载完成
      setState(() {
        // 这里可以用library.allGames更新UI状态
      });
    }
    

    方案二:用FutureBuilder处理异步加载

    通过FutureBuilder自动管理异步状态,避免直接操作Future对象:

    FutureBuilder(
      future: Library().loadJsonData(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          final library = Library();
          return ListView.builder(
            itemCount: library.allGames.length,
            itemBuilder: (context, index) {
              final game = library.allGames[index];
              return ListTile(title: Text(game.name));
            },
          );
        } else {
          // 加载中显示进度提示
          return const CircularProgressIndicator();
        }
      },
    )
    

额外优化建议

可以将Game类改为不可变类,使用初始化列表构造函数,避免late变量的潜在问题:

class Game {
  final int id;
  final int ownerId;
  final String name;
  final String editor;
  final int wished;

  Game({
    required this.id,
    required this.ownerId,
    required this.name,
    required this.editor,
    required this.wished,
  });

  Game.fromJson(Map<String, dynamic> json) : 
    id = int.parse(json['id']),
    ownerId = int.parse(json['ownerId']),
    name = json['name'],
    editor = json['editor'],
    wished = json['wished'];
}

内容的提问来源于stack exchange,提问作者Adrien Chapelet

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 13:32:36