Flutter Provider:无法从提供者的列表中删除项目
Flutter Provider : cannot remove item from list in provider
我在 listview 生成器中有复选框 listtile 我想要当我检查任何一个然后它的数据添加到列表然后当我取消选中它时将其从列表中删除:
Directionality(
textDirection: TextDirection.rtl,
child: ListView.builder(
itemCount: student.length,
itemBuilder: (context, index) {
return Card(
child: CheckBoxedListTile(
student[index], widget.date, widget.time,widget.teacher,widget.subject));
}),
),
);
}
}
检查 listtile 小部件是:
class _CheckBoxedListTileState extends State<CheckBoxedListTile> {
var checked;
@override
void initState() {
checked = false;
super.initState();
}
@override
Widget build(BuildContext context) {
return Consumer<AbsenceProvider>(builder: (context, absProv, child) {
return CheckboxListTile(
value: checked,
onChanged: (val) {
setState(() {
checked = !checked;
});
var data = {
"name": widget.student.name,
"stage": widget.student.stage,
"group": widget.student.group,
"teacher": widget.teacher,
"subject": widget.subject,
"date": widget.date,
"time": widget.time,
"vacs": "No"
};
if (checked == true) {
absProv.addAbs(data);
} else {
absProv.remAbs(data);
}
print(absProv.absences);
},
title: Text('${widget.student.name}'),
);
});
}
}
提供商是:
class AbsenceProvider with ChangeNotifier {
var absences = [];
addAbs(item) {
absences.add(item);
notifyListeners();
}
remAbs(item) {
absences.remove(item);
notifyListeners();
}
}
当我点击复选框时,它添加成功
但是当我再次点击时它也没有被移除
我使用 removeWhere 解决了它:
之前:
absences.remove(item);
之后:
absences.removeWhere((e) => e['name'] == item['name']);
我在 listview 生成器中有复选框 listtile 我想要当我检查任何一个然后它的数据添加到列表然后当我取消选中它时将其从列表中删除:
Directionality(
textDirection: TextDirection.rtl,
child: ListView.builder(
itemCount: student.length,
itemBuilder: (context, index) {
return Card(
child: CheckBoxedListTile(
student[index], widget.date, widget.time,widget.teacher,widget.subject));
}),
),
);
}
}
检查 listtile 小部件是:
class _CheckBoxedListTileState extends State<CheckBoxedListTile> {
var checked;
@override
void initState() {
checked = false;
super.initState();
}
@override
Widget build(BuildContext context) {
return Consumer<AbsenceProvider>(builder: (context, absProv, child) {
return CheckboxListTile(
value: checked,
onChanged: (val) {
setState(() {
checked = !checked;
});
var data = {
"name": widget.student.name,
"stage": widget.student.stage,
"group": widget.student.group,
"teacher": widget.teacher,
"subject": widget.subject,
"date": widget.date,
"time": widget.time,
"vacs": "No"
};
if (checked == true) {
absProv.addAbs(data);
} else {
absProv.remAbs(data);
}
print(absProv.absences);
},
title: Text('${widget.student.name}'),
);
});
}
}
提供商是:
class AbsenceProvider with ChangeNotifier {
var absences = [];
addAbs(item) {
absences.add(item);
notifyListeners();
}
remAbs(item) {
absences.remove(item);
notifyListeners();
}
}
当我点击复选框时,它添加成功 但是当我再次点击时它也没有被移除
我使用 removeWhere 解决了它:
之前:
absences.remove(item);
之后:
absences.removeWhere((e) => e['name'] == item['name']);