如何修复Flutter类型错误:Iterable无法赋值给List<dynamic>变量?
Dart/Flutter类型错误解决:Iterable无法赋值给List
错误信息
A value of type 'Iterable' can't be assigned to a variable of type 'List
'.
Try changing the type of the variable, or casting the right-hand type to 'List'.
问题代码
const List<String> countriesList = <String>["Aphganistan",...]; //This countriesList comes from constants/countries.dart class SignUp extends StatefulWidget { const SignUp({super.key}); @override State<SignUp> createState() => _SignUpState(); } class _SignUpState extends State<SignUp> { static List<String> _allCountries = countriesList; static List _foundCountries = []; @override void initState() { _foundCountries = _allCountries; super.initState(); } @override Widget build(BuildContext context) { return Container( child: TextFormField( onChanged: (String enteredKeyword) { List<dynamic> results = []; if (enteredKeyword.isEmpty) { results = _allCountries; } else { results = _allCountries.where((element) => false); // 错误发生在这里! } setState(() { _foundCountries = results; }); log(enteredKeyword); }, ), ); } }
问题原因
where()方法返回的是Iterable[index]访问元素(Iterable不支持下标访问)。
解决方案
1. 将Iterable转为List
在where()调用后追加.toList()方法,把筛选结果转为List类型,同时替换掉占位的=> false,加入实际筛选逻辑:
results = _allCountries .where((element) => element.toLowerCase().contains(enteredKeyword.toLowerCase())) .toList();
2. 统一变量类型为List
避免使用dynamic模糊类型,让类型更明确:
- 修改
_foundCountries的类型:static List<String> _foundCountries = []; - 修改
results的类型:List<String> results = [];
这样后续在ListView.builder中使用_foundCountries[index]时不会再报错。
完整修复代码示例
const List<String> countriesList = <String>["Afghanistan", "Albania", "Algeria", ...]; //This countriesList comes from constants/countries.dart class SignUp extends StatefulWidget { const SignUp({super.key}); @override State<SignUp> createState() => _SignUpState(); } class _SignUpState extends State<SignUp> { static List<String> _allCountries = countriesList; static List<String> _foundCountries = []; @override void initState() { _foundCountries = _allCountries; super.initState(); } @override Widget build(BuildContext context) { return Container( child: Column( children: [ TextFormField( onChanged: (String enteredKeyword) { List<String> results = []; if (enteredKeyword.isEmpty) { results = _allCountries; } else { results = _allCountries .where((element) => element.toLowerCase().contains(enteredKeyword.toLowerCase())) .toList(); } setState(() { _foundCountries = results; }); log(enteredKeyword); }, ), Expanded( child: ListView.builder( itemCount: _foundCountries.length, itemBuilder: (context, index) { return ListTile(title: Text(_foundCountries[index])); }, ), ) ], ), ); } }
内容的提问来源于stack exchange,提问作者newbie2210
相关产品推荐
相关产品推荐

