繁体   English   中英

Flutter ToDo 列表复选框无法分配 bool

[英]Flutter ToDo list checkbox cant assign bool

我正在尝试用 flutter 开发一个 ToDo 列表。

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

  @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),
      ),
    );
  }
}

一个 function addItem(String item) 正在工作,还有一个 function deleteItem(String key),我传递给 ToDoListEntry class 正在工作。 现在我尝试编写复选框的更新功能代码并将我的条目保存到 Map<String, bool> 产品中:

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

当我现在将 products[key] 传递给我的 ToDoListEntry Widget 时,它说:“参数类型 '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’”

对 map 条目products[key]的引用必须由运算符尾随。 以保证它不会为空。

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

由于某种原因,我的 Checkbox 的onChanged方法必须是nullsafe 错误没有指出这一点。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM