How to get data from firebase using child value in flutter? - firebase

I want to retrieve data from firebase via "continent" value
here is my database
this is my code:
DatabaseReference ref = FirebaseDatabase.instance
.reference()
.child("Country/")
.orderByChild("continent")
.equalTo("Asia");
ref.once()
.then((DataSnapshot datasnapshot) {
datalist.clear();
var keys=datasnapshot.value.keys;
var values=datasnapshot.value;
for(var key in keys) {
Country data = new Country(
values[key]['Country'],
values[key]['continent'],
values[key]['Capital'],
);
}
datalist.add(data);
}
what is wrong?

DatabaseReference ref = FirebaseDatabase.instance
.reference()
.child("Country/")
.orderByChild("continent")
.equalTo("Asia");
ref.once()
.then((DataSnapshot snapshot) {
Map<dynamic, dynamic> values = snapshot.value;
values.forEach((key, values) {
print(values["continent"]);
});
});

From the 9.0.0 version of firebase_database, many breaking changes applied. Now its something like:
Query ref = FirebaseDatabase.instance.ref()
.child("Country/")
.orderByChild("continent")
.equalTo("Asia");
ref.once()
.then((DatabaseEvent event) {
if(event.snapshot.value == null) return;
var values = event.snapshot.value;
print(values);
});

Related

How to read read a value from firebase document field

here is the firebase firestore section
how do I read the value 'purchase-id'
this is how I did, but not working
var collection = FirebaseFirestore.instance.collection('users');
final docSnapshot = await collection.doc('$index').get();
Map<String, dynamic> data = docSnapshot.data()!;
final purID = data['purchased-id'];
the value is receiving but as the future value
here is how the value is receiving
final purchaseID = coursePurchaseCheck
but this is a Future value, how do I parse that to normal data
how do I properly get document value from firebase??
Check your index is equal to document key ??
You can get document key with below code:
List<String> _userKey = [];
await fireStore
.collection('user').get()
.then((QuerySnapshot querySnapshot) {
for (var doc in querySnapshot.docs) {
_userKey.add(doc.id);
}
});
And get data below:
for(String _key in _userKey){
await FirebaseFirestore.instance
.collection('user')
.doc(_key)
.get()
.then((DocumentSnapshot documentSnapshot) async {
if (documentSnapshot.exists) {
var data = documentSnapshot.data();
var res = data as Map<String, dynamic>;
final purID = res['purchased-id'];
}
});
}

How can I filter a map / Firestore Flutter

I need to search for data from a map in the "users" collection of a single document. But I only found ways to search all documents.
See below.
Code 1:
FirebaseFirestore.instance
.collection('users')
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((doc) {
Map<String, dynamic> res = doc["favorite"];
});
});
Code 2:
final String _collection = 'users';
final FirebaseFirestore _fireStore = FirebaseFirestore.instance;
getData() async {
return await _fireStore.collection(_collection).get();
}
getData().then((val) {
if (val.docs.length > 0) {
print(val.docs[0].data()["favorite"]);
} else {
print("Not Found");
}
});
Hello you can search in fields:
// Create a reference to the cities collection
var citiesRef = db.collection("cities");
// Create a query against the collection.
var query = citiesRef.where("state", "==", "CA");
See the Firestore queries reference here:
https://firebase.google.com/docs/firestore/query-data/queries

i want to send the data under the userid and also fetch the same data

i am not able to send it under the current userid and also not able to fetch it for current userid.
basically i want to send the data under the userid and also fetch the same data.
So for that i want to change the current document name as the user id. but whenever i do that and i call _sendToServer() in an on pressed button it gives me error.
_sendToServer() {
if (_key.currentState.validate()) {
_key.currentState.save();
DatabaseReference ref = FirebaseDatabase.instance.reference();
final Firestore _db = Firestore.instance;
var data = {
"name": name,
"profession": profession,
"message": message,
};
_db
.collection('Profile')
.document('KoMna0Hv7VXoeABwFTGH7LTo1No2')
.setData(data)
.then((v) {
_key.currentState.reset();
});
}
}
also while fetching data i am not able to do this. as i am getting error in the below code.
fetchUser() async{
Future<List<Text>> getAllProfiles() async {
List<Text> returnList = [];
final Firestore _db = Firestore.instance;
await _db.collection("profile").getDocuments().then((QuerySnapshot snapshot) {
snapshot.documents.forEach((doc) {
var keys = snapshot.value.keys;
var data = snapshot.value;
allData.clear();
for (var key in keys) {
myData d = new myData(
data[key]['name'],
data[key]['message'],
data[key]['profession'],
);
allData.add(d);
}
setState(() {
print('Length : ${allData.length}');
});
});
});
return returnList;
}
}
i must provide these key value pair for fetching the data but unfortunately i am not able to do so.
I have added the orderByChild('id') and equalTo('${user.uid}') filed in the code with firebase user. and i also one more item to my list which is data[key]['id'], my current user id. this way everytime the user tries to fetch the data it will look into the list item for current userid and if it matches it will fetch that particular database only.
#override
// ignore: must_call_super
void initState() {
FirebaseAuth.instance.currentUser().then((user) {
fetchUser(user);
});
}
fetchUser(FirebaseUser user) {
DatabaseReference ref = FirebaseDatabase.instance.reference();
ref
.child('node-name')
.orderByChild('id')
.equalTo('${user.uid}')
.once()
.then((DataSnapshot snap) {
var keys = snap.value.keys;
var data = snap.value;
print(snap.value.toString());
allData.clear();
for (var key in keys) {
myData d = new myData(
data[key]['name'],
data[key]['number'],
data[key]['address'],
data[key]['id'],
data[key]['location'],
data[key]['website'],
);
allData.add(d);
}
setState(() {
print('Length : ${allData.length}');
});
});
}
_sendToServer() async{
FirebaseUser user = await FirebaseAuth.instance.currentUser();
if (_key.currentState.validate()) {
_key.currentState.save();
DatabaseReference ref = FirebaseDatabase.instance.reference();
var data = {
"id": user.uid,
"name": name,
"number": number,
"address": address,
"location":location,
"website":website,
};
ref.child('node-name').child(user.uid).set(data).then((v) {
_key.currentState.reset();
});
} else {
setState(() {
_autovalidate = true;
});
}
}

How to transform the data received from cloud_firestore into a Map

The data from the cloud_firestore database is in the form of JSON. However, how to transform the data from JSON in a List of Map?
The dummy data in my firestore
Data to List of Map:
final CollectionReference ref = Firestore.instance.collection('food');
List<Map<String, dynamic>> listOfMaps = [];
await ref.getDocuments().then((QuerySnapshot snapshot) {
listOfMaps =
snapshot.documents.map((DocumentSnapshot documentSnapshot) {
return documentSnapshot.data;
}).toList();
});
print(listOfMaps);
Just in case if You want to use better way. Parse data to List of Objects:
1) create a model class:
class Food {
String affordability;
String title;
Food.fromJson(Map<String, dynamic> jsonData) {
this.affordability = jsonData['affordability'];
this.title = jsonData['title'];
}
}
2) convert to list of Food:
final CollectionReference ref = Firestore.instance.collection('food');
List<Food> list = [];
await ref.getDocuments().then((QuerySnapshot snapshot) {
list = snapshot.documents.map((DocumentSnapshot documentSnapshot) {
return Food.fromJson(documentSnapshot.data);
}).toList();
});
print(list);

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

Resources