[英]Flutter: CheckboxListTile inside ListView jumps to top
So I know there are some similar questions about this issue but none of them worked for me.所以我知道关于这个问题有一些类似的问题,但没有一个对我有用。 I have a ListView with different CheckboxListTiles and when I scroll down and choose an item, the ListView automatically jumps to the top.
我有一个具有不同 CheckboxListTiles 的 ListView,当我向下滚动并选择一个项目时,ListView 会自动跳到顶部。 Is there a way to prevent this from happening?
有没有办法防止这种情况发生? Thank you very much, I've added a screenshot.
非常感谢,我已经添加了截图。 so you can better understand: This is my code:
所以你可以更好地理解:这是我的代码:
class CheckboxWidget extends StatefulWidget {
const CheckboxWidget({
Key key,
this.item,
this.type,
this.state,
}) : super(key: key);
final Map<String, bool> item;
final String type;
final Map<String, dynamic> state;
@override
State<CheckboxWidget> createState() => _CheckboxWidgetState();
}
class _CheckboxWidgetState extends State<CheckboxWidget> {
@override
void initState() {
super.initState();
if (widget.state[widget.type].isEmpty) {
widget.item.updateAll((key, value) => value = false);
}
}
bool isChecked = false;
@override
Widget build(BuildContext context) {
final FilterProvider filterProvider = Provider.of<FilterProvider>(context);
return Expanded(
child: ListView(
key: UniqueKey(),
children: widget.item.keys.map(
(key) {
return CheckboxListTile(
contentPadding: EdgeInsets.only(left: 2, right: 2),
title: Text(
key,
style: TextStyle(fontSize: 19, fontWeight: FontWeight.w400),
),
value: widget.item[key],
activeColor: Color(0xffF6BE03),
checkColor: Color(0xff232323),
shape: CircleBorder(),
//contentPadding: EdgeInsets.all(0),
onChanged: (value) {
value
? filterProvider.multifiltervalue = [widget.type, key]
: filterProvider.multifiltervalue = [
widget.type,
key,
false
];
setState(
() {
widget.item[key] = value;
},
);
},
);
},
).toList(),
),
);
}
}
CheckboxListTile is a stateless Widget... setState is redrawing the whole list. CheckboxListTile 是一个无状态的小部件... setState 正在重绘整个列表。
You could wrap the CheckboxListTile
into a Statefull Widget or into a StatefulBuilder
... if you call setState inside the StatefulBuilder
only this part should be redrawed..您可以将
CheckboxListTile
包装到 Statefull Widget 或StatefulBuilder
中……如果您在StatefulBuilder
中调用 setState ,则仅应重绘此部分。
another way could be to save the scroll position... but i think redrawing only the part on screen you haved changed is smarter:-)另一种方法可能是保存滚动 position ......但我认为只重绘屏幕上你已经改变的部分更聪明:-)
Probably because this line key: UniqueKey(),
when you call setState
the build function builds its widgets again, and the ListView
will have a new UniqueKey
so it will rebuild the list cause it thinks its a different widget可能是因为这个行
key: UniqueKey(),
当您调用setState
时,构建 function 会再次构建它的小部件,并且ListView
将有一个新的UniqueKey
,因此它将重建列表,因为它认为它是一个不同的小部件
remove this line key: UniqueKey(),
and it should work fine删除此行
key: UniqueKey(),
它应该可以正常工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.