Home > database >  Flutter: querying firebase realtime database data list with streambuilder error
Flutter: querying firebase realtime database data list with streambuilder error

Time:01-04

iam trying to show list of data using StreamBuilderbut when i run this code it give me an error:

error image here

database image here

i am fallowing this youtube video and i am trying to show data list i need to do this using streambuilder

DatabaseReference starCountRef =
      FirebaseDatabase.instance.ref('/Shop/qw1234/Inventory/');

 Expanded(child:StreamBuilder(
            stream: starCountRef.onValue,
            builder: (context,AsyncSnapshot<DatabaseEvent> snapshot){
              if(snapshot.hasData){
                return ListView.builder(
                    itemCount: snapshot.data!.snapshot.children.length,
                    itemBuilder: (context,index){
                     Map<dynamic, dynamic> map =
                            snapshot.data!.snapshot.value as dynamic;
                        List<dynamic> list = [];
                        list.clear();
                        list = map.values.toList();
                      return ListTile(
                        title: Text('data'),
                      );
                    });
              }else{
return Text("no");
              }

            },
          )
          )

CodePudding user response:

The keys in your database are sequential numeric value (i.e. 1, 2, 3), which the Firebase SDK interprets as the data being an array and thus exposing it as a List to your Flutter code.

So the proper way to get the values is:

List list = snapshot.data!.snapshot.value as List;

Note that the list will not have any item at index 0, was that is missing in your source data too.

In general, it's recommended to not use such sequential numeric keys in Firebase, as it results in counterintuitive behavior at times. For more on this, and how to properly store lists of data in Firebase, see Best Practices: Arrays in Firebase.

  • Related