Home > database >  Can't store data in a list using flutter firebase
Can't store data in a list using flutter firebase

Time:01-31

i'm trying to store data coming from the cloud firestore into a list. I'm getting the following error: _CastError (type '_Map<String, dynamic>' is not a subtype of type 'String' in type cast). Actually I was able to print the objects separately ( {id: mR1TZTI1yzdUzXYXuRXOZwGJS363, type: PP SANS RDV} ). But I couldn't parse the type field and save it into a list.

Here is my code:

StreamBuilder(
                      stream: FirebaseFirestore.instance
                          .collection('type')
                          //.where('userId', isEqualTo: user!.uid)
                          .snapshots(),
                      builder:
                          (context, AsyncSnapshot<QuerySnapshot> snapshot) {
                        if (snapshot.hasData) {

                          
                          List<Object?> data = snapshot.data!.docs.map((e) {
                            return e.data();
                          }).toList();

                          //Map<dynamic, dynamic> type = data[0] as Map;

                          data.forEach(
                            (element) {
                              print(element);
                            },
                          );

The print statement shows each object separately, but whenever I try to parse them:

print(jsonDecode(element as String);  // error.

I appreciate your help.

CodePudding user response:

Try this

 List<Map<String,dynamic>> data = snapshot.data!.docs.map((e) {
                            return e.data() as Map<String,dynamic>;
                          }).toList();

I hope it helps

  • Related