RangeError(索引):无效值:有效值范围为空:0

时间:2019-03-04 06:52:44

标签: flutter

Widget build(context) {
    try{
      if (isFirst == true) {
        fetchImage();
        fetchCategories(context);
        isFirst = false;
      }
    }catch(Exception){

    }

    return MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.black,
        appBar: AppBar(
          title: Text('Lets see images!'),
        ),
        body: new Column(
          children: <Widget>[
            new Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                new InkResponse(
                    child: new Column(
                      children: <Widget>[
                        Padding(
                          padding: EdgeInsets.all(10.0),
                          child: new Image.asset(
                            catimages[0],
                            width: 60.0,
                            height: 60.0,
                          ),
                        ),
                        new Text(
                          categoriesText[0],
                          style: TextStyle(color: Colors.white),
                        ),
                      ],
                    ),
                    onTap: () {
                      debugPrint("on tv clikced");
                      widget.fetchApI.fetchSubCategories(context, 6);
                    }),
                new InkResponse(
                  child: new Column(
                    children: <Widget>[
                      Padding(
                        padding: EdgeInsets.all(10.0),
                        child: new Image.asset(
                          catimages[1],
                          width: 60.0,
                          height: 60.0,
                        ),
                      ),
                      new Text(
                        categoriesText[1],
                        style: TextStyle(color: Colors.white),
                      ),
                    ],
                  ),
                  onTap: () {
                    debugPrint("on moview clicked");
                    widget. fetchApI.fetchSubCategories(context, 7);
                  },
                ),
                new InkResponse(
                  child: new Column(
                    children: <Widget>[
                      Padding(
                        padding: EdgeInsets.all(10.0),
                        child: new Image.asset(
                          catimages[2],
                          width: 60.0,
                          height: 60.0,
                        ),
                      ),
                      new Text(
                       categoriesText[2],
                        style: TextStyle(color: Colors.white),
                      ),
                    ],
                  ),
                  onTap: () {
                    debugPrint("on news clicked");
                    widget.fetchApI.fetchSubCategories(context, 10);
                  },
                ),
                new InkResponse(
                  child: new Column(
                    children: <Widget>[
                      Padding(
                        padding: EdgeInsets.all(10.0),
                        child: new Image.asset(catimages[3],
                            width: 60.0, height: 60.0),
                      ),
                      new Text(
                        categoriesText[3],
                        style: TextStyle(color: Colors.white),
                      ),
                    ],
                  ),
                  onTap: () {
                    debugPrint('on shows clicked');
                    widget.fetchApI.fetchSubCategories(context, 8);
                  },
                ),
                new InkResponse(
                  child: new Column(
                    children: <Widget>[
                      Padding(
                        padding: EdgeInsets.all(10.0),
                        child: new Image.asset('assets/live_icon.png',
                            width: 60.0, height: 60.0),
                      ),
                      new Text(
                        'Live',
                        style: TextStyle(color: Colors.white),
                      ),
                    ],
                  ),
                  onTap: () {
                    debugPrint('on live clicked');
                  },
                ),
              ],
            ),
            ImageList(images,widget.fetchApI),
          ],
        ),
      ),
    );
  }

我正在尝试从API中获取列表,这是两种方法fetchImages和fetchCategories。第一次显示红屏错误,然后2秒钟后自动加载列表。您能告诉我代码中的问题以及如何避免在我的应用中显示红屏错误。

9 个答案:

答案 0 :(得分:3)

问题可能是您正在尝试访问尚未准备就绪的变量/数组(可能是因为future / api调用尚未完成)

一种快速的解决方法是检查数组的长度或检查是否为空,例如:

Text( (myArray?.length > 0 ? myArray[0] : '') );

答案 1 :(得分:1)

确保指定数据列表的长度。例如,如果您使用的是ListView.builder,请为属性itemCount赋予适当的值。

ListView.builder(
            itemCount: snapshot.data.length,
            itemBuilder: (ctx, index) {
              return WidgetItem();
            });

答案 2 :(得分:1)

空安全

错误原因:

在检索 List 中不存在的索引的值时发生此错误。例如:

List<int> list = [];
list[0]; // <-- Error since there's no element at index 0 in the list. 

解决方案:

检查 List 是否不是 null 并且在索引处具有元素:

var myList = nullableList;
var index = 0;
if (myList != null && myList.length > index) {
  myList[index]; // You can safely access the element here. 
}

答案 3 :(得分:0)

如果您要从API提取数据,请考虑使用FutureBuilder

答案 4 :(得分:0)

有个简单而又正确的答案

快捷方式

