Flutter错误:RangeError(索引):无效值:不在0..2范围内,包括3:

时间:2018-12-29 07:32:46

标签: android-studio dart flutter

我在扑朔迷离中使用了一长串。所有项目都可以正常渲染,但还会出现以下错误:

RangeError (index): Invalid value: Not in range 0..2, inclusive: 3

以下是我的代码:

@override
Widget build(BuildContext context) {
return Container(
  child: getList(),
 );
}

以下是我的getList()方法:

Widget getList (){
List<String> list = getListItems();
ListView myList = new ListView.builder(itemBuilder: (context, index){
  return new ListTile(
    title: new Text(list[index]),
  );
});
return myList;
}

以下是我的getListItem()方法:

List<String> getListItems(){
return ["Faizan", "Usman", "Naouman"];
}

以下是错误的屏幕截图:

enter image description here

7 个答案:

答案 0 :(得分:8)

您应该将itemCount参数传递给ListView.builder,以使其了解商品计数

Widget getList() {
  List<String> list = getListItems();
  ListView myList = new ListView.builder(
    itemCount: list.length,
    itemBuilder: (context, index) {
    return new ListTile(
      title: new Text(list[index]),
    );
  });
  return myList;
}

答案 1 :(得分:1)

如果你使用的是 StreamBuilder 那么你必须使用这行代码

  StreamBuilder(
                  stream: FirebaseFirestore.instance.collection("Tooth")
                  .orderBy("date", descending: false).snapshots() ,
                
                  builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot){
                 
                    if(snapshot.hasData)
                    {
                      return ListView.builder(
                        itemCount: snapshot.data.docs.length,
                          padding: const EdgeInsets.only( top: 20.0),
                        itemBuilder: (BuildContext context, int index) {
                           DocumentSnapshot ds = snapshot.data.docs[index];
 },
                      );
                    }
                   
                  },
                ),

答案 2 :(得分:0)

有限卷轴

解决方案很简单,您只需将 itemCount 添加到构建器,以便构建器允许它知道项目计数。就像上面的代码如this answer

中所述

无限滚动

要执行无限滚动,请使用 ListView.builder 而不指定 itemCount 参数。

  body: ListView.builder(
   itemCount: _photos.length + (_hasMore ? 1 : 0),
    itemBuilder: (context, index) {
      if (index == item.length - _nextPageThreshold) {
        // Here is your manuplated data code
      } else {
        getMoreData();
        return Center(child: CircularProgressIndicator());
      }
    },
  ),

完整代码示例

class ItemListScreen extends StatefulWidget {
  ItemListScreen({Key key}) : super(key: key);
  @override
  _PhotosListScreenState createState() => _PhotosListScreenState();
}

class _PhotosListScreenState extends State<ItemListScreen> {
  bool _hasMore;
  int _pageNumber;
  bool _error;
  bool _loading;
  final int _defaultPhotosPerPageCount = 10;
  List<Photo> _photos;
  final int _nextPageThreshold = 5;
  @override
  void initState() {
    super.initState();
    _hasMore = true;
    _pageNumber = 1;
    _error = false;
    _loading = true;
    _photos = [];
    fetchPhotos();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Photos App")),
      body: getBody(),
    );
  }

  Widget getBody() {
    if (_photos.isEmpty) {
      if (_loading) {
        return Center(
            child: Padding(
              padding: const EdgeInsets.all(8),
              child: CircularProgressIndicator(),
            ));
      } else if (_error) {
        return Center(
            child: InkWell(
              onTap: () {
                setState(() {
                  _loading = true;
                  _error = false;
                  fetchPhotos();
                });
              },
              child: Padding(
                padding: const EdgeInsets.all(16),
                child: Text("Error while loading photos, tap to try agin"),
              ),
            ));
      }
    } else {
      return ListView.builder(
          itemCount: _photos.length + (_hasMore ? 1 : 0),
          itemBuilder: (context, index) {
            if (index == _photos.length - _nextPageThreshold) {
              fetchPhotos();
            }
            if (index == _photos.length) {
              if (_error) {
                return Center(
                    child: InkWell(
                      onTap: () {
                        setState(() {
                          _loading = true;
                          _error = false;
                          fetchPhotos();
                        });
                      },
                      child: Padding(
                        padding: const EdgeInsets.all(16),
                        child: Text("Error while loading photos, tap to try agin"),
                      ),
                    ));
              } else {
                return Center(
                    child: Padding(
                      padding: const EdgeInsets.all(8),
                      child: CircularProgressIndicator(),
                    ));
              }
            }
            final Photo photo = _photos[index];
            return Card(
              child: Column(
                children: <Widget>[
                  Image.network(
                    photo.thumbnailUrl,
                    fit: BoxFit.fitWidth,
                    width: double.infinity,
                    height: 160,
                  ),
                  Padding(
                    padding: const EdgeInsets.all(16),
                    child: Text(photo.title,
                        style: TextStyle(
                            fontWeight: FontWeight.bold, fontSize: 16)),
                  ),
                ],
              ),
            );
          });
    }
    return Container();
  }

  Future<void> fetchPhotos() async {
    try {
      final response = await http.get("https://jsonplaceholder.typicode.com/photos?_page=$_pageNumber");
      List<Photo> fetchedPhotos = Photo.parseList(json.decode(response.body));
      setState(() {
        _hasMore = fetchedPhotos.length == _defaultPhotosPerPageCount;
        _loading = false;
        _pageNumber = _pageNumber + 1;
        _photos.addAll(fetchedPhotos);
      });
    } catch (e) {
      setState(() {
        _loading = false;
        _error = true;
      });
    }
  }
}

class Photo {
  final String title;
  final String thumbnailUrl;
  Photo(this.title, this.thumbnailUrl);
  factory Photo.fromJson(Map<String, dynamic> json) {
    return Photo(json["title"], json["thumbnailUrl"]);
  }
  static List<Photo> parseList(List<dynamic> list) {
    return list.map((i) => Photo.fromJson(i)).toList();
  }
}

无限滚动答案信用和更多信息Infinite Scrolling ListView

答案 3 :(得分:0)

您可以在ListView.builder

中使用itemCount:snapshot.data.length,

看起来像这样

 ListView.builder(
                itemCount: snapshot.data.length,
                itemBuilder: (BuildContext context, int index) {
                  return Container(
                    child: Text(
                      "${snapshot.data[index]['title']}",
                      style: TextStyle(color: Colors.white),
                    ),
                  );
                });

答案 4 :(得分:0)

这主要发生在您使用错误的索引值从列表中获取数据时。就我而言,我犯了同样的错误。

答案 5 :(得分:-1)

我在GridView中遇到了这个问题,但是与我的GridView无关。我用逗号分隔地址,例如addresses[index].split(',')[0],但是遇到一个没有逗号的地址,这就是为什么我突然收到此错误的原因。在调试控制台中仔细查看,以查找错误的确切行,并测试GridView中的每段代码以查明错误。

答案 6 :(得分:-2)

Widget getListView(){
  var itemList = getListElement();
   var list = ListView.builder(
     itemCount: itemList.length,
       itemBuilder:(context, index){
         return ListTile(
           title: Text(itemList[index]),   
         );
         }
   );
   return list;
}