这是我更新的代码,UI 仍未刷新。我究竟做错了什么? 我移动了 setState 函数,也删除了 initState
class IncludeObject extends StatefulWidget {
const IncludeObject({
Key key,
this.title,
}) `: super(key: key); 最终字符串标题;
@override _IncludeObject createState() => _IncludeObject();`
class _IncludeObject extends State<IncludeObject> {
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 2.5),
child: Container(
decoration: BoxDecoration(
color: Color(0xffDEDEDE), borderRadius: BorderRadius.circular(4)),
child: Expanded(
child: Row(
children: [
Padding(
padding: const EdgeInsets.all(8),
child: Text(
widget.title.toString(),
style:
TextStyle(fontFamily: "Montserrat Regular", fontSize: 12),
),
),
IconButton(
icon: Icon(
Icons.close_outlined,
size: 20,
),
onPressed: () {
setState(() {
for (int i = 0; i <= includedList.length; i++) {
if (includedList[i].title == widget.title) {
includedList.removeAt(i);
included.removeAt(i);
print("removed");
}
}
});
}),
],
),
),
),
);
}
答案 0 :(得分:0)
首先,在您的 initState 中有一个 setState 不太好(阅读有关小部件生命周期的更多信息)
现在为什么会发生这个问题是因为你没有调用 setState 来用新数据更新 UI,只是为了做到这一点,只需在 setState
内的 onPressed 中添加代码,像这样
onPressed: () {
setState(() {
for (int i = 0; i <= includedList.length; i++) {
if (includedList[i].title == widget.title) {
includedList.removeAt(i);
included.removeAt(i);
_isRemoved = true;
print("removed");
print(_isRemoved);
}
}
});
}),
答案 1 :(得分:0)
您需要在删除项目后调用 setState
。
setState() 告诉 flutter 重新运行构建,从而反映更改。
您可以在删除项目后调用它。
onPressed: () {
for (int i = 0; i <= includedList.length; i++) {
if (includedList[i].title == widget.title) {
includedList.removeAt(i);
included.removeAt(i);
_isRemoved = true;
setState(() {});
print("removed");
print(_isRemoved);
}
}
}