How to retrieve value of child data from firebase DB? - firebase

I am trying to grab the children data from a certain movie title in a database, but I can only get an output of "Instance of Datasnapshot."
Here is the setup of the DB with the highlighted information I am trying to store in a list:
I tried using the following code with no success:
Future<List<String>> getMovieDetails(String movieName) async {
DataSnapshot movies = await DBRef.child("Movies").child(movieName).once().then((DataSnapshot datasnapshot)
{
print(datasnapshot.value.toString());
});
var moviesMap = Map<String, dynamic>.from(movies.value);
List<String> moviesList = [];
moviesMap.forEach((key, value){
moviesList.add(key);
print('My-Key $key');
print('Movie List: $moviesList');
});
return moviesList;
}
Note: I am passing the selected movie name so I only grab the child information from the movie the user selects. This portion is correctly, if the user clicks on the list tile of Batman, the title will be passed to this getMovieDetails() function.

Try the following:
Future<List<String>> getMovieDetails(String movieName) async {
DataSnapshot movies = await FirebaseDatabase.instance
.reference()
.child("Movies")
.child(movieName)
.once();
var moviesMap = Map<String, dynamic>.from(movies.value);
List<String> moviesList = [];
moviesMap.forEach((key, value) {
moviesList.add(value);
print('My-Key $key');
print('My-Value $value');
});
return moviesList;
}
}
You dont have to use then() since you are using await. Also when you call this method, you need to do for example:
await getMovieDetails("Batman");

I will make the above answer as correct, but the biggest issue was when I did:
moviesList.add(key)
When it should be:
moviesList.add(value)

Related

Flutter firebase get a field from document

I'm trying to get the message from a field in a collection. It is a read only data, i have modeled it like this
class SocialShare {
final String message;
SocialShare({
this.message,
});
factory SocialShare.fromJson(Map<String, dynamic> json) {
return SocialShare(
message: json['message'],
);
}
}
I have a collection named 'Social Share and contains a doc with a single field called message..
Here is how i call it
class SocialShares {
final CollectionReference _socialMessage =
FirebaseFirestore.instance.collection('socialShare');
Future<SocialShare> fetchsocial() {
return _socialMessage.get().then((value) {
return SocialShare.fromJson(value); // how can i call it
});
}
}
How can i get a that value from firebase
You can do fetchSocial async and await the result to return:
fetchSocial() async{
var value = await _socialMessage.get();
return SocialShare.fromJson(value);
}
then you have to call fetchSocial method with await or then where you need it.
await fetchSocial() or fetchSocial.then ...
The value in _socialMessage.get().then((value) { is a QuerySnapshot object, which contains the DocumentSnapshots of all documents in the socialShare collection.
To get a field, or the Map<String, dynamic> of all fields, you need the data from a single document. For example, to get the message field fro the first document from the collection, you can do:
return SocialShare.fromJson(value.docs[0].data());

How do I get the surrounding data related to my userId using flutter and firebase

While using flutter I am able to successfully get the UserId, however I want to be able get more user data (using the UserId)
Surrounding Information:
With the userId how would I go about printing the users; name bio, membership... etc?
Since you are using Realtime Database, then to get the other data, you can do the following:
db = FirebaseDatabase.instance.reference().child("Users");
db.once().then((DataSnapshot snapshot){
Map<dynamic, dynamic> values = snapshot.value;
values.forEach((key,values) {
print(values);
print(values["name"]);
});
});
First add a reference to node Users then use the forEach method to iterate inside the retrieved Map and retrieve the other values.
Try like this :
Future<dynamic> getWeightinKeg() async {
final DocumentReference document = Firestore.instance.collection('you_collection_name').document(user_id);
await document.get().then<dynamic>(( DocumentSnapshot snapshot) async {
final dynamic data = snapshot.data;
print(data['name'].toString())
//Do whatever you want to do with data here.
});
}
getUsers() async {
//here fbPath is reference to your users path
fbPath.once().then((user){
if(user.value !=null){
Map.from(user.value).forEach((k,v){
//here users is List<Map>
setState((){
users.add(v);
});
}
}
});
}
//Or
getUsers() async {
//here fbPath is reference to your users path
//and userListener is StreamSubscription
userListener = fbPath.onChildAdded.listen((user){
//here users is List<Map>
setState((){
users.add(Map.from(user.snapshot.value));
});
});
}
//and cancel in dispose method by calling
userListener.cancel();

Flutter: Get Firebase Database reference child all data

I have a firebase database child which content is like below:
How to retrieve this in flutter?
My Current code:
static Future<Query> queryUsers() async{
return FirebaseDatabase.instance
.reference()
.child("zoom_users")
.orderByChild('name');
}
queryUsers().then((query){
query.once().then((snapshot){
//Now how to retrive this snapshot? It's value data giving a json
});
});
To retrieve the data try the following:
db = FirebaseDatabase.instance.reference().child("zoom_users");
db.once().then((DataSnapshot snapshot){
Map<dynamic, dynamic> values = snapshot.value;
values.forEach((key,values) {
print(values["name"]);
});
});
Here first you add the reference at child zoom_users, then since value returns data['value'] you are able to assign it to Map<dynamic, dynamic> and then you loop inside the map using forEach and retrieve the values, example name.
Check this:
https://api.dartlang.org/stable/2.0.0/dart-core/Map/operator_get.html
Flutter: The method forEach isn't defined for the class DataSnapshot
query.once().then((snapshot){
var result = data.value.values as Iterable;
for(var item in result) {
print(item);
}
});
or with async that you already use
var snapshot = await query.once();
var result = snapshot.value.values as Iterable;
for(var item in result) {
print(item);
}

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

flutter firebase how do I get all the children of a node

I am not very familiar with using dart and firebase and I was wondering how I could get all the children of a certain node and how I could check if a node exists
Something like this should you get the list of users:
static Future<int> getUserAmount() async {
final response = await FirebaseDatabase.instance
.reference()
.child("Users")
.once();
var users = [];
reponse.value.forEach((v) => users.add(v));
print(users);
return users.length;
}
You can check with users what you need to check and then return a result;
If you want only the name of the parentes of the example bellow:
https://i.stack.imgur.com/NjxbJ.png
I'd use the code of Günter Zöchbauer with a little modification. The result will be: user = [A,B,C,D,E,LIVRE] with 5 length size.
Future getUserAmount() async
{
final database = await FirebaseDatabase.instance
.reference()
.child("CHILD1/ana/exercicios/")
.once();
List <String> users = [];
database.value.forEach((key,values) => users.add(key));
print(users);
print(users.length);
}

Resources