How to convert to JSON Format Realtime Database Flutter - flutter

I managed to get one data from Firebase Realtime Database. This time I want to turn it into JSON format and get two data at least. Below is the code
my Database Reference
`
DatabaseReference ref =
FirebaseDatabase.instance.ref().child('UsersData/$userDataUID/test/int');
my code `
StreamBuilder(
stream: ref.onValue,
builder: (context, snapshot) {
if (snapshot.hasData) {
debugPrint(snapshot.data?.snapshot.value.toString());
}
return const CircularProgressIndicator();
})),
my Firebase console
I believe I have to convert it into Maps? I have no idea how to begin with

Try with
DatabaseReference ref =
FirebaseDatabase.instance.ref().child('UsersData/$userDataUID/test');
This will return a map with those fields.
And use on widget like
if (snapshot.hasData) {
final map = snapshot.data?.snapshot.value as Map?;
return Text("int: ${map?["int"]} voltage: ${map?["voltage"]}"); }
Find more about getting data

Related

Firestore query returns only one document

I have an app where admin can delete all documents in the firebase collection and add an x number of new documents, this works beautifully, but my streambuilder isn't updating properly,
the stream builder is getting back only one document everytime you delete all documents and create new ones, it only returns one, and like when you leave the app and come back, it fetches the proper amount of documents, all I can find online is that it's wrong to use a loop when querying and I've removed my for loop and am now using the map method, still, it is the same, here is my stream builder code
StreamBuilder<QuerySnapshot>(
stream: _store.collection("picks").snapshots(),
builder: (context, snapshot) {
if (snapshot.hasData) {
List<PickCard> pickCards = [];
final documentSnapshots = snapshot.data!.docs;
debugPrint(documentSnapshots.length.toString());
if (documentSnapshots.isNotEmpty) {
documentSnapshots.map((e) {
pickCards.add(
PickCard(
pickerPosition: e["pickerPosition"],
pickerName: e["pickerName"],
isPicked: e["isPicked"],
pickerEmail: e["pickerEmail"],
),);
}).toList();
dHelp.setCards(
context,
pickCards,
);
dHelp.setContributors(context, documentSnapshots.length);
}
} else {
}
the print document snapshot length is always 1 when they get created, but after refresh, the actual length updates, but in the firebase console, everything works perfectly, the documents update effectively,
here is a video of the problem https://www.dropbox.com/s/25qqnh0ttgemgf1/2022-08-16%2010-26-46.mp4?dl=0
I found that passing the stream directly to the streamBuilder was causing the stream to restart each time the build method rebuilt, which was supposed to be whenever the stream returns new data, so, it was kinda knotting over itself,
I instantiated the stream in the state then passed it to the streamBuilder, so now it's only created once in the lifetime of the page
// created this variable
late Stream<QuerySnapshot> _stream;
#override
initState() {
// gave it a value in iniState
_stream = _store.collection("picks").snapshots();
super.initState();
}
StreamBuilder<QuerySnapshot>(
stream: _stream, // then added this here
builder: (context, snapshot) {
if (snapshot.hasData) {
List<PickCard> pickCards = [];
final documentSnapshots = snapshot.data!.docs;
debugPrint(documentSnapshots.length.toString());
if (documentSnapshots.isNotEmpty) {
documentSnapshots.map((e) {
pickCards.add(
PickCard(
pickerPosition: e["pickerPosition"],
pickerName: e["pickerName"],
isPicked: e["isPicked"],
pickerEmail: e["pickerEmail"],
),);
}).toList();
dHelp.setCards(
context,
pickCards,
);
dHelp.setContributors(context, documentSnapshots.length);
}
} else {
}

How can i fetch data from Firestore (the cashed data) in flutter

i am trying to save data reads which have been not changed yet to avoid more and more the same repeated data that not changed yet ..
i have normal Future.Builder that get data from firstore (network side)
Widget build(BuildContext context) {
return FutureBuilder(
future: FirebaseFirestore.instance.collection('users').get(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData) {
return const Expanded(child: SizedBox()) ;
}
return ListView.builder(
itemCount: snapshot.data!.docs.length ,
itemBuilder: (context, int index) {
DocumentSnapshot documentSnapshot = snapshot.data!.docs[index];
return ListView.builder(
itemCount: snapshot.data!.docs.length ,
itemBuilder: (context, int index) {
DocumentSnapshot documentSnapshot = snapshot.data!.docs[index];
return Text(documentSnapshot['products'])
}
);
}
}
and i have into every single document Timestamp and i need to use where('modify',isGreaterThen : HERE i need to put the old timestamp from cashe to chick if it not changed yet to decide to fetch the new ones
in flutter i cannot handle it as well .. How can i fetch the cashed data with the new ones from network in the harmonic index such as reading the whole data in normal way .. so i avoided these old ones to be reload again ..
i have read a lot of this topic but it was in old Firestore version also it was using java code ...
this following code that cannot handle in flutter
Source CACHE = Source.CACHE;
Source SERVER = Source.SERVER;
Query.Direction DESCENDING = Query.Direction.DESCENDING;
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference shoesRef = rootRef.collection("shoes");
Query lastAddedQuery = shoesRef.orderBy("lastModified", DESCENDING)
shoesRef.get(CACHE).addOnCompleteListener(task -> {
if (task.isSuccessful()) {
boolean isEmpty = task.getResult().isEmpty();
if (isEmpty) {
shoesRef.get(SERVER).addOnCompleteListener(/* ... */);
}
}
});
Query query = shoesRef.orderBy("lastModified", DESCENDING)
.whereGreaterThan("lastModified", savedDate);
source code was written by Alex Mamo
https://medium.com/firebase-tips-tricks/how-to-drastically-reduce-the-number-of-reads-when-no-documents-are-changed-in-firestore-8760e2f25e9e
any support or example with latest version of Firbase and in dart or flutter code will be so thankful ..
best regards

How to fetch data from realtime database in a simple way in flutter?

currently i'm using firestore and realtime database at the same time. I set and retrieve from firestore in the most simplest and effective way in code and for realtime database i set data but i couldn't retrieve it in the same way that i do with firestore.
Summary i want to do the same thing which i do with firestore code in realtime database code.
Here is my code:
//Get data from Firestore
Stream <DocumentSnapshot> getData() async*{
final user = FirebaseAuth.instance.currentUser;
yield* FirebaseFirestore.instance.collection('users').doc(user.uid).snapshots();
}
//Return data in StreamBuilder (No lists or ListView.Builder needed here)
#override
Widget build(BuildContext context) {
return StreamBuilder(
stream: getData(),
builder: (context, snapshot) {
//--------------------------------------
//These equations comes from Firestore
//--------------------------------------
int currentWater ()=> snapshot.data['currentLitersAmount'];
int remainingWater () => snapshot.data['currentLitersAmount'] <= snapshot.data['recomendedLitersAmount'] ? snapshot.data['recomendedLitersAmount'] - snapshot.data['currentLitersAmount'] : 0;
double progress ()=> snapshot.data['currentLitersAmount'] / snapshot.data['recomendedLitersAmount'];
So how to do the same thing here for realtime database?
The equivalent of your getData function for Realtime Database would be:
Stream <Event> getData() async*{
final user = FirebaseAuth.instance.currentUser;
yield* FirebaseDatabase.instance.reference().child('users').child(user.uid).onValue();
}
And you can then get the DataSnapshot from each Event object in your UI building code.
#override
Widget build(BuildContext context) {
return StreamBuilder(
stream: getData(),
builder: (context, snapshot) {
int currentWater ()=> snapshot.data.snapshot.value['currentLitersAmount'];
...
If that snapshot.snapshot looks confusing, have a look at What is the difference between existing types of snapshots in Firebase?

Getting collection data from flirestore and appending into a list so that i can use ListView.builder to build the content in Flutter

Im trying to retrieve data from firestore and putting them into a list so that i can build read and build widgets from the data retrieved. I cant seem do both, i can either get the data, or append a list with a fixed value, but i CANT seem to RETRIEVE DATA + APPEND THE LIST WITH THE RETRIEVED DATA
. Sorry if im not being clear enough, do let me know what do you need, below is my screenshot from my database structure and code snippets.
Database structure :
Data retrieval code snippet :
onRefreshPage() {
Firestore.instance
.collection("testimonies")
.getDocuments()
.then((querySnapshot) {
querySnapshot.documents.forEach((result) {
print(result.data);
});
});
}
List declaration :
List<DocumentSnapshot> testimonyCards = [];
If I understand you correctly you want to transform the data into widgets. Have a look at FutureBuilder from Flutter: https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html and https://firebase.flutter.dev/docs/firestore/usage#realtime-changes
In your case you can do something like:
FutureBuilder<QuerySnapshot>(
future: FirebaseFirestore.instance.collection('testimonies').get(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return Text('Something went wrong');
}
if (snapshot.connectionState == ConnectionState.waiting) {
return Text("Loading");
}
return new ListView(
children: snapshot.data.docs.map((DocumentSnapshot document) {
return new ListTile(
title: new Text(document.data()['DisplayName']),
subtitle: new Text(document.data()['TestimonyData']),
);
}).toList(),
);
},
);
If I am correct, you want to query Firebase and append the results to a list. In this case, it is an array. Is this what you are looking for?
Appending data from Firebase to array

How to retrun all documents to the list in flutter

I want to return my all documents in firestore my document in Identifier based on name but when I do my function its return to me With the same number I have documents but the name its different instance of DocumentSnapshot but I need to return same names I have. How can I do this? Below is the code I am using
Widget build(BuildContext context) {
// TODO: implement build
return StreamBuilder < QuerySnapshot > (
stream: Firestore.instance.collection("Institute")
.document(widget.id).collection("Ravs").snapshots(),
builder: (context, snapshot) {
if (snapshot.hasData) {
print('list of docment:${snapshot.data.documents.toList()}');
};
return CircularProgressIndicator();
}
);
}
The Instance of DocumentSnapshot log is saying that you are interacting with the Snapshot object itself. which is what your code is indeed doing.
To get access to the data inside the Snapshot you have to add the .data() call next to your Snapshot, so your stream should look like this:
stream: Firestore.instance.collection("Institute").document(widget.id)
.collection("Ravs").snapshots().data()