Firebase Realtime Database and Flutter - Snapshot has no data - flutter

I try to implement the Firebase Realtime Database in Flutter and I want to display updated values in realtime. I try to achieve this with a StreamBuilder.
StreamBuilder Code
StreamBuilder(
stream: GuestbooksDatabase().getAllGuestbooksSync().asStream(),
builder: (context, snapshot) {
if (!snapshot.hasData || !snapshot.data.length) {
return CircularProgressIndicator();
} else {
return ListView.builder(
shrinkWrap: true,
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return Text(snapshot.data[index].title);
});
}
}),
The stream function
Future<List<Guestbook>> getAllGuestbooksSync() async {
List<Guestbook> guestbooks = [];
databaseRef.onValue.listen((event) async {
var dataSnapshot = event.snapshot;
if (dataSnapshot.value != null) {
dataSnapshot.value.forEach((key, value) async {
Guestbook guestbook = await Guestbook.fromJson(value);
guestbook.setId(key);
guestbooks.add(guestbook);
});
await Future.delayed(Duration.zero);
print(guestbooks); // Result: All Instances of Guestbook
return guestbooks;
}
});
}
I only see the CircularProgressIndicator() what means that the snapshot has no data.
What's the issue there?

You can use StreamController for this.
Create a new controller -
final StreamController streamController = StreamController<List>.broadcast();
Convert Future<List> to void type for your getAllGuestbooksSync() function and return nothing.
It can and will be called in initState() -
void getAllGuestbooksSync() {
List<Guestbook> guestbooks = [];
databaseRef.onValue.listen((event) async {
var dataSnapshot = event.snapshot;
if (dataSnapshot.value != null) {
dataSnapshot.value.forEach((key, value) async {
Guestbook guestbook = await Guestbook.fromJson(value);
guestbook.setId(key);
guestbooks.add(guestbook);
});
print(guestbooks); // Result: All Instances of Guestbook
streamController.add(guestbooks); // Adding list to the stream
}
});
}
In your StreamBuilder use -
stream: streamController.stream,

Related

Future Builder with for loop in flutter

In my application, I have two future builders:
CollectionReference stream = Firestore.instance.collection('users');
List<String> myIDs =[];
List <dynamic> mylist =[];
List<String> myNames =[];
String? userName;
Widget userValues() {
return FutureBuilder(
future: getrecords(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData &&
snapshot.connectionState == ConnectionState.done) {
return ListView.builder(
shrinkWrap: true,
itemCount: snapshot.data!.length,
itemBuilder: (context, index) {
return Text(snapshot.data? [index] ?? "got null");
},
);
}
else {
return CircularProgressIndicator();
}
},
);
}
..................
Future getrecords() async{
final data = await stream.get();
mylist.addAll(data);
mylist.forEach((element) {
final String firstPartString = element.toString().split('{').first;
final String id = firstPartString.split('/').last;
myIDs.add(id.trim());
});
return(myIDs);
}
....................
Widget Names() {
return FutureBuilder(
future: getNames(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData &&
snapshot.connectionState == ConnectionState.done) {
return ListView.builder(
shrinkWrap: true,
itemCount: snapshot.data!.length,
itemBuilder: (context, index) {
return Text(snapshot.data?[index] ?? "got null");
},
);
}
else {
return CircularProgressIndicator();
}
},
);
}
............................
Future getNames() async{
for (var id in myIDs ){
var names = stream.document(id).collection('userName').document('userName');
var document = await names.get();
userName = document['name'];
myNames.add(userName!);
}
return(myNames);
}
The first future (userValues) works fine, and I get the result just fine, but the other one with the for loop is not working properly and is not returning values until I hot reload, then a name will be added to the list, and so on with each hot reload.
What I want to achieve is to keep the loading indicator until the for loop is over, then build the screen.
UPDATE:
If I could manage to make it so that the "Names" futurebuilder awaits for the userValues to complete before starting, then my problem would be solved, but what I realized is that it's taking the initial value of the return from "userValues," which is non, and using it to build.
Future getNames() async{
await Future.delayed(const Duration(seconds: 2));
for (var id in myIDs ){
var names = stream.document(id).collection('userName').document('userName');
var document = await names.get();
userName = document['name'];
myNames.add(userName!);
}
return(myNames);
}
When I added this 2 seconds delay, it worked properly but is there any other way to make it wait for the first future to complete then start the second one?
You can use the await keyword on the future returned from getrecords() to wait for the completion of getrecords() before starting the getNames() function:
Future getNames() async{
await getrecords();
for (var id in myIDs ){
var names = stream.document(id).collection('userName').document('userName');
var document = await names.get();
userName = document['name'];
myNames.add(userName!);
}
return(myNames);
}

How can I convert FutureBuilder code to StreamBuilder?

