Flutter中JSON列表展示的List与Iterable类型转换报错求助
解决Flutter中JSON列表数据添加到List的类型不匹配问题
问题根源
jsonDecode解析返回的names['peoplesnames']是List<dynamic>类型,而你的peopleNames是List<String>,直接使用addAll会因为类型不兼容报错,需要将动态列表明确转换为字符串列表。
修复方案
将原代码中的:
peopleNames.addAll((names['peoplesnames'] as List));
替换为以下两种方式之一:
- 使用
cast<String>()强制转换类型:
peopleNames.addAll((names['peoplesnames'] as List).cast<String>());
- 遍历列表逐个转换为字符串(更安全,可处理非字符串元素的异常情况):
for (var name in names['peoplesnames'] as List) { peopleNames.add(name.toString()); }
完整修正代码
另外注意:不要在build方法中调用getData(),每次UI重建都会触发重复请求,应在initState中初始化数据:
import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'dart:convert'; class Test extends StatefulWidget { const Test({Key? key}) : super(key: key); @override State<Test> createState() => _TestState(); } class _TestState extends State<Test> { List<String> peopleNames = []; void getData() async { http.Response response = await http.get( Uri.parse('https://www.genericwebsite.com'), // 补充http/https协议头 ); if (response.statusCode == 200) { String data = response.body; final names = jsonDecode(data); // 使用cast转换类型 peopleNames.addAll((names['peoplesnames'] as List).cast<String>()); setState(() {}); } else { print(response.statusCode); } } @override void initState() { super.initState(); getData(); // 在initState中调用,仅执行一次 } @override Widget build(BuildContext context) { return Scaffold( body: ListView.builder( shrinkWrap: true, itemCount: peopleNames.length, itemBuilder: (context, index) { return Text(peopleNames[index]); }), ); } }
额外注意点
- 确保请求URL包含
http://或https://协议头,否则Uri.parse会解析失败。 - 类名首字母大写(
Test而非test),符合Dart代码规范。
内容的提问来源于stack exchange,提问作者Nomad09
相关产品推荐
相关产品推荐

