Juan Martin Zabala
Juan Martin Zabala

Reputation: 801

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

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

Upvotes: 21

Views: 28353

Answers (7)

Benjamin Inemugha
Benjamin Inemugha

Reputation: 76

You can tag doc.data() as dynamic and use it. So that your code can look like this

// brew list from snapshot
  List<Brew> _brewListFromSnapshot(QuerySnapshot snapshot) {
    return snapshot.docs.map((doc) {
      dynamic data = doc.data();

      return Brew(
          name: data['name'] ?? '',
          sugars: data['sugar'] ?? '0',
          strength: data['strength'] ?? 0);
    }).toList();
  }

Upvotes: 1

Tiku Brenda Gaelle
Tiku Brenda Gaelle

Reputation: 1

messageText = message['text'];

This syntax should work with any updated plugins you use.

Upvotes: 0

Felipe Sales
Felipe Sales

Reputation: 1139

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

Upvotes: 13

Nilesh Sahu
Nilesh Sahu

Reputation: 11

yes, you should try message['text']

Upvotes: -1

Muhammad Saqib Aziz
Muhammad Saqib Aziz

Reputation: 84

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,
            );
          }
        ),

Upvotes: -1

Anis R.
Anis R.

Reputation: 6912

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']

Upvotes: 7

Peter Haddad
Peter Haddad

Reputation: 80914

Change this:

name: doc.data['name'] ?? '' 

Into this:

name: doc.data()['name'] ?? '' 

data() is a method now therefore you have to add (), from the source code:

  Map<String, dynamic> data() {
    return _CodecUtility.replaceDelegatesWithValueInMap(
        _delegate.data(), _firestore);
  }

https://github.com/FirebaseExtended/flutterfire/blob/master/packages/cloud_firestore/cloud_firestore/lib/src/document_snapshot.dart#L38

Upvotes: 65

Related Questions