首页 > 解决方案 > Flutter ToDo 列表复选框无法分配布尔值

问题描述

我试图用颤振开发一个待办事项列表。

我为列表运行一个有状态的小部件,其状态的构建方法如下所示:

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('ToDo App'),
        backgroundColor: const Color.fromRGBO(35, 0, 0, 100),
      ),
      body: ListView.builder(
          itemCount: products.length,
          itemBuilder: (context, index) {
            String key = products.keys.elementAt(index);
            return ToDoListEntry(
                key, products[key], () => deleteItem(key), () => check(key));
          }),
      floatingActionButton: FloatingActionButton(
        onPressed: newEntry,
        child: const Icon(Icons.arrow_downward),
      ),
    );
  }
}

一个函数 addItem(String item) 正在工作,还有一个函数 deleteItem(String key),我传递给 ToDoListEntry 类正在工作。现在我尝试为 Checkbox 编写更新功能并将我的条目保存到 Map<String, bool> 产品中:

Map<String, bool> products = {
    'Kartoffel': false,
    'Tomate': false,
    'Käse': false,
    'Wurst': false
  };

当我现在将 products[key] 传递给我的 ToDoListEntry 小部件时,它说:“参数类型'bool?' 不能分配给参数类型'bool'”

什么是“布尔”?我找不到任何解释。

ToDoListEmtry 看起来像这样:

class ToDoListEntry extends StatelessWidget {
  final String title;
  bool state;
  final Function remove, check;
  ToDoListEntry(this.title, this.state, this.remove, this.check);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 22),
      child: ListTile(
        contentPadding: EdgeInsets.symmetric(vertical: 8.0),
        leading: Checkbox(
          value: state,
          onChanged: (bool value) => check(),
        ),
        title: Text(
          title,
          style: TextStyle(fontSize: 18, color: Colors.black54),
        ),
        trailing: IconButton(
          icon: Icon(Icons.delete_outline),
          onPressed: () => remove(),
        ),
      ),
    );
  }
}

在这里,我遇到了 Checkbox 中的 onChecked 方法的问题:“参数类型 'void Function(bool)' 不能分配给参数类型 'void'”

标签: flutterdartassign

解决方案


对映射条目的引用products[key]必须以 ! 运算符,以保证它不会为空。

return ToDoListEntry(
  key, products[key]!, () => deleteItem(key), () => check(key));
}),

onChanged我的 Checkbox的方法一定是nullsafe出于某种原因。错误并没有指出这一点。

leading: Checkbox(
          value: state,
          onChanged: (bool? value) => check(),
        ),

推荐阅读