Add Future function to iterable List

Hey guys. I’ve some issue with my code. I have this future function
Future<List> getSliders() async {
** var data = await http.get(url);**
** var jsonData = json.decode(data.body);**
** List list = [];**
** for(var s in jsonData){**
** list.add(HomeSlider(slideImage: s[“slideImage”], title: s[“title”],isHD: s[“isHD”]));**
** }**
** // print(list.length);**
** return list;**
}
And here is my List : final mSliderList = List();
when I’m ty to add the function to list like this:mSliderList.addAll(getSliders());
i always get this error : The argument type ‘Future<List>’ can’t be assigned to the parameter type ‘Iterable’. please need the help.

You must await the list:
mSliderList.addAll(await getSliders())

1 Like

Thanks for your answer. I’ve tried but there is an other issue.
the function is called inside a state function like : ** getData() {
setState(() async {
mSliderList.addAll(await getSliders());
mMovieList.addAll(getUpcomingMovie());
mCinemaMovieList.addAll(getTop10());
mcontinueList.addAll(getContinueMovies());
mTrendingMuviList.addAll(getTrendingOnMovie());
mMadeForYouList.addAll(getMadeForYouMovie());
});
}**

I hade that error

The error message tells you the cause and how to fix it.

So I don’t understand, and how to go about it.

For example you can do:

getSliders().then((sliders) {
  setState(() {
    mSliderList.addAll(sliders);
    // ...
  });
});

Or:

var sliders = await getSliders();
setState(() {
  mSliderList.addAll(sliders);
  // ...
});

Thanks, I’ve tried : getSliders().then((sliders) {
setState(() {
mSliderList.addAll(sliders);
// …
});
});

now it’s working.

1 Like

In your code you are returning future value, so directly you can not assign this in any veriable so you have two option for that :
1.

 getSliders().then((list) {
   setState(() {
     mSliderList.addAll(list);
   });
 }).error((error){....});
var list = await getSliders();
setState(() {
  mSliderList.addAll(list);
});