简体   繁体   中英

Why aren't I creating a widget with the information from the RTDB?

I don't understand why my code isn't creating the post. It should access the RTDB and put name1 and name2 into a new card that says "'name1' and 'name2'" but it only gives me a post that says "and". Here is the following code:

Post addPost() {
    DatabaseReference db = FirebaseDatabase.instance.reference();
    String name1;
    String name2;
    db
        .child('users')
        .child(FirebaseAuth.instance.currentUser.uid)
        .once()
        .then((DataSnapshot snap) {
      Map<dynamic, dynamic> values = snap.value;
      if (snap.value == null) {
        print("No data");
      }
      name1 = values['name1'];
      name2 = values['name2'];
    });
    return Post(
      name1: name1,
      name2: name2,
    );
  }

Any help is appreciated. Thank you in advance!

If you run the code in a debugger, or add some print statements, you will see that your return Post( name1: name1, name2: name2,); runs before the name1 = values['name1'];ever executes.

That's because data is loaded from Firebase (and most cloud APIs) asynchronously, and your main code (the return statement) continues to execute while the data is loaded. Then when the data is available, the callback block is executed. But at that point, nobody will see the assignment to name1 and name2 anymore.

The solution is to return a Future<Post> instead of just Post and using async and await :

Future<Post> addPost() async {
    DatabaseReference db = FirebaseDatabase.instance.reference();
    String name1;
    String name2;
    var snap = await db
        .child('users')
        .child(FirebaseAuth.instance.currentUser.uid)
        .once();
    Map<dynamic, dynamic> values = snap.value;
    if (snap.value == null) {
      print("No data");
    }
    name1 = values['name1'];
    name2 = values['name2'];
    return Post(
      name1: name1,
      name2: name2,
    );
}

Also see:

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