如何从JSON文件生成Game类对象列表以填充展示游戏的信息卡片
实现步骤
1. 修正JSON文件格式
你现有的JSON是多个游戏对象的集合,需要在外层包裹方括号[],使其成为标准JSON数组格式,否则会解析失败,修正后结构示例:
[ { "gameCategory": "Kaum Material", "gameName": "game1", "playerNumber": "2 - 10", // 剩余字段不变 }, { "gameCategory": "Kaum Material", "gameName": "game2", // 剩余游戏对象不变 } ]
2. 配置资源引用
把修正后的JSON文件放到项目的assets/json/目录下(没有对应目录可新建),然后在pubspec.yaml的flutter节点下添加资源声明:
flutter: assets: - assets/json/games.json
3. 补全Game类定义
你当前的Game类构造函数、属性声明里漏了explanations、materials、imagePath等JSON中存在的字段,需要先补全,避免解析报错,补全示例:
class Game { Game({ required this.gameCategory, required this.gameName, required this.playerNumber, required this.gameDuration, required this.explanations, required this.materials, required this.imagePath, // 剩余需要用到的字段依次添加 }); String gameCategory; String gameName; String playerNumber; String gameDuration; List<String> explanations; String materials; String imagePath; // 剩余属性依次添加 // 原有fromJson和toJson方法保持,补全对应字段赋值即可 factory Game.fromJson(Map<String, dynamic> json) => Game( gameCategory: json["gameCategory"], gameName: json["gameName"], playerNumber: json["playerNumber"], gameDuration: json["gameDuration"], explanations: List<String>.from(json["explanations"].map((x) => x)), materials: json["materials"], imagePath: json["imagePath"], // 剩余字段依次赋值 ); }
4. 加载JSON并解析为List
通过Flutter的rootBundle加载资源文件,再做解析即可,封装示例函数:
import 'dart:convert'; import 'package:flutter/services.dart'; Future<List<Game>> loadGameList() async { // 加载JSON文件内容 final jsonString = await rootBundle.loadString('assets/json/games.json'); // 解析为List<dynamic>类型的数组 final List<dynamic> jsonList = json.decode(jsonString); // 遍历每一项转为Game对象,最终得到List<Game> return jsonList.map((jsonItem) => Game.fromJson(jsonItem)).toList(); }
5. 页面渲染示例
如果要在界面中加载后渲染游戏卡片,可配合FutureBuilder使用:
FutureBuilder<List<Game>>( future: loadGameList(), builder: (context, snapshot) { if (snapshot.hasData) { final gameList = snapshot.data!; return ListView.builder( itemCount: gameList.length, itemBuilder: (context, index) { final game = gameList[index]; // 这里返回你自定义的游戏卡片组件即可,传入game对象的对应字段 return GameCard(game: game); }, ); } else if (snapshot.hasError) { return Text('加载失败:${snapshot.error}'); } return const CircularProgressIndicator(); }, )
内容的提问来源于stack exchange,提问作者Angelina Petzold
相关产品推荐
相关产品推荐

