A simple Query in flutter/firebase database

2020-06-06 04:38发布

问题:

I try to experience Firebase Live database with flutter. I just would like to get a value in the datasnapshot of the firebase response.

My Firebase

My Code

static Future<User> getUser(String userKey) async {
Completer<User> completer = new Completer<User>();

String accountKey = await Preferences.getAccountKey();

FirebaseDatabase.instance
    .reference()
    .child("accounts")
    .child(accountKey)
    .child("users")
    .childOrderBy("Group_id")
    .equals("54")
    .once()
    .then((DataSnapshot snapshot) {
  var user = new User.fromSnapShot(snapshot.key, snapshot.value);
  completer.complete(user);
});

return completer.future;
  }
}

class User {
  final String key;
  String firstName;

  Todo.fromJson(this.key, Map data) {
    firstname= data['Firstname'];
    if (firstname== null) {
      firstname= '';
    }
  }
}

I got Null value for firstname. I guess I should navigate to the child of snapshot.value. But impossible to manage with foreach, or Map(), ...

Kind regards, Jerome

回答1:

You are querying with a query and the documentation for Queries (here in JavaScript, but it is valid for all languages), says that "even when there is only a single match for the query, the snapshot is still a list; it just contains a single item. To access the item, you need to loop over the result."

I don't know exactly how you should loop, in Flutter/Dart, over the children of the snapshot but you should do something like the following (in JavaScript):

  snapshot.forEach(function(childSnapshot) {
    var childKey = childSnapshot.key;
    var childData = childSnapshot.val();
    // ...
  });

and assuming that your query returns only one record ("one single match"), use the child snapshot when you do

var user = new User.fromSnapShot(childSnapshot.key, childSnapshot.value);


回答2:

This will give you Users in reusable dialog. There might be slight disservice to yourself if you don't use stream and stream-builders, the solution below is a one time fetch of the users' collection on FirebaseDB.

class User {
  String firstName, groupID, lastName, pictureURL, userID;

  User({this.firstName, this.groupID, this.lastName, this.pictureURL, this.userID});
  factory User.fromJSON(Map<dynamic, dynamic> user) => User(firstName: user["Firstname"], groupID: user["Group_id"], lastName: user["Lastname"], pictureURL: user["Picturelink"], userID: user["User_id"]);
}

Future<List<User>> users = Firestore.instance.collection("users").snapshots().asyncMap((users) {
  return users.documents.map((user) => User.fromJSON(user.data)).toList();
}).single;