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
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
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With