I am trying to get data from Firestore and pass that data to screen using stream. I have done this using FutureBuilder, this solution works as followed, but I need to use StreamBuilder Can anyone help me find the problem?
Future<List<Business>> list(FirebaseFirestore _firesore) async {
CollectionReference _col = _firesore.collection('Buisiness');
var _result = await _col.get();
var _docs = _result.docs;
return List.generate(_docs.length, (index) {
var satir = _docs[index].data();
return Business.fromMap(satir as Map<String, dynamic>);
});
}
This Code works in FutureBuilder but not StreamBuilder
StreamBuilder<List<Business>>(
stream: _firestorelist.list(_firestore), // Error Here
builder: (context, snapshot) {
if (snapshot.hasData) {
List<Business>? data = snapshot.data;
return ListView.builder(
itemCount: data!.length,
itemBuilder: (context, index) {
var result = data[index];
return ListTile(
title: Text(result.nereden),
subtitle: Text(result.nereye),
trailing: Text(result.fiyat),
);
},
);
} else {
return CircularProgressIndicator();
}
},
)```
You can write your data source method as
Stream<List<Business>> list(FirebaseFirestore _firesore) {
CollectionReference _col = _firesore.collection('Buisiness');
final _snap = _col.snapshots();
return _snap.map((event) => event.docs
.map<Business>((e) => Business.fromMap(e.data() as Map<String, dynamic>))
.toList());
}
The current method is a One-time Read method, You can get snapshots from the specific collection.
You can change the method like this and Then use it as stream in streamBuilder:
list(FirebaseFirestore _firesore) async {
CollectionReference _col = _firesore.collection('Buisiness');
var _result = await _col.snapshots();
return _result;
}

StreamBuilder updating the stream only after hot restart

I am building an app where it collects all the orders and order details placed from Firebase. I have to get 2 things
Salon details from contactnumber which I saved using singleton method once the user logs in
Customer details from CustID
What happens right now is that during debugging I created this button, on pressing it fetches the salon details from database. But now, the details will only get fetched when I
Click the button first
Hot restart the app
Only then the streambuilder fetched the data
Here are my code snippets causing the problem :
Future<void> getSalonFromContact(String saloonContact) async {
await for (var docs in firestore.collection('Saloon').snapshots()) {
// final loop = snap.data!.docs;
for (var variable in docs.docs) {
if (variable.get(FieldPath(['Contact'])) == saloonContact) {
aadhar = variable.get(FieldPath(['Aadhar']));
getOrdersList(aadhar);
}
}
}
}
Future<void> getOrdersList(String aadhar) async {
ordersList.clear();
await for (var docs in firestore
.collection('orders')
.where('SalonID', isEqualTo: aadhar)
.snapshots()) {
for (var variable in docs.docs) {
if (variable.get('SalonID') == aadhar) {
ordersList.add(variable.data());
print('My orderlist is $ordersList');
} else {
continue;
}
}
}
}
Future<void> getCustomerDetails(String custID) async {
await for (var docs in firestore
.collection('Customers')
.where('Customer_Uid', isEqualTo: custID)
.snapshots()) {
// final loop = snap.data!.docs;
for (var variable in docs.docs) {
print(variable.data());
if (variable.get(FieldPath(['Customer_Uid'])) == custID) {
customerDetails.add(variable.data());
print('My customer details are ${customerDetails}');
}
}
}
}
#override
void didChangeDependencies() async {
await getSalonFromContact(contactNumber);
for (int i = 0; i < ordersList.length; i++) {
await getCustomerDetails(ordersList[i]['CustomerID']);
}
// TODO: implement didChangeDependencies
super.didChangeDependencies();
}
These codes are for finding out the details.
And this is my StreamBuilder code :
StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection('orders')
.where('SalonID', isEqualTo: aadhar)
.snapshots(),
builder: (context, snapshot) {
didChangeDependencies();
if (snapshot.connectionState ==
ConnectionState.waiting) {
return Text('Loading...');
} else {
List<AppointmentCard> listitems = [];
return ListView(
physics: NeverScrollableScrollPhysics(),
shrinkWrap: true,
children: snapshot.data!.docs
.asMap()
.map((index, DocumentSnapshot document) {
getCustomerDetails(document['CustomerID']);
return MapEntry(
index,
AppointmentCard(
isCompleted: document['Status'],
name: customerDetails[index]['Name'],
contact: customerDetails[index]
['Contact'],
services: Flexible(
child: ListView.builder(
shrinkWrap: true,
padding: const EdgeInsets.all(8),
itemCount:
document['Requested_Service']
.length,
itemBuilder: (BuildContext context,
int index) {
return Text(
document['Requested_Service']
[index]['name']);
}),
// child: Text(
// // "Text",
// " ${ordersList[i]['Requested_Service']} ",
//// .join(' '),
//
// softWrap: true,
// ),
),
),
);
})
.values
.toList(),
);
}
}),
Any idea what is going wrong and how I can fetch the data without the button and hot restart?
You use getCustomerDetails(document['CustomerID']); in before MapEntry and it is an asynchronous function. It will return probably after the MapEntry is built. You have to await getCustomerDetails function before put your variables which is updating in getCustomerDetails function.

Flutter - NoSuchMethodError: Class '_MapStream<QuerySnapshotPlatform, QuerySnapshot>' has no instance method 'then'

I wanted to retrieve data from my sub collection. It should return the list of friendid.
But I keep getting the NoSuchMethodError snapshot has no instance method then error with the code below.
The error is at firebaseMethods.getFriend(Constant.currentId).then((value) line.
Widget friendList() {
return StreamBuilder(
stream: friendlistStream,
builder: (context, snapshot) {
return snapshot.hasData
? ListView.builder(
itemCount: snapshot.data.docs.length,
itemBuilder: (context, index) {
return FriendTile(
snapshot.data.docs[index].data()["friendid"]);
},
)
: Container();
},
);
}
#override
void initState() {
getUserFriend();
super.initState();
}
getUserFriend() async {
Constant.currentId =
await HelperFunctions.getUserIdSharedPreference(Constant.currentId);
setState(() {
firebaseMethods.getFriend(Constant.currentId).then((value) {
setState(() {
friendlistStream = value;
});
});
});
}
The code for firestore is as below.
getFriend(String ownerid) {
return FirebaseFirestore.instance
.collection("users")
.doc(ownerid)
.collection("friends")
.snapshots();
}
I had tried hardcoding the Constant.currentId to the actual ID that I wanted to retrieve but still having the same error. What should I do to display the list of friendid correctly?
Future getFriend(String ownerid) async {
return await FirebaseFirestore.instance
.collection("users")
.doc(ownerid)
.collection("friends")
.get();
}
.then() is used for futures so your getFriend() method needs to return a Future
If you want to use the Stream than you need to use a StreamBuilder instead of calling a function in initState
This might help: https://www.youtube.com/watch?v=MkKEWHfy99Y&ab_channel=GoogleDevelopers

How to return Future List from DataSnapshot

I want to return a Future List from Firebase Database snapshot and this is my code but I cant get it work properly:
Future<List<CocheDetailItem>> getCoches(ids) async {
List<CocheDetailItem> coches = [];
final dbRef = FirebaseDatabase.instance.reference().child('17082019');
for (var i = 0; i < ids.length; i++) {
var id = ids[i];
dbRef.child(id).once().then((DataSnapshot snapshot) {
if (snapshot.value != null) {
Map<dynamic, dynamic> jsres = snapshot.value;
CocheDetailItem coche = CocheDetailItem.fromJson(jsres);
coches.add(coche);
}
});
print('here is i ${ids[i]} ');
}
return coches;
}
The return I get is empty Area. Can anyone help me with this, please?
Note, dbRef.child(id).once(); is a async function, so you must wait it ends to get your data. Use await keyword to do it.
Future<List<CocheDetailItem>> getCoches(ids) async {
List<CocheDetailItem> coches = [];
final dbRef = FirebaseDatabase.instance.reference().child('17082019');
for (var i = 0; i < ids.length; i++) {
var id = ids[i];
var dataSnapshot = await dbRef.child(id).once();
if (dataSnapshot.value != null) {
Map<dynamic, dynamic> jsres = dataSnapshot.value;
CocheDetailItem coche = CocheDetailItem.fromJson(jsres);
coches.add(coche);
}
print('here is i ${ids[i]} ');
}
return coches;
}
well.. I don't use firebase but I send a request to my database with this (you have to use async and await)
Future<List<PlaceModel>> getPlaces(String ciudad, String tipo) async {
Uri request = Uri.http('domain.com', '/getPlaces/$ciudad/$tipo');
ResponseModel response = ResponseModel.fromJsonMap(json.decode((await http.get(request)).body));
List<PlaceModel> items = [];
if(response.res) {
if(response.value != null) {
for(var item in response.value) {
final place = PlaceModel.fromJsonMap(item);
items.add(place);
}
}
}
print("Places Loaded: ${items.length}");
return items;
}
I use my ResponseModel to convert the json answer in an object.
Then I show it with the future builder:
class PlacesListPage extends StatelessWidget{
final _selectedLocation, _selectedList;
PlacesListPage(this._selectedLocation, this._selectedList);
final _provider = PlaceProvider();
#override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(8.0),
child: FutureBuilder(
future: _provider.getPlaces(_selectedLocation, _selectedList), // async request to database
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData) { // check when your request is done
if(snapshot.data.length != 0) { // check if any data has been downloaded
return ListView.builder( // build a listview of any widget with snapshot data
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
// i just return containers but you can use any custom widget, it's like a forEach and use the index var
return Container(
child: Text(snapshot.data[index]),
);
},
);
} else {
// If you don't have anything in your response shows a message
return Text('No data');
}
} else {
// shows a charge indicator while the request is made
return Center(
child: CircularProgressIndicator(),
);
}
},
),
);
}
}