"The operator '[]' isn't defined" error when using .data[] in flutter firestore

Viewed 24196

I am learning to use firestore in flutter following Net Ninja's tutorial on youtube. After user authenticatin was done this guy added user records to the database whenever a new user is created, for doing this a new model was added passing 1 String named "name" and from what I undertstood for calling that he mapped the model and then used .data['name'] to get that string from the model(string was called name) and when doing this, I got the error The operator '[]' isn't defined for the type 'Map<String, dynamic> Function()' Why am I getting this error?

username model

class Username {
  final String name;
  Username({ this.name });
}

databse.dart file (the following code is wrapped in a class called DatabaseService)

  List<Username> _usernameListFromSnapshot(QuerySnapshot snapshot) {
    return snapshot.docs.map((doc){
      return Username(
        name: doc.data['name'] ?? '',
      );
    }).toList();
  }

auth.dart

  Future registerWithEmailAndPassword(String email, String password) async {
    try {
      UserCredential result = await _auth.createUserWithEmailAndPassword(email: email, password: password);
      User user = result.user;

      // create a new document for the user with uid
      await DatabaseService(uid: user.uid).updateUserData('user123');
      return _userFromFirebaseUser(user);
    } catch(e) {
      print(e.toString());
      return null;
    }
  }

if you have any questions or need to see more code, please let me know in the comments

6 Answers

For me, worked like this:

return snapshot.docs.map((doc) {
  return Todo(
    // before
    title: doc.data()['title'],
    // after
    title: (doc.data() as dynamic)['title'],
  );
}).toList();

In pubspec.yaml:

environment:
  sdk: ">=2.12.0 <3.0.0"
...
cloud_firestore: ^2.3.0
firebase_core: ^1.3.0

Firestore's data used to be a property of QueryDocumentSnapshot, but now it is a function, data().

And, as the error message suggests, what you are dealing with is indeed a Map<String, dynamic> Function(), i.e. a function that returns a map.

So, simply add empty parentheses to call the function data:

doc.data()['name']
messageText = message['text'];

This syntax should work with any updated plugins you use.

StreamBuilder<QuerySnapshot>(
          stream: _fireStore.collection('messages').snapshots(),
          builder: (context, snapshot){
            if(!snapshot.hasData){
              return Center(
                child: CircularProgressIndicator(
                // ignore: missing_return
                backgroundColor: Colors.lightBlueAccent,
                ),
              );
            }
            final messages = snapshot.data.docs;
            List<Text> messageWidgets = [];
            for(var message in messages){
              final messageText = message.data()['text'];
              final messageSender = message.data()['sender'];
              final messageWidget = Text('$messageText from $messageSender');
              messageWidgets.add(messageWidget);
            }

            return Column(
              children: messageWidgets,
            );
          }
        ),

yes, you should try message['text']

Related