首页 文章

Dart / Flutter - Flutter - 为什么ListView无限

提问于
浏览
0

不确定,因为我刚开始用Flutter和Dart制作东西 . 如果有人可以查看代码并可以共享输入:

  • 如何显示具有固定数量项目的列表视图,让我们在示例中说明我们正在获取100个项目

  • 如何实现分页,最初我想先获取第一页然后滚动第二页,依此类推 .

Issues:

在目前的实施中,我发现了两个问题:

  • 能够在底部无休止地滚动

  • 在logcat输出中查找异常:

03-15 06:14:36.464 3938-3968 / com.technotalkative.flutterfriends I / flutter:抛出另一个异常:RangeError(index):无效值:不在0..99范围内,包括:100

我在我的Github存储库上发布了同样的问题:https://github.com/PareshMayani/Flutter-Friends/issues/1

如果你为这个回购做出贡献,我将不胜感激!

enter image description here

1 回答

  • 6

    这是因为你正在使用ListView.builder,它实际上在未指定 itemCount 时呈现无限列表 . 尝试将 itemCount 指定为100 .

    对于分页,使用 ListView.builder 的最简单的解决方案是在列表到达终点时显示刷新小部件并启动刷新API调用,然后将新项添加到列表中并增加项目计数 .

    例:

    class Example extends StatefulWidget {
      @override
      _ExampleState createState() => new _ExampleState();
    }
    
    class _ExampleState extends State<Example> {
    
      // initial item count, in your case `_itemCount = _friendList.length` initially
      int _itemCount = 10;
    
      void _refreshFriendList() {
        debugPrint("List Reached End - Refreshing");
    
        // Make api call to fetch new data
        new Future<dynamic>.delayed(new Duration(seconds: 5)).then((_){
            // after new data received
            // add the new data to the existing list
            setState(() {
              _itemCount = _itemCount + 10; // update the item count to notify newly added friend list
              // in your case `_itemCount = _friendList.length` or `_itemCount = _itemCount + newData.length`
            });
        });
      }
    
      // Function that initiates a refresh and returns a CircularProgressIndicator - Call when list reaches its end
      Widget _reachedEnd(){
        _refreshFriendList();
        return const Padding(
          padding: const EdgeInsets.all(20.0),
          child: const Center(
            child: const CircularProgressIndicator(),
          ),
        );
      }
    
      @override
      Widget build(BuildContext context) {
        return new Scaffold(
          appBar: new AppBar(),
    
          // ListView Builder
          body: new ListView.builder(
            itemCount: _itemCount + 1,
            itemBuilder: (_, index) {
              final Widget listTile = index == _itemCount // check if the list has reached its end, if reached end initiate refresh and return refresh indicator
                  ? _reachedEnd() // Initiate refresh and get Refresh Widget
                  : new Container(
                      height: 50.0,
                      color: Colors.primaries[index%Colors.primaries.length],
                    );
              return listTile;
            },
          ),
        );
      }
    }
    

    希望有所帮助!

    注意:我并不是说这是最好的方式或最佳方式,但这是其中一种方法 . 有一个git社交网络应用程序的例子以不同的方式做,你可以看看它here .

相关问题