flutter - RangeError(索引):无效值:使用异步功能,有效值范围为空

标签 flutter asynchronous dart index-error

我正在尝试遍历List<ClassName>,以便以后可以从中检索数据。
Future<List<ClassName>> _getValues() async函数内的json文件中检索数据。
问题是,当我启动应用程序时,我收到“RangeError(索引):无效值:有效值范围为空:-1”,但过了一会儿,屏幕显示了正确的信息。
我是Flutter的新手,但据我了解,迭代最初是通过一个空列表进行的。
这是我提到的功能:

  Future<List<CountryData>> _getValues() async {
var countriesData = List<CountryData>();
var data = await http
    .get("https://opendata.ecdc.europa.eu/covid19/casedistribution/json");

var jsonData = json.decode(data.body);

for (var i in jsonData["records"].toList()) {
  countriesData.add(CountryData.fromJson(i));
}

return countriesData;
}
这是我设置列表状态的地方:
List<CountryData> _countriesData = List<CountryData>();
void initState() {
_getValues().then((value) {
  setState(() {
    _countriesData.addAll(value);
  });
});
super.initState();
}
这是我从上述列表中获取数据的地方:
int findState(String code) {
var index = _countriesData.length;
for (int i = 0; i < index; i++) {
  if (_countriesData[i].alpha3Code == (code)) {
    return i;
  }
}
return -1;
}
这是我要显示的地方:
Widget build(BuildContext context) {
return Scaffold(
...
...
body: ListView(children: <Widget>[
      Text(_countriesData[findState(code)]])))
CountryData类为:
class CountryData{
String alpha3Code;
String day;
String month;
String year;
CountryData(this.alpha3Code, this.day, this.month,this.year);
CountryData.fromJson(Map<String, dynamic> json){
      this.day = json['day'];
      this.month = json['month'];
      this.year = json['year'];
      this.alpha3Code = json['alpha3Code'];
      }
 }
现在,如果您需要更多信息,请让我。谢谢

最佳答案

您的问题是,在拥有要显示的数据之前,构建方法正在运行。一种解决方法是使用“isLoading”标志,该标志在http调用之前设置为true,并在返回数据时设置为false(并调用setState)。在构建方法中,您检查标志并在标志为true时显示进度指示器。当它变为false时,显示您的ListView。

关于flutter - RangeError(索引):无效值:使用异步功能,有效值范围为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62968444/

相关文章:

flutter - 在 Dart 中使用 "this"关键字是什么意思?

flutter - 分段条列表动态

flutter - 如何在 flutter 中获得这种单选按钮

ios - 将 TikTok 的 iOS 登录套件与 Flutter 结合使用

php - React PHP 如何处理异步非阻塞 I/O?

node.js - meteor 方法不起作用

javascript - 对抛出错误的异步代码和同步代码进行基准测试

flutter - Dart 的广播流中的 forEach 会泄漏吗?

flutter - 如何更改 flutter showAboutDialog 中的文本按钮颜色?

gradle - 如何在离线模式下使用 gradle 运行 flutter 应用程序?