Flutter Dart中如何解析JSON列表并用于组件渲染?
Flutter Dart JSON列表解析解决方案
第一步:修正JSON格式(关键前提)
你提供的JSON使用了单引号,而Dart的jsonDecode仅支持标准双引号格式。如果是本地硬编码的JSON字符串,先把所有单引号替换为双引号;如果是API响应数据,通常已经是标准双引号格式。
方式一:快速解析(无需实体类)
直接将JSON解码为动态列表,适合简单场景:
import 'dart:convert'; // 标准格式的JSON字符串 String jsonData = ''' [ { "id": 6, "owner": { "username": "ghazali", "email": "ghazali@gmail.com", "first_name": "Abu", "last_name": "Ubaidah", "groups": [] }, "name": "Food Hub", "date_created": "2023-12-27T20:13:13.414637Z" }, { "id": 7, "owner": { "username": "ghazali", "email": "ghazali@gmail.com", "first_name": "Abu", "last_name": "Ubaidah", "groups": [] }, "name": "Hamas", "date_created": "2023-12-27T20:04:56.852096Z" } ] '''; // 解码为动态列表 List<dynamic> orgs = jsonDecode(jsonData);
修改你的children代码:必须去掉const关键字(动态数据无法作为编译时常量传入const组件),同时显式转换类型避免运行时错误:
children: [ for (final org in orgs) OrganizationCard( id: org['id'] as int, tagLine: "We'll find the best for you.", organizationName: org['name'] as String, ), ],
方式二:类型安全解析(推荐)
创建实体类封装数据,避免类型错误,适合复杂项目:
1. 定义实体类
class Organization { final int id; final Owner owner; final String name; final DateTime dateCreated; Organization({ required this.id, required this.owner, required this.name, required this.dateCreated, }); // 从JSON映射到实体 factory Organization.fromJson(Map<String, dynamic> json) { return Organization( id: json['id'] as int, owner: Owner.fromJson(json['owner'] as Map<String, dynamic>), name: json['name'] as String, dateCreated: DateTime.parse(json['date_created'] as String), ); } } class Owner { final String username; final String email; final String firstName; final String lastName; final List<dynamic> groups; Owner({ required this.username, required this.email, required this.firstName, required this.lastName, required this.groups, }); factory Owner.fromJson(Map<String, dynamic> json) { return Owner( username: json['username'] as String, email: json['email'] as String, firstName: json['first_name'] as String, lastName: json['last_name'] as String, groups: json['groups'] as List<dynamic>, ); } }
2. 解码为实体列表
import 'dart:convert'; List<Organization> orgs = (jsonDecode(jsonData) as List) .map((item) => Organization.fromJson(item as Map<String, dynamic>)) .toList();
3. 生成组件
直接使用实体类属性,代码更清晰安全:
children: [ for (final org in orgs) OrganizationCard( id: org.id, tagLine: "We'll find the best for you.", organizationName: org.name, ), ],
常见问题排查
- JSON格式错误:确保所有键和字符串值使用双引号,单引号会导致
jsonDecode抛出异常。 - 误用
const:动态数据无法传入const组件,必须移除const关键字。 - 类型转换:显式使用
as int/as String转换类型,避免隐式转换带来的运行时错误。
内容的提问来源于stack exchange,提问作者Abdullah Saeed
相关产品推荐
相关产品推荐

