繁体   English   中英

运算符“[]”没有为类型“Object”定义。 尝试为 Flutter 定义运算符“[]”

[英]The operator '[]' isn't defined for the type 'Object'. Try defining the operator '[]' for Flutter

我试图将我的数据库值存储到 class 中,但我无法使用 DataSnapshot 将其转换为我的 class。 我已经添加了所有必要的 null 安全操作员。 但它仍然显示错误。

class User {
  String userID = "";
  String name = "";
  String phoneNo = "";
  String email = "";
  String password = "";

  User(
      {required this.userID,
      required this.name,
      required this.phoneNo,
      required this.email,
      required this.password});

  User.fromSnapshot(DataSnapshot dataSnapshot) {
    userID = dataSnapshot.key!;
    if (dataSnapshot.value != null) {
      name = dataSnapshot.value!["name"] as String;
      email = dataSnapshot.value!['email'];
      phoneNo = dataSnapshot.value!['phone'];
      password = dataSnapshot.value!['password'];
    }
  }
}

我正在尝试将快照值定义为字符串,但也与其他值相同。

错误信息

尝试指定您的 DataSnapshot 的类型:

  User.fromSnapshot(DataSnapshot<Map<String,dynamic>> dataSnapshot) {
        userID = dataSnapshot.key!;
        if (dataSnapshot.value != null) {
          name = dataSnapshot.value!["name"] as String;
          email = dataSnapshot.value!['email'];
          phoneNo = dataSnapshot.value!['phone'];
          password = dataSnapshot.value!['password'];
        }
      }

尝试

if (dataSnapshot.value != null) {
      final data = dataSnapshot.value as Map;
      name = data["name"] as String;
      email = data['email'] as String;
      phoneNo = data['phone'] as String;
      password = data['password'] as String;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM