简体   繁体   English

在 null flutter 错误上调用了 getter 'Key'

[英]The getter 'Key' was called on null flutter error

I am trying to achieve a screen with a Listview of items that can be selected with a Checkbox.我正在尝试使用可以使用复选框选择的项目的列表视图来实现屏幕。 This is the code for the main screen and checkbox:这是主屏幕和复选框的代码:

class InterestHobbies extends StatefulWidget {
  @override
  _InterestHobbiesState createState() => _InterestHobbiesState();
}

class _InterestHobbiesState extends State<InterestHobbies> {

  final interests = [
    ModelCheckbox(title: 'Sports'),
    ModelCheckbox(title: 'Sports'),
    ModelCheckbox(title: 'Sports'),
    ModelCheckbox(title: 'Sports'),
    ModelCheckbox(title: 'Sports'),
    ModelCheckbox(title: 'Sports'),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView(
        children: [
          ...interests.map((interest) => null).toList(),
        ],
      ),
    );
  }

  Widget buildSingleCheckbox(ModelCheckbox interest) => buildCheckbox(
    interest: interest,
    onClicked: (){
      setState(() {
        final newValue = !interest.value;
        interest.value = newValue;
      });
    }
  );

  Widget buildCheckbox({
    @required ModelCheckbox interest,
    @required VoidCallback onClicked,
  }) =>
      ListTile(
        onTap: onClicked,

        leading: Checkbox(
          value: interest.value,
          onChanged: (value) => onClicked(),
        ),
        title: Text(interest.title),
      );
}

I also created a model file:我还创建了一个 model 文件:

class ModelCheckbox {
  String title;
  bool value;

  ModelCheckbox({
    @required this.title,
    this.value = false,
  });
}

I get the following error:我收到以下错误:

The getter 'key' was called on null.
Receiver: null
Tried calling: key

Null check operator used on a null value

Does anyone know why?有谁知道为什么? I am passing the value as interest and I created the model accordingly to be able to show the title dynamically and not hard coded.我将值作为兴趣传递,并相应地创建了 model 以便能够动态显示标题而不是硬编码。

You are mapping each element of the interests list to null.您正在将兴趣列表的每个元素映射到 null。 The ListView can only have Widgets as its children. ListView 只能将 Widgets 作为其子项。

Try尝试

  body: ListView(
    children: interests.map((interest) => buildSingleCheckbox(interest)).toList(),
  ),

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

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