gpt4 book ai didi

list - flutter : Unsupported operation: Cannot add to an unmodifiable list

转载 作者:IT王子 更新时间:2023-10-29 07:15:21 25 4
gpt4 key购买 nike

我在 StatelessWidget 中有一个 ListView。它有项目,每个项目都包含一个复选框。当有人检查一个项目时,我希望 ListView 将其作为参数发送到另一个页面。但是当我这样做时,它给了我这个错误:

I/flutter ( 7067): The following UnsupportedError was thrown while handling a gesture:
I/flutter ( 7067): Unsupported operation: Cannot add to an unmodifiable list
I/flutter ( 7067): When the exception was thrown, this was the stack:

这是我的代码

class StudentsList extends StatelessWidget {
final List<Child> mList;
StudentsList({this.mList});

@override
Widget build(BuildContext context) {
List<Child> selectedList = [];

return Container(
margin: EdgeInsets.only(top: 50, bottom: 20),
child: ListView.builder(
shrinkWrap: true,
physics: ClampingScrollPhysics(),
itemCount: mList == null ? 0 : mList.length,
padding: EdgeInsets.only(right: 10),
itemBuilder: (BuildContext context, int position) {
return GestureDetector(
onTap: () {
if (selectedList.isEmpty) {
Navigator.push(
context,
new MaterialPageRoute(
builder: (BuildContext context) => SolokPage(
mChildList: [mList[position]],
isTeacher: true,
),
),
);
} else {
if (!selectedList.contains(mList[position])) {
selectedList.add(mList[position]);
}
Navigator.push(
context,
new MaterialPageRoute(
builder: (BuildContext context) => SolokPage(
mChildList: selectedList,
isTeacher: true,
),
),
);
}
},
child: StudentItem(
student: mList[position],
),
);
},
),
);
}
}

最佳答案

Stateless Widget 属性是不可变的

class StudentsList extends StatelessWidget {
// final means, flutter will not change value in future
final List<Child> mList;
StudentsList({this.mList});

为什么?

因为 Flutter 期望 没有业务逻辑驻留在 StatelessWidget 中。如果我们需要在学生列表中添加新的学生,它被认为是业务逻辑。如果我们需要删除学生列表中的一些学生,这被认为是业务逻辑。

因此,通过使用无状态小部件,Flutter 将关注它在屏幕上的显示方式、宽度、约束等。

这就是为什么我们在 StatelessWidget 中的类属性之前找到了 final 语法。

类似于我们的大学生活。我们在最终报告中标记的成绩,即使在我们大学毕业后也不会改变。正如Final Report中所说,那么它一定是final

Stateful Widget 属性是可变的

为什么?因为 Flutter 期望业务逻辑驻留在在 StatefulWidget 中。

要进行的更改

所以我建议从这里更改 StudentsList 小部件:

class StudentsList extends StatelessWidget {
final List<Child> mList; // this is the issue
StudentsList({this.mList});

到这个:

class StudentsList extends StatefulWidget {
@override
_StudentsListState createState() => _StudentsListState();
}

class _StudentsListState extends State<StudentsList> {
// final List<Child> mList; // Do not mark this as final

List<Child> mList;

...

}

工作库

您可能会查看与您的问题密切相关的工作存储库。 Github

Demo

关于list - flutter : Unsupported operation: Cannot add to an unmodifiable list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57549163/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com