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

Par*_*ani 0 dart flutter

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

  • 如何显示具有固定数量项目的列表视图,让我们说在我的示例中我们获取100个项目
  • 如何实现分页,最初说我要获取第一页然后滚动第二页,依此类推.

问题:

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

  • 能够在底部无休止地滚动
  • 在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

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

在此输入图像描述

Hem*_*Raj 8

这是你正在使用的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;
        },
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

希望有所帮助!

注意:我并不是说这是最好的方式或最佳方式,但这是其中一种方法.有一个git的社交网络应用程序以不同的方式进行,您可以在这里查看它.