如何用 flutter 读取 firebase 中的数据

How can I read the data in firebase with flutter

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

我也试过了,但是这个代码在 await 上有一些错误(我怎么可能从 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;
}

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

我希望这能解决您的问题,如果仍然没有解决,post 请根据您遇到的特定错误。

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
        }
      }
    },
  ),