我在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],
),
);
},
),
);
}
}
发布于 2019-08-19 17:26:28
无状态Widget属性应该是不可变的
class StudentsList extends StatelessWidget {
// final means, flutter will not change value in future
final List<Child> mList;
StudentsList({this.mList});
为什么?
因为Flutter需要,所以没有业务逻辑驻留在中的StatelessWidget中。如果我们需要在学生列表中添加新的学生,则将其视为业务逻辑。如果我们需要删除学生列表中的某个学生,则将其视为业务逻辑。
因此,通过使用无状态窗口小部件,Flutter will only专注于它将如何在屏幕上显示,宽度是什么,约束等。
这就是为什么我们在StatelessWidget
中发现final
语法先于类属性。
类似于我们的大学生活。我们在期末报告中标注的成绩,即使我们大学毕业也不会改变。正如它所说的在Final Report中,那么它一定是final。
有状态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
发布于 2020-11-09 17:03:19
无状态窗口小部件属性不能是不可变的,简单地说就是它不应该包含任何非最终变量。
只需将其转换为有状态小部件,然后在class _StudentsListState
中创建不带最终关键字的变量,因为您正在修改该列表的值。
https://stackoverflow.com/questions/57549163
复制相似问题