已通过API获取并解码JSON,如何在Flutter应用中使用该数据?
在Flutter中使用API获取并解码后的JSON数据
首先,你得先明确data1的结构——jsonDecode返回的要么是Map<String, dynamic>(单个对象),要么是List<dynamic>(对象列表)。可以先打印确认结构:
print(data1);
接下来分场景处理:
一、直接使用动态数据(快速验证,不推荐生产环境)
如果只是快速测试功能,直接通过键名或索引取值即可:
场景1:API返回单个对象(比如用户信息)
假设API返回格式如下:
{ "id": 1, "name": "John Doe", "email": "john@example.com" }
直接在UI组件中取值展示:
Text('用户名: ${data1['name']}'), Text('邮箱: ${data1['email']}'),
场景2:API返回对象列表(比如用户列表)
假设API返回格式如下:
[ {"id":1, "name":"John"}, {"id":2, "name":"Jane"} ]
用ListView.builder渲染列表:
ListView.builder( itemCount: data1.length, itemBuilder: (context, index) { var user = data1[index]; return ListTile( title: Text(user['name']), subtitle: Text('ID: ${user['id']}'), ); }, )
二、转换成模型类(生产环境推荐,类型安全)
为了避免键名拼写错误、获得IDE代码提示,建议将JSON数据转换为自定义模型类。
步骤1:创建模型类
针对上述用户对象,创建User类:
class User { final int id; final String name; final String? email; // 可选字段用?标记 User({required this.id, required this.name, this.email}); // 从Map转成User对象的工厂方法 factory User.fromJson(Map<String, dynamic> json) { return User( id: json['id'], name: json['name'], email: json['email'], ); } }
如果返回的是列表,批量转换:
List<User> users = List<User>.from(data1.map((x) => User.fromJson(x)));
步骤2:使用模型类数据展示
现在可以安全地调用类属性,无需担心类型错误:
// 单个用户场景 User user = User.fromJson(data1); Text('用户名: ${user.name}'), // 用户列表场景 ListView.builder( itemCount: users.length, itemBuilder: (context, index) { User user = users[index]; return ListTile( title: Text(user.name), subtitle: Text(user.email ?? '无邮箱'), ); }, )
三、处理加载与错误状态
实际开发中,网络请求存在延迟或失败的可能,需要完善状态处理:
class _UserListPageState extends State<UserListPage> { List<User>? _users; bool _isLoading = true; String? _errorMsg; @override void initState() { super.initState(); _fetchUsers(); } Future<void> _fetchUsers() async { try { var res = await http.get(Uri.parse("SomeEndPoint")); if (res.statusCode == 200) { var data1 = jsonDecode(res.body); _users = List<User>.from(data1.map((x) => User.fromJson(x))); } else { _errorMsg = '请求失败,状态码: ${res.statusCode}'; } } catch (e) { _errorMsg = '网络错误: $e'; } finally { setState(() { _isLoading = false; }); } } @override Widget build(BuildContext context) { if (_isLoading) { return const Center(child: CircularProgressIndicator()); } if (_errorMsg != null) { return Center(child: Text(_errorMsg!)); } return ListView.builder( itemCount: _users?.length ?? 0, itemBuilder: (context, index) { User user = _users![index]; return ListTile(title: Text(user.name)); }, ); } }
内容的提问来源于stack exchange,提问作者Krishnapal Sendhav
相关产品推荐
相关产品推荐

