如何使用flutter检查Firebase实时数据库中的特定节点中是否存在特定密钥



我正在尝试使用flutter检查Firebase实时数据库中的特定节点中是否存在特定密钥。代码:

var pSnapshot = FirebaseDatabase.instance
.reference()
.child('Parents')
.child(currentUId)
.key;
if (pSnapshot == currentUId) {
print(pSnapshot);
print(currentUId);
print("Key & UID Match in Parents");
// redirect to Parents
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (BuildContext context) =>
ParentProfile(),
),
);
}

我将每个用户存储在一个密钥下,该密钥也是他们注册时的用户id。

我想说的是,如果当前登录用户的id作为"Parents"中的密钥存在,那么这意味着用户是父用户,因此我将把他们重定向到父页面。

这不起作用,你知道如何处理这种情况吗?

您的代码还没有从数据库中读取任何内容。

检查路径上是否存在值的唯一方法是从数据库中读取该路径上的数据(例如,通过调用once(),然后检查快照是否有值。

来自我现有的项目:

var snapshot = await _db.child("accessTokens").child(token).once();
if (snapshot.value != null) {
...
}

我也遇到了同样的问题,这是我的解决方案,每当用户登录时,我都试图存储额外的用户信息,但随后我需要检查用户id是否存在,然后如果用户存在,则转到主页,如果用户不存在,则创建用户信息,这是进行检查的代码

Future getUserInRtdb() async {
var snapshot =
await rootRef.child(FirebaseAuth.instance.currentUser!.uid).once();
print(snapshot.snapshot.exists); 
// this print statement returns false if the child is not found
// returns true if the child is found
}

在未来的构建器中使用它可以很好地进行检查

最新更新