firebase - argumnet 类型 'Null Funcion(DataSnapshot)

我有一个给我错误的函数。

getCurrentOnLineUserInfo 函数正在尝试从当前登录用户的 Firebase 数据库中读取数据。

The argument type 'Null Funcion(DataSnapshot)' can't be assigned to the parameter of type 'Future Or Function(DataBaseEvent)'

我正在学习一年前的教程,所以问题可能是代码太旧了。我可能需要新语法或其他东西。

static void getCurrentOnLineUserInfo() async {
    firebaseUser = await FirebaseAuth.instance.currentUser;
    String userId = firebaseUser!.uid;
    DatabaseReference reference =
        FirebaseDatabase.instance.ref().child("user").child(userId);

    print("getCurrentOnLineUser info executed!");

    print('${firebaseUser!.email}${firebaseUser!.displayName}');
    
    // errors below this

    reference.once().then((DataSnapshot dataSnapshot) {
      if (dataSnapShot!.value != null) {
        userCurrentInfo = Users.fromSnapshot(dataSnapshot);
      }
    });

  }
}

这是我正在分配数据的类(class)。这个类没有给出错误

class Users {
  String? id;
  String? email;
  String? phone;
  String? name;

  Users({this.id, this.email, this.phone, this.name});

  Users.fromSnapshot(DataSnapshot dataSnapshot) {
    id = dataSnapshot.key!;

    var data = dataSnapshot.value as Map?;

    if (data != null) {
      email = data?["email"];
      name = data?["name"];
      phone = data?["phone"];
    }
  }
}

最佳答案

once 方法返回一个 DatabaseEvent,而不是一个 DataSnapshotDatabaseEvent 是一个类,封装了一个DataSnapshot AND一个DatabaseEventType,要提取快照,必须使用数据库事件.快照:

reference.once().then((event) {
  final dataSnapshot = event.snapshot;
  if (dataSnapShot!.value != null) {
    userCurrentInfo = Users.fromSnapshot(dataSnapshot);
  }
});

这是我认为可以满足您要求的另一种解决方案:

// async methods should return a future
static Future<void> getCurrentOnLineUserInfo() async {
    firebaseUser = await FirebaseAuth.instance.currentUser;
    String userId = firebaseUser!.uid;
    DatabaseReference reference =
        FirebaseDatabase.instance.ref().child("user").child(userId);

    final snapshot = await reference.get(); // you should use await on async methods
    if (snapshot!.value != null) {
      userCurrentInfo = Users.fromSnapshot(snapshot);
    }
  }
}

关于firebase - argumnet 类型 'Null Funcion(DataSnapshot)' 不能分配给参数类型 'Future Or <dynamic> Function(DataBaseEvent)',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70585172/

相关文章:

c++ - std::unordered_map 如何确定哈希表中特定键的位置?

kotlin - 为什么 Kotlin 不提示歧义?为什么要调用辅助构造函数?

c# - 如何将字符串拆分为包含前一个最后一个字符的两个字符的字符串数组?

c++ - 自动占位符类型和显式模板类型在 C++20 中是否等效?

websocket - 将 Nextjs 部署到 Vercel 的 SocketIO,套接字未连接

python - 小列表的长排列

javascript - 如何在 react 中更改 useState 的对象值?

r - 有没有一种方法可以将列添加到函数形式的数据框中

r - 如何将多列连接成一列并删除重复项?

c++ - 这个 'for' 循环与键盘记录器有什么关系?