“未定义运算符‘[]’";在 flutter firestore 中使用 .data[] 时出错 [英] "The operator '[]' isn't defined" error when using .data[] in flutter firestore
问题描述
我正在按照 youtube 上的 Net Ninja 教程学习在 flutter 中使用 firestore.完成用户身份验证后,每当创建新用户时,这个人都会将用户记录添加到数据库中,为此,添加了一个新模型,传递 1 个名为name"的字符串.根据我对调用他映射模型的理解,然后使用 .data['name'] 从模型中获取该字符串(字符串被称为 name),在执行此操作时,我收到错误 The operator '[]' 没有为类型 'Map
为什么我会收到这个错误?
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?
用户名模型
class Username {
final String name;
Username({ this.name });
}
databse.dart 文件(以下代码封装在一个名为 DatabaseService 的类中)
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
推荐答案
改变这个:
name: doc.data['name'] ?? ''
进入这个:
name: doc.data()['name'] ?? ''
data()
现在是一种方法,因此您必须从源代码中添加 ()
:
data()
is a method now therefore you have to add ()
, from the source code:
Map<String, dynamic> data() {
return _CodecUtility.replaceDelegatesWithValueInMap(
_delegate.data(), _firestore);
}
这篇关于“未定义运算符‘[]’";在 flutter firestore 中使用 .data[] 时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!