调用setState时,不会重置ListView.builder的索引找到了一个奇怪的解决方案有更好的解决方案吗?为什么会这样呢?

问题描述

我有这个listview.builder,它应该根据状态显示一些Order对象数组中的订单。 看起来有点像这样:

enter image description here

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);

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...