Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A simple Query in flutter/firebase database

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

enter image description here

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

like image 263
Jérôme Bonjour Avatar asked May 23 '18 14:05

Jérôme Bonjour


People also ask

How do I get data from firestore database in Flutter?

How to get all data from a Firestore collection in flutter? Call the getDocs() function, then use the build function, then print all the document IDs in the console. Here is how you do it! Get all data from the collection that you found working, without using deprecated methods.


1 Answers

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);
like image 159
Renaud Tarnec Avatar answered Nov 08 '22 20:11

Renaud Tarnec