flutter - 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'”
解决方案
对映射条目的引用products[key]
必须以 ! 运算符,以保证它不会为空。
return ToDoListEntry(
key, products[key]!, () => deleteItem(key), () => check(key));
}),
onChanged
我的 Checkbox的方法一定是nullsafe
出于某种原因。错误并没有指出这一点。
leading: Checkbox(
value: state,
onChanged: (bool? value) => check(),
),
推荐阅读
- cmis - 如何使用 DotCMIS 检查存储库文件夹中是否已存在文档
- html - 在 React 中创建一个类似日期的 html 输入字段(用点自动分隔数字)
- javascript - 指定请求桌面站点位置
- python - 如何将“aH bM”时间格式字符串转换为浮点数?
- google-colaboratory - Google colab 消耗过多的互联网数据
- scala - 如何将两个数据帧转换为行的元组列表
- mysql - MySQL 8 崩溃子选择查询
- debian - 在 debian 版本上解压缩无字符编码
- image - Xamarin Forms:Flowlistview 项目点击问题
- bitbucket-pipelines - 如何在拉取请求时跳过默认管道?