Slow data loading from firebase causing “RangeError (index)”

此生再无相见时 提交于 2021-02-11 06:11:37

问题


Here i am trying to load image link from firebase into flutter app then passing it into image.network(). the data loading is taking time to load data so it is giving me following error: RangeError (index): Invalid value: Valid value range is empty: 1 but after 5 second the data is loaded successfully and printed in console but not displayed on screen. here is code to print data

class _DataFetching extends State<MyHomePage> {

  List<eyes> allCriminals=eyes.allcriminals();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(

        title: Text("fetch"),
      ),
      body: Center(

        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[

            new Image.network(allCriminals[1].link
            ),

           ]// This trailing comma makes auto-formatting nicer for build methods.
    )));

  }
}

and function to load data from firebase is

 static  List<eyes> allcriminals() {
    var allEyes = new List<eyes>();
    Future<Query>  queryUsers() async{
      return await FirebaseDatabase.instance
          .reference()
          .child('Facial Parts/Eyes');
    }
    queryUsers().then((query) {
      query.once().then((snapshot) {
        var result =  snapshot.value.values as Iterable;
        for (var item in result) {
          print(result);
           allEyes.add(new eyes(criminal_id: item["criminal_id"],
              eye_size: item["eyesize"],
              link: item["link"]));

        print(item['link']);
        }

      });
    });
    return allEyes;
  }

is there any method that can help me to load all data and after that it should go to Widget build()?


回答1:


Data is loaded from Firebase asynchronously. By the time your return allEyes runs, the .then() from the database hasn't run yet. And you can't return something now that hasn't been loaded yet.

That's why you'll have to return a Future<List<eyes>>, which is a promise to have a list of eyes at some point in the future.

static Future<List<eyes>> allcriminals() {
  var query = FirebaseDatabase.instance.reference().child('Facial Parts/Eyes');

  return query.once().then((snapshot) {
    var allEyes = new List<eyes>();
    var result = snapshot.value.values as Iterable;
    for (var item in result) {
       allEyes.add(new eyes(criminal_id: item["criminal_id"],
          eye_size: item["eyesize"],
          link: item["link"]));
    }
    return allEyes;
  });
}

Then you can use that in your render method by either using a FutureBuilder or by directly calling setState().



来源:https://stackoverflow.com/questions/62320383/slow-data-loading-from-firebase-causing-rangeerror-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!