使用list?.elementAt(<index>) ?? ""安全访问列表元素

Widget build(context) {
    try{
      if (isFirst == true) {
        fetchImage();
        fetchCategories(context);
        isFirst = false;
      }
    }catch(Exception){

    }

    return MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.black,
        appBar: AppBar(
          title: Text('Lets see images!'),
        ),
        body: new Column(
          children: <Widget>[
            new Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                new InkResponse(
                    child: new Column(
                      children: <Widget>[
                        Padding(
                          padding: EdgeInsets.all(10.0),
                          child: new Image.asset(
                            catimages?.elementAt(0) ?? "",
                            width: 60.0,
                            height: 60.0,
                          ),
                        ),
                        new Text(
                          categoriesText?.elementAt(0) ?? "",
                          style: TextStyle(color: Colors.white),
                        ),
                      ],
                    ),
                    onTap: () {
                      debugPrint("on tv clikced");
                      widget.fetchApI.fetchSubCategories(context, 6);
                    }),
                new InkResponse(
                  child: new Column(
                    children: <Widget>[
                      Padding(
                        padding: EdgeInsets.all(10.0),
                        child: new Image.asset(
                          catimages?.elementAt(1) ?? "",
                          width: 60.0,
                          height: 60.0,
                        ),
                      ),
                      new Text(
                        categoriesText?.elementAt(1) ?? "",
                        style: TextStyle(color: Colors.white),
                      ),
                    ],
                  ),
                  onTap: () {
                    debugPrint("on moview clicked");
                    widget. fetchApI.fetchSubCategories(context, 7);
                  },
                ),
                new InkResponse(
                  child: new Column(
                    children: <Widget>[
                      Padding(
                        padding: EdgeInsets.all(10.0),
                        child: new Image.asset(
                          catimages?.elementAt(2) ?? "",
                          width: 60.0,
                          height: 60.0,
                        ),
                      ),
                      new Text(
                       categoriesText?.elementAt(2) ?? "",
                        style: TextStyle(color: Colors.white),
                      ),
                    ],
                  ),
                  onTap: () {
                    debugPrint("on news clicked");
                    widget.fetchApI.fetchSubCategories(context, 10);
                  },
                ),
                new InkResponse(
                  child: new Column(
                    children: <Widget>[
                      Padding(
                        padding: EdgeInsets.all(10.0),
                        child: new Image.asset(catimages?.elementAt(3) ?? "",
                            width: 60.0, height: 60.0),
                      ),
                      new Text(
                        categoriesText?.elementAt(3) ?? "",
                        style: TextStyle(color: Colors.white),
                      ),
                    ],
                  ),
                  onTap: () {
                    debugPrint('on shows clicked');
                    widget.fetchApI.fetchSubCategories(context, 8);
                  },
                ),
                new InkResponse(
                  child: new Column(
                    children: <Widget>[
                      Padding(
                        padding: EdgeInsets.all(10.0),
                        child: new Image.asset('assets/live_icon.png',
                            width: 60.0, height: 60.0),
                      ),
                      new Text(
                        'Live',
                        style: TextStyle(color: Colors.white),
                      ),
                    ],
                  ),
                  onTap: () {
                    debugPrint('on live clicked');
                  },
                ),
              ],
            ),
            ImageList(images,widget.fetchApI),
          ],
        ),
      ),
    );
  }
}

正确答案

坦率地说,如果我回顾这段代码,即使它可以无缝运行,我也会拒绝此更改,因为该代码使用的结构/模式非常糟糕。

请改用FutureBuilderStreamBuilderValueListenableBuilder,但您需要提供更多代码(尤其是fetchImagefetchCategories)以帮助我们。

答案 5 :(得分:0)

如果您正在fetchApI方法中获取数据,我假设您是从fetch ApI方法中获取数据。那么你应该遵循这个

fetchApI并且为asynchronous方法,因此从json获取数据需要花费时间,并且在乞求的fetchApI为空的情况下,因此会产生范围错误。 您可以使用asynchronousawait *创建fetchApI方法async,并在调用该方法时使用.then方法然后访问值。

fetchApI().then((){ // access fetchApI over here });

答案 6 :(得分:0)

如果其他方法不起作用,请检查您的数据库是否包含任何冲突的数据条目。如果是这样,请修复它们。

答案 7 :(得分:-1)

您没有获取数据。缺少数据文件夹或数据源。我也一样。后来,我创建了用于数据的json文件并指向该位置。并简单地将其修复!

答案 8 :(得分:-1)

对我来说,转到项目目录并运行命令flutter clean修复了错误

相关问题