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
相关产品推荐
相关产品推荐

