简体   繁体   English

在 Flutter 上读取从 Firebase 更改的值

[英]Read values that change from Firebase on Flutter

I want to read and display values from my Firebase realtime database on flutter.我想在 flutter 上读取和显示我的 Firebase 实时数据库中的值。 I have managed to read and display a value from my database, but it won't get updated on my app when it's changed.我已经设法从我的数据库中读取并显示一个值,但是当它发生变化时它不会在我的应用程序上更新。 I think I have to use onValue(), but I can't get it working using it.我想我必须使用 onValue(),但我无法使用它来工作。

I am using a future builder to display the data on my app, would I need it using onValue()?我正在使用未来的构建器在我的应用程序上显示数据,我需要它使用 onValue() 吗?

Future getVolumesFirst() async {
  final ref = FirebaseDatabase.instance.ref();
  final snapshot = await  ref.child('path').get();
  if (snapshot.exists) {
    print(snapshot.value);
    return snapshot.value;
  } else {
    print('No data available.');
  }
}

When you call get() you indeed get the value only once, and it doesn't monitor for updates.当您调用get()时,您确实只获得一次值,并且它不监视更新。 The Firebase documentation contains a pretty good example of listening for updates : Firebase 文档包含一个很好的侦听更新示例:

DatabaseReference starCountRef =
        FirebaseDatabase.instance.ref('posts/$postId/starCount');
starCountRef.onValue.listen((DatabaseEvent event) {
    final data = event.snapshot.value;
    updateStarCount(data);
});

Alternatively, you can just use onValue (without listen ) and use that value in a StreamBuilder .或者,您可以只使用onValue (不使用listen )并在StreamBuilder中使用该值。

Also see:另见:

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

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