“未定义运算符'[]'”;在flutter firestore中使用.data []时出错 [英] "The operator '[]' isn't defined" error when using .data[] in flutter firestore

查看:36
本文介绍了“未定义运算符'[]'”;在flutter firestore中使用.data []时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据Net Ninja在youtube上的教程,我正在学习在扑朔迷离中使用Firestore。在完成用户身份验证之后,只要创建新用户,此人便将用户记录添加到数据库中,为此,通过传递1个名为 name的字符串来添加新模型。从我对调用的理解中,他映射了模型,然后使用.data ['name']从模型中获取该字符串(字符串称为name),并且在执行此操作时,出现错误没有为类型 Map< String,dynamic>定义运算符 [] Function()'为什么会出现此错误?

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

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

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

这篇关于“未定义运算符'[]'”;在flutter firestore中使用.data []时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