You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复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类型,直接赋值给List类型变量会触发类型不匹配错误;若强行将变量改为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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 20:11:28