Flutter Reading firebase

Viewed 41

I am following this tutorial so that i can read the data of an event https://petercoding.com/firebase/2020/02/16/using-firebase-queries-in-flutter/ I went to the Reading data section "Retrieving The Firebase Data in a ListView"

I pasted the code in my code and i cannot find in the tutorial where should i create the "lists" list. Can anyone tell me what list should i define so it works?

    FutureBuilder(
  
future: databaseReference.once(),
builder: (context, AsyncSnapshot<DataSnapshot> snapshot) {
  
    if (snapshot.hasData) {
    lists.clear();
    Map<dynamic, dynamic> values = snapshot.data.value;
    values.forEach((key, values) {
        lists.add(values);
    });
    return new ListView.builder(
        shrinkWrap: true,
        itemCount: lists.length,
        itemBuilder: (BuildContext context, int index) {
            return Card(
            child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                Text("Name: " + lists[index]["name"]),
                Text("Age: "+ lists[index]["age"]),
                Text("Type: " +lists[index]["type"]),
                ],
            ),
            );
        });
    }
    return CircularProgressIndicator();
}),

https://gyazo.com/bc6769b8b515919a67030682987d0b85

1 Answers

You haven't provided the full code of your widget class, so I can't give you the best place for the variable. Try declaring variable named lists List lists = [] in your class. I have declared it in your builder. It will work here as well. But better make it a field of your class.

FutureBuilder(
      
    future: databaseReference.once(),
    builder: (context, AsyncSnapshot<DataSnapshot> snapshot) {
      List lists = []; //Just add this line
        if (snapshot.hasData) {
        lists.clear();
        Map<dynamic, dynamic> values = snapshot.data.value;
        values.forEach((key, values) {
            lists.add(values);
        });
        return new ListView.builder(
            shrinkWrap: true,
            itemCount: lists.length,
            itemBuilder: (BuildContext context, int index) {
                return Card(
                child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                    Text("Name: " + lists[index]["name"]),
                    Text("Age: "+ lists[index]["age"]),
                    Text("Type: " +lists[index]["type"]),
                    ],
                ),
                );
            });
        }
        return CircularProgressIndicator();
    }),
Related