gariaable
gariaable

Reputation: 177

Retrive data from Firebase Firestore to List<Object>

I have found a lot of solutions of how to retrive data from Firebase to Widget or with usage of async methods, although I am not able to use it for my case. I want to use flutter_week_view from https://pub.dev/packages/flutter_week_view and in order to pass events from database I need to populate them to List<FlutterWeekViewEvent> events. I have tried the approach with StreamBuilder, but it creates a ListView widget and that's not what I intend to do:

StreamBuilder(
              stream: FirebaseFirestore.instance.collection('Test').snapshots(),
              builder: (context, snapshot) {
                if (!snapshot.hasData) return const Text('Loading..');
                return ListView.builder(
                    itemExtent: 80.0,
                    itemCount: snapshot.data.documents.length,
                    itemBuilder: (context, index) => Text(snapshot
                        .data.documents[index]
                        .get('name')
                        .toString()));
              })

I had also tried other approach:

  Future<List<FlutterWeekViewEvent>> retriveRecords() async {
  List<FlutterWeekViewEvent> events = [];
  DateTime now = DateTime.now();

  QuerySnapshot querySnapshot =
      await FirebaseFirestore.instance.collection("Test").get();
  for (int i = 0; i < querySnapshot.docs.length; i++) {
    var a = querySnapshot.docs[i];

    DateTime start = DateTime(now.year, now.month, now.day, now.hour - 7);
    events.add(FlutterWeekViewEvent(
      title: a.get('name'),
      start: start,
      end: start.add(const Duration(hours: 2)),
      backgroundColor: Colors.red,
      description: 'bla bla',
    ));
  }
  return events;
}

But in this case my problem is that I wanted to fill event list in build() method and it's not working, since retriveRecords is anync method.

Any help appreciated! I am begginer at Flutter.

Upvotes: 0

Views: 994

Answers (3)

Chichebe
Chichebe

Reputation: 598

Let me know if it works...

StreamBuilder(
  stream: FirebaseFirestore.instance.collection('Test').snapshots(),
  builder: (context, snapshot) {

    if (!snapshot.hasData) {
      return const Text("Loading");
    } else if (snapshot.hasData && snapshot.connectionState == ConnectionState.active) {
      List<QueryDocumentSnapshot> documentSnapshot = snapshot.data.documents;

      List<FlutterWeekViewEvent> events = [];

      for(QueryDocumentSnapshot doc in queryDocumentSnapshot) {
        
        DateTime start = DateTime(now.year, now.month, now.day, now.hour - 7);

        final flutterWeekViewEvent = FlutterWeekViewEvent(
          title: doc.data()["name"],
          start: start,
          end: start.add(const Duration(hours: 2)),
          backgroundColor: Colors.red,
          description: "bla bla",
        );

        events.add(flutterWeekViewEvent);
      }

    }
    return ListView.builder(
        itemExtent: 80.0,
        itemCount: event.length,
        itemBuilder: (context, index) {
          /// I got this part from the package
          return DayView (
            date: now,
            event: events,
          );

        }
      );
  });

Upvotes: 0

Sergio
Sergio

Reputation: 30735

You can call your async function retriveRecords() in FutureBuilder. It will wait for it to finish:

FutureBuilder<List<FlutterWeekViewEvent>>(
          future: retriveRecords(),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              List<FlutterWeekViewEvent> weekEvents = snapshot.data;
              return DayView(
                       date: DateTime.now(),
                       events: weekEvents,
              );
            }

            return const Text('Loading..');
          },
        )

Upvotes: 1

Mehmet Yaz
Mehmet Yaz

Reputation: 305

Try replace From : a.get(name); To : a.data[name]

Upvotes: 0

Related Questions