Flutter RangeError(索引):无效值:有效值范围为空:存在列表数据时为0



所以我创建了这个小部件,即进行API调用,然后用接收到的数据填充Listview.Builder。出于某种原因,它只显示前13个结果(端点返回20个结果(,然后抛出我收到的错误。我有确切的小部件布局和API调用(虽然指向不同的端点,但响应是相同的(,它工作得很好,显示了所有20个结果。我是不是做错了什么?当我在API调用后检查变量的长度时,它显示它包含所有20个项目,并且我已经将每个项目单独打印到控制台。现在几乎被难住了。也相当于一个供参考的颤动角落:(

import 'package:flutter/material.dart';
import 'package:testapp/widgets/movie_card.dart';
import 'package:http/http.dart' as http;
import 'dart:convert' as cnv;
class TvShows extends StatefulWidget {
const TvShows({Key? key}) : super(key: key);
@override
_TvShowsState createState() => _TvShowsState();
}
class _TvShowsState extends State<TvShows> {
List tvShows = [];
@override
void initState() {
getPopularShows();
super.initState();
}
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(border: Border.all(color: Colors.black)),
height: 400,
child: ListView.builder(
scrollDirection: Axis.horizontal,
shrinkWrap: true,
itemCount: tvShows.length,
itemBuilder: (context, index) {
return MovieCard(
overview: tvShows[index]["overview"],
id: tvShows[index]["id"].toString(),
index: index,
title: tvShows[index]["name"],
rating: tvShows[index]["vote_average"].toString(),
imageUrl: tvShows[index]["poster_path"],
genreId: tvShows[index]["genre_ids"][0].toString(),
);
}),
);
}
void getPopularShows() async {
final params = {
"api_key": "apikey",
"language": "en-US",
"page": "1"
};
Uri url = Uri.https('api.themoviedb.org', '/3/tv/popular', params);
http.Response res = await http.get(url);
var body = cnv.jsonDecode(res.body);
body["results"].forEach((value) {
tvShows.add(value);
});
}
}

我解决了它。发现这是一个后端错误。与此代码无关。:(

我是平台新手,但你在容器中做了一个条件如果(tvShows==0({返回容器(progressIndicator(;

)其他的{您的集装箱在这里}

Use This  

ListView.builder(
scrollDirection: Axis.horizontal,
shrinkWrap: true,
itemCount: tvShows.length,
itemBuilder: (context, index) {
return tvShows.length > 0 ? MovieCard(
overview: tvShows[index]["overview"],
id: tvShows[index]["id"].toString(),
index: index,
title: tvShows[index]["name"],
rating: tvShows[index]["vote_average"].toString(),
imageUrl: tvShows[index]["poster_path"],
genreId: tvShows[index]["genre_ids"][0].toString(),
) :  CircularProgressIndicator();
}),

最新更新