簡體   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