how to fix the "The operator '[]' isn't defined for the type 'Object'" error while getting data from snapshot?

Issue

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

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']
    );
  }

Answered By – salihgueler

Answer Checked By – David Marino (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *