Home > Back-end >  FutureBuilder with lists
FutureBuilder with lists

Time:11-07

This is the future function I want to call:

Future<List<Marker>> getMarkers() async {
  List<Marker> markerTemp = [];
  List<String> friendsList = [];
  QuerySnapshot snapshot = FireStoreUtils.getFriendsList(current.userID);
  for (var doc in snapshot.docs) {
    friendsList.add(doc.reference.id);
  }
  for (var friend in friendsList) {
    DocumentSnapshot document = await locationRef.doc(friend).get();
    MarkerTemp.add(Marker(...))
  }
  return markerTemp;
}

Now I want it to be called in FutureBuilder widget to save the results in a variable called markerList that is useful for my view. How can I do?

I'm pretty sure it's a stupid question but I couldn't find the exact answer on web

CodePudding user response:

Your future builder, when the future finishes in your case, returns a list of markers. Now to use that list, you don't have to store it again, it's already returned and stored in your snapshot in your future builder. You can validate this by printing the length of it:

if(snapshot.hasData) print(snapshot.data.length.toString());

CodePudding user response:

return FutureBuilder<List<Marker>>(
  future: getMarkers(),
  builder: (context, snapshot) {
    if (snapshot.connectionState != ConnectionState.done) {
      // async call has not finished
      return const Center(child: CircularProgressIndicator());
    }
    if (snapshot.hasError) {
      // getMarkers() throws an exception
      return Center(child: Text(snapshot.error.toString()));
    }
    if (!snapshot.hasData) {
      // getMarkers() returns null
      return const Center(child: Text("getMarkers() returns null!"));
    }
    markerList = snapshot.data as List<Marker>; // cast to List<Marker>
    return SomeWidget(); // use markerList in this Widget
  },
);
  • Related