简体   繁体   中英

How can I read the data in firebase with flutter

I tried some things but I cant read the data. I'm a beginner in flutter and I have to do a project that it shows the data in firebase. Can you show a beginner project that it only shows the datas in direbase?

I tried this too but this code have some errors on await (how it's possible I copied this from flutter official site)

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);

Thanks for replys I checked the await keyword and correct them (I think) But I dont know how to print this Can you show me that too And I edited code to this =>

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;
}

Wherever you're calling the GetData method you need to await it...or if it is a widget which needs to display data after fetching it from firebase you can wrap it with a future builder.

I hope this solves your problem, if it still doesn't, post with the specific error you're getting.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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