我正在尝试使用可使用复选框选择的项目列表视图来实现屏幕。 这是主屏幕和复选框的代码:
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),
);
}
我还创建了一个模型文件:
class ModelCheckbox {
String title;
bool value;
ModelCheckbox({
@required this.title,
this.value = false,
});
}
我收到以下错误:
The getter 'key' was called on null.
Receiver: null
Tried calling: key
Null check operator used on a null value
有人知道为什么吗?我将值作为兴趣传递,并相应地创建了模型,以便能够动态显示标题而不是硬编码。
答案 0 :(得分:0)
您正在将兴趣列表的每个元素映射到 null。 ListView 只能将 Widgets 作为其子项。
试试
body: ListView(
children: interests.map((interest) => buildSingleCheckbox(interest)).toList(),
),