Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to fix the error while getting data from snapshot?

i have this function

UserData _userDataFromSnapshot(DocumentSnapshot snapshot) {
    return UserData(
      uid: uid,
      userName: snapshot.data()['userName'],
      userEmail: snapshot.data['userEmail'],
      phoneNumber: snapshot.data['phoneNb']
    );
  }

but im getting error on the paranthesis

The operator '[]' isn't defined for the type 'Object'.

updateee for the question

also i have the function and instance of collection

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

final CollectionReference users = FirebaseFirestore.instance.collection('users');

 // get user doc stream
  Stream<UserData> get userData {
    return users.doc(uid).snapshots()
      .map(_userDataFromSnapshot);
  }

when i read data:

Widget profile(context, user){
    return StreamBuilder<UserData>(
      stream: DatabaseService(uid: user.uid).userData,
      builder: (context, snapshot) {
        if(snapshot.hasData){
          UserData userData = snapshot.data;
          print(userData.userName);
         } else print('no data');
      }
     );
}

what can i do?

im using versions:

Flutter 2.0.1 • channel stable • https://github.com/flutter/flutter.git
Framework • revision c5a4b4029c (1 year, 1 month ago) • 2021-03-04 09:47:48 -0800
Engine • revision 40441def69
Tools • Dart 2.12.0

>Solution :

You are approaching to the data in two different ways. One of them (which is the first one) is correct but the other ways are wrong. Once you have the document snapshot, get the data out of it and use it as an assigning mechanism.

You can try the code below.

For more information –> https://firebase.flutter.dev/docs/firestore/usage/

UserData _userDataFromSnapshot(DocumentSnapshot document) {
    final data = document.data()! as Map<String, dynamic>;
    return UserData(
      uid: uid,
      userName: data['userName'],
      userEmail: data['userEmail'],
      phoneNumber: data['phoneNb']
    );
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading