Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Flutter 无效值:有效值范围为空:0_Flutter_Dart - Fatal编程技术网

Flutter 无效值:有效值范围为空:0

Flutter 无效值:有效值范围为空:0,flutter,dart,Flutter,Dart,我是颤振初学者,我创建了一个颤振应用程序来显示一些来自互联网的数据,我有一个错误,上面写着RangeError(index):无效值:有效值范围为空:0 持续几秒钟,然后出现此错误 以下是我尝试过的: import 'package:flutter/material.dart'; import 'package:footyappp/Key/Key.dart'; import 'package:footyappp/stats/player_goals.dart'; imp

我是颤振初学者,我创建了一个颤振应用程序来显示一些来自互联网的数据,我有一个错误,上面写着
RangeError(index):无效值:有效值范围为空: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);
    
    }
导入“包装:颤振/材料.省道”;
导入“包:footyappp/Key/Key.dart”;
导入“包:footyappp/stats/player_goals.dart”;
导入“package:footyappp/stats/teams_json.dart”;
导入“包装:footyappp/表格%20份/联盟板.dart”;
导入“套装:footyappp/stats/player_assesss.dart”;
导入“套装:footyappp/stats/player_red_cards.dart”;
导入“套装:footyappp/stats/player_yellow_cards.dart”;
导入“dart:convert”;
将“package:http/http.dart”导入为http;
导入“assist_json.dart”;
导入“goals_json.dart”;
类Statss扩展StatefulWidget{
@凌驾
_StatssState createState()=>\u StatssState();
}
类_StatssState扩展状态{
名单

我正试图找出这个错误背后的原因并加以纠正。 为什么这个错误会出现几秒钟然后消失?
任何帮助都将不胜感激。

这是暂时的,因为在给定的时刻,在构建方法中,您要求它查看索引[0],这意味着您正在告诉Flatter此列表中至少有一个项目。它返回一个错误,表示没有此类有效索引,并显示红色屏幕,直到您的未来函数完成运行,并调用
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()),
         ];
列表菜单=[
选项(“顶级得分手:”,goals.toString(),topgoals[0]。player.name,topgoals[0]。player.photo.toString()),
选项(“Top Assister:”,assists.toString(),topassists[0]。player.name,topassists[0]。player.photo.toString()),
选项(“顶级团队目标”、teamgoals.toString()、“”、teamphoto.toString()),
选项(“第一团队”,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()),
         ];
if(topgoals.isNotEmpty&&topassists.isNotEmpty)列表菜单=[
选项(“顶级得分手:”,goals.toString(),topgoals[0]。player.name,topgoals[0]。player.photo.toString()),
选项(“Top Assister:”,assists.toString(),topassists[0]。player.name,topassists[0]。player.photo.toString()),
选项(“顶级团队目标”、teamgoals.toString()、“”、teamphoto.toString()),
选项(“第一团队”,teampoints.toString(),”,teamphoto.toString()),
];

这是暂时发生的,因为在给定的时刻,在构建方法中,您要求它查看索引[0],这意味着您正在告诉Flatter此列表中至少有一个项目。它返回一个错误,表示没有此类有效索引,并显示红色屏幕,直到您的未来函数完成运行,并调用
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()),
         ];
列表菜单=[
选项(“顶级得分手:”,goals.toString(),topgoals[0]。player.name,topgoals[0]。player.photo.toString()),
选项(“Top Assister:”,assists.toString(),topassists[0]。player.name,topassists[0]。player.photo.toString()),
选项(“顶级团队目标”、teamgoals.toString()、“”、teamphoto.toString()),
选项(“第一团队”,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()),
         ];
if(topgoals.isNotEmpty&&topassists.isNotEmpty)列表菜单=[
选项(“顶级得分手:”,goals.toString(),topgoals[0]。player.name,topgoals[0]。player.photo.toString()),
选项(“Top Assister:”,assists.toString(),topassists[0]。player.name,topassists[0]。player.photo.toString()),
选项(“顶级团队目标”、teamgoals.toString()、“”、teamphoto.toString()),
选项(“第一团队”,teampoints.toString(),”,teamphoto.toString()),
];

您要构建小部件的任何位置,该位置取决于列表是否为空。这将防止错误屏幕或您的应用程序引发错误。因为如果此列表为空,它将构建加载微调器,而不是依赖于列表的小部件。您可以在任何位置使用此微调器,而不仅仅是在此代码中。并且
myList
下面是一个示例n example name.Bro,你是认真的吗?这也是一个假的\example name,你用造成问题的实际小部件替换它!我在更新后编辑了你的帖子,现在检查。现在尝试代码,看看错误是否仍然发生。我也为你修复了它,现在检查。Youc ant use
Statss()
像这样。调试它。stackoverflow不是这样工作的。试着找出错误是什么,你最终会找到它。此外,每篇文章都应该包含一个问题,到目前为止,我们已经有三个问题了。任何你想构建小部件的地方,这取决于列表是否为空。这将防止错误屏幕或你的应用程序抛出错误。Bec因为如果这个列表是空的,它将构建一个加载微调器,而不是依赖于列表的小部件。你可以在任何地方使用它,而不仅仅是在这个代码中。还有
myList
这里是一个示例名称。兄弟,你是认真的吗?这也是一个假的\示例名称,你用你的实际小部件替换它,这是造成问题的原因!我编辑了你的帖子更新后,现在检查。现在尝试代码,看看错误是否仍然发生