【问题标题】:How can I read the data in firebase with flutter如何使用颤振读取 Firebase 中的数据
【发布时间】:2022-02-09 22:48:54
【问题描述】:

我尝试了一些东西,但我无法读取数据。我是颤振的初学者,我必须做一个项目来显示firebase中的数据。你能展示一个只显示 direbase 中数据的初学者项目吗?

我也试过了,但是这段代码在等待时有一些错误(我怎么可能从flutter官方网站复制了这个)

import 'package:firebase_database/firebase_database.dart';
DatabaseReference ref = FirebaseDatabase.instance.ref("users/123");
// Get the data once
DatabaseEvent event = await ref.once();
// Print the data of the snapshot
print(event.snapshot.value);

感谢您的回复我检查了 await 关键字并更正了它们(我认为) 但我不知道如何打印这个 你也可以给我看吗 我为此编辑了代码=>

Future<Object?> GetData() async {
  FirebaseDatabase database = FirebaseDatabase.instance;

  DatabaseReference ref = FirebaseDatabase.instance.ref("litre");

// Get the data once
  DatabaseEvent event = await ref.once();

// Print the data of the snapshot
  print(event.snapshot.value); // { "name": "John" }
  return event.snapshot.value;
}

【问题讨论】:

  • 这对我来说非常重要。我是 10 年级
  • 您可以使用await 关键字等待future 和async 方法的结果,您是否在正确的地方使用它?请检查此链接:dart.dev/codelabs/async-await
  • 请编辑您的问题以包含您遇到的错误。
  • @mahmoud_eslami 如何使用 Text() 函数打印此方法的返回值?

标签: firebase flutter dart firebase-realtime-database


【解决方案1】:

无论您在哪里调用 GetData 方法,您都需要等待它……或者如果它是一个小部件,需要在从 firebase 获取数据后显示数据,您可以用未来的构建器包装它。

我希望这可以解决您的问题,如果仍然没有,请发布您遇到的具体错误。

FutureBuilder(
    future: GetData(),
    builder: (context, snapshot) {
      if (snapshot.connectionState == ConnectionState.waiting) {
        return Center(
          child: CircularProgressIndicator(),
        );
      } else {
        if (snapshot.error != null) {
          return Center(
            child: Text('An error occured'),
          );
        } else {
          return Text(snapshot.data); // Or whatever widget you want to return or display
        }
      }
    },
  ),

【讨论】:

    猜你喜欢
    • 2022-06-27
    • 1970-01-01
    • 2021-01-06
    • 2022-10-06
    • 2019-01-01
    • 2021-02-16
    • 2021-06-30
    • 2022-11-12
    • 2019-06-11
    相关资源
    最近更新 更多