简体   繁体   中英

How do I get the key of a value in FirebaseDatabase using Flutter / Dart?

I'm trying to get the key of a child that I've already returned from the database. In the example below, I have the user selected as Carlos Sainz and I'm trying to get "csainz" however the code below returns "email".

    DatabaseReference keyRef = FirebaseDatabase.instance.reference();
    await keyRef.child('users')
        .child('email')
        .equalTo(userList[0].email) // userList[0].email returns Carlos' email
        .once()
        .then((DataSnapshot dataSnapshot) {
          String newKey = dataSnapshot.key;
          print(newKey);
    });

Here is how my db is setup: 在此处输入图像描述

Two problems:

  1. To order/filter on a specific property of each child node, you need to use orderByChild(...) and not just child(...) . Right now your code reads /users/email , which doesn't exist.

  2. When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.

    Your code doesn't handle the list, but prints the key of the location against which the query was executed: users .

So to fix both would look something like this:

DatabaseReference keyRef = FirebaseDatabase.instance.reference();
await keyRef.child('users')
    .orderByChild('email')
    .equalTo(userList[0].email)
    .onChildAdded.listen((Event event) {
      print('${event.snapshot.key}');
    }, onError: (Object o) {
      final DatabaseError error = o;
      print('Error: ${error.code} ${error.message}');
    });
});

You can also use .once().then(...) but will then have convert dataSnapshot.value to a map, and show the key(s) from that map. Not check, but it should be something like this:

DatabaseReference keyRef = FirebaseDatabase.instance.reference();
await keyRef.child('users')
    .orderByChild('email')
    .equalTo(userList[0].email)
    .once()
    .then((DataSnapshot dataSnapshot) {
      String newKey = dataSnapshot.value.keys[0];
      print(newKey);
    });

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