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

Flutter开发待办清单遇int不是String子类型及List初始化错误

问题原因及解决方法

问题2:List todos = List();无法运行的原因

  • Dart 2.12及以上版本引入了空安全机制,移除了默认的无参数List()构造函数,旧版教程的写法已经不兼容新版SDK,所以会报错。
  • 正确的空列表初始化方式如果要放String类型的待办,应该声明泛型:List<String> todos = [];,如果要使用动态类型直接写List todos = [];即可。

问题1:type 'int' is not a subtype of type 'String'报错原因

有两个触发点:

  1. 当前的初始化代码List todos = List.filled(3, 0, growable: true)给列表填充了3个int类型的0,但后续代码要把列表元素当String用在Text()组件、Key()参数里,类型不匹配就抛出了类型错误。
  2. 生命周期函数initState被拼写错误成了initSate,导致写的四个待办项添加逻辑完全没有执行,列表里始终只有3个int类型的0,进一步触发了类型错误。

完整修复方案

修改_TodoState类的代码即可:

class _TodoState extends State<TodoApp>{
  // 声明泛型为String的空可增长列表,替代旧的List()写法
  List<String> todos = [];

  @override // 补充方法注解,同时修正拼写错误
  void initState(){
    super.initState();
    todos.add("Item1");
    todos.add("Item2");
    todos.add("Item3");
    todos.add("Item4");
  }

  @override
  Widget build(BuildContext context){
    return Scaffold(
      appBar: AppBar(
        title: const Text("TodoApp"),
      ),
      body: ListView.builder(
          itemCount: todos.length,
          itemBuilder: (BuildContext context, int index){
            return Dismissible(
                key: Key(todos[index]),
                child: Card(
                  child: ListTile(
                    title: Text(todos[index]),
                  ),
                ));
          }),
    );
  }
}

内容的提问来源于stack exchange,提问作者Fabboy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 23:15:04