FutureBuilder with lists

Question

Asked by Lorenzo C on November 06, 2021 (source).

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?

Answer

Question answered by Roslan A (source).

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
  },
);
DART FLUTTER FLUTTER-LAYOUT
SHARE: