flutter - 无效值:有效值范围为空:0 Flutter
问题描述
我是 Flutter 的初学者,我创建了一个 Flutter 应用程序来显示一些来自 Internet 的数据,我有一个错误提示RangeError (index): Invalid value: Valid value range is empty: 0
了几秒钟,然后这个错误消失了。
这是我尝试过的:
import 'package:flutter/material.dart';
import 'package:footyappp/Key/Key.dart';
import 'package:footyappp/stats/player_goals.dart';
import 'package:footyappp/stats/teams_json.dart';
import 'package:footyappp/tables%20copy/league_board.dart';
import 'package:footyappp/stats/player_assists.dart';
import 'package:footyappp/stats/player_red_cards.dart';
import 'package:footyappp/stats/player_yellow_cards.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'assist_json.dart';
import 'goals_json.dart';
class Statss extends StatefulWidget {
@override
_StatssState createState() => _StatssState();
}
class _StatssState extends State<Statss> {
List<AssistsJson> topassists = [];
List<GoalsJson> topgoals = [];
List<TeamsJson> teams = [];
List<String> data = [];
List<Choices> menu = [];
String assister;
String assisterphoto;
String scorerphoto;
String assists;
String goals;
String scorer;
String teamgoals;
String teamname;
String teamphoto;
String teampoints;
Future<void> getScorers() async {
http.Response response = await http.get(
'https://v3.football.api-sports.io/players/topscorers?league=39&season=2020',
headers: {'x-rapidapi-key': ApiKey.key,
'x-rapidapi-host':'v3.football.api-sports.io'});
String body = response.body;
var data = jsonDecode(body);
List<dynamic> clubList = data['response'];
setState(() {
topgoals = clubList
.map((dynamic item) => GoalsJson.fromJson(item))
.toList();
goals = topgoals[0].statistics[0].goals.total.toString();
scorer = topgoals[0].player.name+" "+topgoals[0].player.firstname;
scorerphoto = topgoals[0].player.photo;
});
}
Future<void> getStandings() async {
http.Response response = await http.get(
'https://v3.football.api-sports.io/standings?league=39&season=2020',
headers: {'x-rapidapi-key': ApiKey.key,
'x-rapidapi-host':'v3.football.api-sports.io'});
String body = response.body;
var data = jsonDecode(body);
List<dynamic> clubList = data['response'];
setState(() {
teams = clubList
.map((dynamic item) => TeamsJson.fromJson(item))
.toList();
teamgoals = teams[0].league.standings[0][0].all.goals.goalsFor.toString()+" "+"Goals";
teamname = teams[0].league.standings[0][0].team.name.toString();
teamphoto = teams[0].league.standings[0][0].team.logo.toString();
teampoints = teams[0].league.standings[0][0].points.toString()+" "+"Pts";
});
}
Future<void> getAssisters() async {
http.Response response = await http.get(
'https://v3.football.api-sports.io/players/topassists?league=39&season=2020',
headers: {'x-rapidapi-key': ApiKey.key,
'x-rapidapi-host':'v3.football.api-sports.io'});
String body = response.body;
var data = jsonDecode(body);
List<dynamic> clubList = data['response'];
setState(() {
topassists = clubList
.map((dynamic item) => AssistsJson.fromJson(item))
.toList();
assists = topassists[0].statistics[0].goals.assists.toString();
assister = topassists[0].player.name+" "+topassists[0].player.firstname;
assisterphoto = topassists[0].player.photo;
});
}
@override
void initState() {
super.initState();
getScorers();
getAssisters();
getStandings();
}
List<String> images = [
"Assets/tt.jpg",
"Assets/qatarairways.jpg",
"Assets/LOGO_Danao.jpg",
"Assets/delice.jpg"
];
@override
Widget build(BuildContext context) {
if(topgoals.isNotEmpty && topassists.isNotEmpty){ this.menu = [
Choices("Top Scorer: ", goals.toString(), topgoals[0].player.name,topgoals[0].player.photo.toString()),
Choices("Top Assister: ", assists.toString(), topassists[0].player.name,topassists[0].player.photo.toString()),
Choices("Top Team Goals ", teamgoals.toString(), "",teamphoto.toString()),
Choices("1 st Team ", teampoints.toString(), "",teamphoto.toString()),
];}
return teams.isEmpty || topassists.isEmpty || topgoals.isEmpty
? Container(
color: Colors.white,
child: Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(
Color(0xFFe70066),
),
),
),
)
: Scaffold(
appBar: AppBar(
title: Text("Stats"),
backgroundColor: Colors.blue[300],
elevation: 0.0,
),
body: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.centerLeft,
end: Alignment.centerRight,
colors: [Colors.purple, Colors.blue])),
child: ListView(
children: [
SizedBox(
height: 20,
),
Container(
margin: EdgeInsets.fromLTRB(10, 0, 0, 0),
child: Text(
"Statistiques",
style: TextStyle(
fontSize: 25,
fontWeight: FontWeight.w900,
color: Colors.white),
),
),
SizedBox(
height: 30,
),
Container(
padding: EdgeInsets.all(12.0),
child: GridView.builder(
shrinkWrap: true,
itemCount: menu.length,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
crossAxisSpacing: 1.0,
mainAxisSpacing: 1.0),
itemBuilder: (BuildContext context, int index) {
return Card(
color: Colors.black,
elevation: 4.0,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0),
),
child: Container(
//padding: EdgeInsets.all(16.0),
child:
Column(
children: <Widget>[
Container(
padding: EdgeInsets.fromLTRB(30, 10, 30, 10),
height: 100,
width: 100,
decoration: BoxDecoration(
shape: BoxShape.circle,
image: DecorationImage(
image: NetworkImage(menu[index].image),
fit: BoxFit.fill
),
),
),
Container(
padding: EdgeInsets.all(7.0),
width: double.infinity,
child:
Center(
child: Text(menu[index].title+" "+menu[index].name,style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.w900,
color: Colors.white),),
)
),
Container(
padding: EdgeInsets.all(7.0),
width: double.infinity,
child: Center(
child: Text(menu[index].record, style: TextStyle(
fontSize: 25,
fontWeight: FontWeight.w900,
color: Colors.white),),
),
),
],
),
),
);
},
),
),
Container(
margin: EdgeInsets.fromLTRB(15, 30, 15, 0),
child: Column(
children: [
SizedBox(
height: 1,
),
ButtonTheme(
minWidth: double.infinity,
height: 40,
child: RaisedButton(
child: Align(
child: Text(
"Top Scorers",
style: TextStyle(fontSize: 17),
textAlign: TextAlign.right,
),
alignment: Alignment.centerLeft,
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Scorers()),
);
},
color: Colors.grey.shade300,
textColor: Colors.black,
padding: EdgeInsets.fromLTRB(15, 8, 8, 8),
splashColor: Colors.green,
shape: RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(30.0))),
),
SizedBox(
height: 1,
),
ButtonTheme(
minWidth: double.infinity,
height: 40,
child: RaisedButton(
child: Align(
child: Text(
"Top Assists",
style: TextStyle(fontSize: 17),
textAlign: TextAlign.right,
),
alignment: Alignment.centerLeft,
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Assists()),
);
},
color: Colors.grey.shade300,
textColor: Colors.black,
padding: EdgeInsets.fromLTRB(15, 8, 8, 8),
splashColor: Colors.green,
shape: RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(30.0))),
),
SizedBox(
height: 1,
),
ButtonTheme(
minWidth: double.infinity,
height: 40,
child: RaisedButton(
child: Align(
child: Text(
"Yellow Cards",
style: TextStyle(fontSize: 17),
textAlign: TextAlign.right,
),
alignment: Alignment.centerLeft,
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => YellowCards()),
);
},
color: Colors.grey.shade300,
textColor: Colors.black,
padding: EdgeInsets.fromLTRB(15, 8, 8, 8),
splashColor: Colors.green,
shape: RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(30.0))),
),
SizedBox(
height: 1,
),
ButtonTheme(
minWidth: double.infinity,
height: 40,
child: RaisedButton(
child: Align(
child: Text(
"Red Cards",
style: TextStyle(fontSize: 17),
textAlign: TextAlign.right,
),
alignment: Alignment.centerLeft,
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => RedCards()),
);
},
color: Colors.grey.shade300,
textColor: Colors.black,
padding: EdgeInsets.fromLTRB(15, 8, 8, 8),
splashColor: Colors.green,
shape: RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(30.0))),
),
SizedBox(
height: 1,
),
ButtonTheme(
minWidth: double.infinity,
height: 40,
child: RaisedButton(
child: Align(
child: Text(
"Team Stats",
style: TextStyle(fontSize: 17),
textAlign: TextAlign.right,
),
alignment: Alignment.centerLeft,
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => LeagueBoard()),
);
},
color: Colors.grey.shade300,
textColor: Colors.black,
padding: EdgeInsets.fromLTRB(15, 8, 8, 8),
splashColor: Colors.green,
shape: RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(30.0))),
),
SizedBox(
height: 30,
)
],
),
),
Container(
padding: EdgeInsets.all(12.0),
child: GridView.builder(
shrinkWrap: true,
itemCount: images.length,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
crossAxisSpacing: 4.0,
mainAxisSpacing: 4.0),
itemBuilder: (BuildContext context, int index) {
return Image.asset(images[index]);
},
),
),
SizedBox(
height: 30,
)
],
),
));
}
}
class Choices {
String title;
String record;
String name;
String image;
Choices(this.title,this.record,this.name,this.image);
}
我正在尝试找出此错误背后的原因并进行修复。为什么此错误显示几秒钟然后消失?任何帮助将不胜感激。
解决方案
这是暂时发生的,因为在给定时刻,在 build 方法中,您要求它查看 index[0],这意味着您告诉 Flutter 此列表中至少有 1 个项目。它返回一个错误,说没有这样的有效索引,并显示红色屏幕,直到您的未来函数完成运行,然后调用setState
,现在该索引处实际上有项目,它不是一个空列表。
为了解决这个问题,您可以在构建依赖它的小部件之前检查您的列表是否为空,如下所示:
myList.isEmpty ? CircularProgressIndicator() : WidgetThatDependsOnTheListNotBeingEMpty()
这也给您带来了问题:
List<Choices> menu = [
Choices("Top Scorer: ", goals.toString(), topgoals[0].player.name,topgoals[0].player.photo.toString()),
Choices("Top Assister: ", assists.toString(), topassists[0].player.name,topassists[0].player.photo.toString()),
Choices("Top Team Goals ", teamgoals.toString(), "",teamphoto.toString()),
Choices("1 st Team ", teampoints.toString(), "",teamphoto.toString()),
];
出于上述相同的原因,您可以将其更改为:
if(topgoals.isNotEmpty && topassists.isNotEmpty) List<Choices> menu = [
Choices("Top Scorer: ", goals.toString(), topgoals[0].player.name,topgoals[0].player.photo.toString()),
Choices("Top Assister: ", assists.toString(), topassists[0].player.name,topassists[0].player.photo.toString()),
Choices("Top Team Goals ", teamgoals.toString(), "",teamphoto.toString()),
Choices("1 st Team ", teampoints.toString(), "",teamphoto.toString()),
];
推荐阅读
- vb.net - 在 Adobe 阅读器工具中显示和查看 pdf 文件
- arrays - 从数组中获取特定索引的值名称
- javascript - 未捕获的 SyntaxError:意外的令牌“导出”-Karma 配置设置-Angular.js 1.x-javascript
- c++ - 指针互转换:reinterpret_cast 派生到 base
- node.js - twilio API 一直发送请求,直到发生套接字挂起错误
- java - 获取 HTTP 状态 406 - 尝试在 Spring REST 控制器中返回对象时出现不可接受的错误
- python - sparks 集群无法找到传递给它的 zip 文件夹中存在的 txt 文件
- python - 如何使用python从大文件中删除特定行?
- django - 在 Django 中将多条记录作为一条读取
- python - 在 matplotlb 上绘制带有 2 个辅助轴变量的组合图