Flutter - FutureBuilder with firestore
1 min read

Flutter - FutureBuilder with firestore

FutureBuilder could be used to render content that will be loaded in the future. For example, a firestore document query. It requires a Future such as a firebase document query and a builder to render widget based on the received data and state.

 FutureBuilder<DocumentSnapshot<Map<String, dynamic>>>(
          future:
              firestore.collection("trips").doc("UEIN8zcoMx0JV9KVYSVN").get(),
          builder: (context, snapshot) {
            if (snapshot.hasError) {
              return const Text("Error in loading trip details");
            }

            if (snapshot.connectionState == ConnectionState.done &&
                snapshot.hasData) {
              var data = snapshot.data?.data() as Map<String, dynamic>;
              return Text(data["title"]);
            }

            return const Text("Loading data");
          },
        )
FutureBuilder<DocumentSnapshot<Trip>>(
          future: firestore
              .collection("trips")
              .doc("UEIN8zcoMx0JV9KVYSVN")
              .withConverter(fromFirestore: ((snapshot, options) {
            return Trip.fromJson(snapshot.data()!);
          }), toFirestore: (Trip trip, _) {
            return trip.toJson();
          }).get(),
          builder: (context, snapshot) {
            if (snapshot.hasError) {
              return const Text("Error in loading trip details");
            }

            if (snapshot.connectionState == ConnectionState.done &&
                snapshot.hasData) {
              var data = snapshot.data?.data();
              return Text(data!.title);
            }

            return const Text("Loading data");
          },
        )

If you have a custom model with fromJson andtoJson methods, withConverter method can be used to work with type safe objects.