Flutter应用无法展示Node.js Express API返回的数据求助
问题排查与解决步骤
1. 核对JSON字段与Flutter模型类的匹配性
API返回的JSON字段名必须和Flutter模型类的属性名完全大小写一致,比如API返回{"name":"Latte","price":3.5},Flutter模型类就不能写成String coffeeName;,必须是String name;。同时要给字段加空值兜底,避免解析失败:
class Coffee { final String name; final double price; Coffee({required this.name, required this.price}); factory Coffee.fromJson(Map<String, dynamic> json) { return Coffee( name: json['name'] ?? '', price: json['price']?.toDouble() ?? 0.0, ); } }
2. 修正列表解析逻辑
确保把API返回的数组逐个转换成Coffee对象,而非直接赋值响应体:
Future<List<Coffee>> fetchCoffees() async { final response = await http.get(Uri.parse('http://localhost:3000/api/coffees')); if (response.statusCode == 200) { List<dynamic> jsonList = json.decode(response.body); // 打印解析前的数组长度,确认数据存在 print('JSON数组长度:${jsonList.length}'); List<Coffee> coffees = jsonList.map((json) => Coffee.fromJson(json)).toList(); // 打印解析后的对象列表长度,确认转换成功 print('解析后列表长度:${coffees.length}'); return coffees; } else { throw Exception('Failed to load coffees'); } }
3. 修复UI状态更新逻辑
如果用FutureBuilder,要避免future在build方法中重复初始化,导致状态反复重置:
late Future<List<Coffee>> futureCoffees; @override void initState() { super.initState(); futureCoffees = fetchCoffees(); } @override Widget build(BuildContext context) { return Scaffold( body: FutureBuilder<List<Coffee>>( future: futureCoffees, builder: (context, snapshot) { if (snapshot.hasData) { return ListView.builder( itemCount: snapshot.data!.length, itemBuilder: (context, index) { return ListTile( title: Text(snapshot.data![index].name), subtitle: Text('\$${snapshot.data![index].price}'), ); }, ); } else if (snapshot.hasError) { return Text('${snapshot.error}'); } return const CircularProgressIndicator(); }, ), ); }
4. 检查Node.js API的响应格式
确保API返回的是纯数组格式,而非嵌套在对象中的数组。比如正确响应:
[ {"name":"Espresso","price":2.5}, {"name":"Cappuccino","price":3.0} ]
如果API返回的是{"coffees": [/*...*/]},Flutter解析时要先取json['coffees']再转列表。
内容的提问来源于stack exchange,提问作者Prashant Shukla
相关产品推荐
相关产品推荐

