Flutter调用API出现List<dynamic>不匹配Map<String,dynamic>错误如何解决
Flutter API请求报错
type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'解决方案 问题根源
你的API返回的根结构是JSON数组(用[]包裹),但你的解析逻辑直接把返回结果传给了接收Map<String, dynamic>类型参数的Welcome.fromJson方法,类型不匹配触发报错,整体的请求封装、模型定义的思路是正确的,只需要调整数组解析逻辑即可。
修复步骤
1. 调整接口请求方法的返回类型与解析逻辑
把原来返回单个Welcome对象的方法,改成返回Welcome对象组成的列表:
Future<List<Welcome>> fetchProduct() async { final response = await http.get(Uri.parse( 'https://api.azabazar.com/api/all-products/?fbclid=IwAR0v4BAB_gFTcpU7Jjqg_t0MnUkUxq8sWPgLj1BHrmOOq_Nd132mz9F8iSU')); if (response.statusCode == 200) { // 先把返回结果转成List<dynamic> List<dynamic> jsonList = jsonDecode(response.body); // 遍历数组每个元素调用fromJson转成Welcome对象 return jsonList.map((jsonItem) => Welcome.fromJson(jsonItem)).toList(); } else { throw Exception('Failed to load product list'); } }
2. 调整State中Future变量的类型
// 原来的Future<Welcome>改成Future<List<Welcome>> late Future<List<Welcome>> futureProduct; @override void initState() { super.initState(); futureProduct = fetchProduct(); }
3. 调整FutureBuilder的渲染逻辑
后续在FutureBuilder中拿到的snapshot.data是商品列表,你可以用ListView等列表组件渲染:
FutureBuilder<List<Welcome>>( future: futureProduct, builder: (context, snapshot) { if (snapshot.hasData) { return ListView.builder( itemCount: snapshot.data!.length, itemBuilder: (context, index) { final product = snapshot.data![index]; // 这里写单个商品的渲染逻辑 return ListTile( title: Text(product.title), subtitle: Text("价格:${product.price}"), ); } ); } else if (snapshot.hasError) { return Text("${snapshot.error}"); } return const CircularProgressIndicator(); } )
优化建议
你的模型类命名为Welcome语义不够清晰,建议改成Product更贴合业务场景,便于后续代码维护。
内容的提问来源于stack exchange,提问作者Romanch haque
相关产品推荐
相关产品推荐

