如何解决调用setState时,不会重置ListView.builder的索引找到了一个奇怪的解决方案有更好的解决方案吗?为什么会这样呢?
我有这个listview.builder,它应该根据状态显示一些Order对象数组中的订单。 看起来有点像这样:
List可以正常工作,直到由于某种原因,当我向下滚动并且视口只能显示带有索引的顺序(listview生成器功能中的那个)5,然后按“ New”之类的另一类别时,setState( )会被调用,整个内容都会重新构建,但是构建器的索引从5开始,而listview.builder不会构建0-4的任何值。我已经在构建器中打印了索引并捕获了这个bug,但是我仍然没有不明白为什么会这样。
这是我的listview.builder代码的样子:
ListView.builder(
controller: _scrollController,shrinkWrap: true,itemBuilder: (BuildContext context,int index) {
print("INDEX: $index");
return _showOrder(index);
},itemCount: orders.length,),
这是_showOrder()的代码:
Widget _showOrder(int i) {
String _currOrderStatus = orders[i].orderStatus;
/// _selectedOrderStatus is just a String which changes depending on the selected category of orders.
/// e.g. "New" or "Past"
return _currOrderStatus == _selectedOrderStatus
? ShowMyOrderWidget()
: SizedBox(
/// AND FOR SOME REALLY WEIRD REASON,THIS FIXES THE PROBLEM
/// It works with any height,as long as it's not 0,but if I have a lot of them,then the
/// layout gets spaced out and messy. With such a low number,this is highly unlikely,but
/// still seems like a stupid fix.
/// Why does this work? Why is this happening? Is there a better way to fix it?
height: 0.000000001,);
}
然后我只需在屏幕顶部那些按钮的setState()
功能中调用onPressed()
。
解决方法
在ListView中更改项目不会重置滚动位置。 由于您已经将ScrollController分配给ListView,请在调用setState()之前尝试调用“ jumpTo(0.0)”以重置其滚动位置。
_scrollController.jumpTo(0.0);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。