【问题标题】:Accessing the last child of a child in firebase real time database访问firebase实时数据库中孩子的最后一个孩子
【发布时间】:2021-11-16 22:30:03
【问题描述】:

我想在实时数据库访问某个孩子中的最后一个孩子

(这个孩子)

我尝试使用此代码,但它在访问 snapshot.value 时返回 {-MkHrcId8EfYpqFWqNrw: {Sender: 97205********, message: hello}},但在尝试访问 snapshot.value['message'] 时返回 null

  Future<String> getLastMessage() async{
    final ref = FirebaseDatabase.instance.reference();
    String RoomId; // RoomId is the name of the first child, the one that starts with 587 in the image
    String lastMessage;
    lastMessage = await ref.child(RoomId).orderByKey().limitToLast(1).once().then((snapshot) {
      snapshot.value['message'];
    return lastMessage;
    });

【问题讨论】:

  • 代码乍一看还不错。您可以在 then() 回调中 print(snapshot.value) 并编辑您的问题以显示更新的代码及其输出吗?
  • 代码在打印snapshot.value时实际上返回{-MkHrcId8EfYpqFWqNrw: {Sender: 97205********, message: hello}},但在尝试打印snapshot.value['message']时返回null@Frank van Puffelen

标签: flutter dart firebase-realtime-database


【解决方案1】:

基于@Frank van Puffelen 的回答,最终解决方案是这样的

lastMessage = await ref.child(RommId).orderByKey().limitToLast(1).once().then((snapshot) {
       return (snapshot.value.values).toList()[0]['message'];
    });

【讨论】:

  • 根据我的信息写出你自己的答案而不至少赞成我的答案是相当不寻常的。 ¯_(ツ)_/¯
【解决方案2】:

当您对 Firebase 数据库执行查询时,可能会有多个结果。所以快照包含这些结果的列表。即使只有一个结果,快照也会包含一个结果列表。

因此,您的回调需要处理该列表,方法是循环其子项(在 snapshot.value.valuesiirc 中),或者直接使用 snapshot.value.toList()[0]['message'] 访问第一个条目。

【讨论】:

  • 对于value 似乎没有一个名为values 的方法(它没有出现在建议中)但是无论如何输入它时它都会返回({Sender: 97205********, message: hello}) 但现在我是无法访问message,因为使用['message] 返回异常“未处理的异常:NoSuchMethodError:类'_CompactIterable'没有实例方法'[]'。”
  • 这意味着您仍然缺少我提到的循环。您需要从列表/地图中获取第一项,并且循环或[0] 是您可以使用的两个选项。
猜你喜欢
  • 2021-08-15
  • 2017-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多