Home > OS >  Flutter how to show list from firebase in list view
Flutter how to show list from firebase in list view

Time:11-26

I am getting a list from firebase in a StreamBuilder widget. I want to show it in a ListView widget but it doesn't work.

enter image description here

Here is my code:

final current = document.data as Map<String, dynamic>;
final activities = current["activities"] as List;
List titles = activities.map((e) => e["title"]).toList();
List av = activities.map((e) => e["days"]).toList();

ListView.builder(
  shrinkWrap: true,
  itemCount: av.elementAt(i).length,
  itemBuilder: (context, index) {
    return ListTile(
      title: Text(av.elementAt(i)[0][index]),
    );
  },
),

What am I doing wrong?

CodePudding user response:

I don't know if I understand the question correctly, but if you are trying to load data from Firestore in a ListView, you should wrap it inside a StreamBuilder, that opens a stream to the Firestore-Collection and displays the data as a ListView. If I understood your question correctly, the code would look something like this:

StreamBuilder(
stream: myFirestoreStream,
builder: (context, AsyncSnapshot snapshot) {
    if (snapshot.hasData) {
        return ListView.builder(
            shrinkWrap: true,
            itemCount: av.elementAt(i).length,
            itemBuilder: (context, index) {
                return ListTile(
                title: Text(av.elementAt(i)[0][index]),
                );
            },
        );
    } else {
        return CircularProgressIndicator();
    }
}
),

CodePudding user response:

All the variables such as these

final current = document.data as Map<String, dynamic>;
final activities = current["activities"] as List;
List titles = activities.map((e) => e["title"]).toList();
List av = activities.map((e) => e["days"]).toList();

needs to be loaded once the data from firestore is recieved.
So, following would be your code:

 StreamBuilder(
            stream: _firestoreStream, //use .snapshot() to get data
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                final current = snapshot.data as Map<String, dynamic>;
                final activities = current["activities"] as List;
                List titles = activities.map((e) => e["title"]).toList();
                List av = activities.map((e) => e["days"]).toList();

                return ListView.builder(
                  shrinkWrap: true,
                  itemCount: av.elementAt(i).length,
                  itemBuilder: (context, index) {
                    return ListTile(
                      title: Text(av.elementAt(i)[0][index]),
                    );
                  },
                );
              } else {
                return const CircularProgressIndicator();
              }
            }),
  • Related