How to display a list from database in flutter - flutter

I am a beginner in flutter, I want to retrieve a list of announcements from the database and display it in a listView but I have a compilation error under snapshot.data saying that A value of type 'List<Annonce>?' can't be assigned to a variable of type 'List<Annonce>'. Try changing the type of the variable, or casting the right-hand type to 'List<Annonce>'.
The code is :
future: AnnonceDataBase.instance.annonces(),
builder: (BuildContext context,
AsyncSnapshot<List<Annonce>> snapshot) {
if (snapshot.hasData) {
List<Annonce> annonces = snapshot.data;
return ListView.separated(... ```

Change like this:
future: AnnonceDataBase.instance.annonces(),
builder: (BuildContext context,
AsyncSnapshot snapshot) {
if (snapshot.hasData) {
List<Annonce> annonces = snapshot.data! as List<Annonce>;
return ListView.separated(... ```
Oh, by the way, Please consider to vote up and give it as accepted answer if an answer solves your problem. The reason is that other people with same issue can easily find the right answer easily. Have fun!

Related

Same streambuilder on next page but it stucks on ConnectionState.waiting

I am using bloc. But I found very rare issue i.e Stream is working well on one page but at the same time when we navigate to another page it is showing in ConnectionState.waiting
Here is my piece of code:
In bloc:
late StreamController<String> _timeRemainingController=StreamController.broadcast();
Stream<String> get timeRemainingStream => _timeRemainingController.stream;
// While adding value:
_timeRemainingController.add("");
Here is streambuilder which I am using
StreamBuilder<String>(
stream: _clockTimerBloc.timeRemainingStream,
builder: (context, snapshot) {
if (snapshot.hasData) {
//code
}
Common code which used everywhere. I am stuck there Please try to check. And thanks for any response.

Getting a field value from known document in firebase flutter

I want a user to give a value in my app and other user to see it. But i can upload data to firebase but not get it on the other side. I have null safety enabled on flutter. The code is :-
child: StreamBuilder(
stream:FirebaseFirestore.instance.collection('Collection name').doc('doc id').snapshots()
builder: (context, snapshot){
if(snapshot.hasData){
return Text(snapshot.data['Field name'].toString()); // here my editor shows error saying 'The method '[]' can't be unconditionally invoked because the receiver can be 'null'.' and asks for a null check and then shows error again
}
return Text('Nothing');
}
),
Edit: I am getting only 'type '_JsonDocumentSnapshot' is not a subtype of type 'Map<String, dynamic>' in type cast' as the error
And if I change
if(snapshot.hasData){
return Text(snapshot.data['Field name'].toString());
to
if (snapshot.hasData) {
return Text(snapshot.data.toString());
}
i get output as
'Instance of '_JsonDocumentSnapshot''
where the data should be.
I am using null check dart
Thannks for everyone's support, but i have accidently found and answer. I read that the data type of that is DocumentSnapshot and this worked for me
builder: (context, snapshot) {
if (snapshot.hasData) {
var numGuess = snapshot.data as DocumentSnapshot;
return Text(numGuess['Field name'].toString());
}
return Text('Nothing');
}
This works for null safety.
Since you are retrieving a collection then try the following:
return Text(snapshot.data!.docs[0].data()["Field Name"]);
A collection will return a list of documents, therefore use the docs property to be able to access the document. The above code will show the field in the first document in the list, it's better if you use a listview to return all documents.
Check:
https://api.flutter.dev/flutter/widgets/ListView-class.html
Give datatype to your StreamBuilder like this
StreamBuilder<DocumentSnapshot<Map<String, dynamic>>>(
stream:
FirebaseFirestore.instance.collection('Collection name').doc('doc id').snapshots(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data?.data()?['Field name']);
}
return Text('Nothing');
},
),

Listening to Stream doesn't get same result as StreamBuilder with Firebase

I'm using firebase and I have this:
Stream<QuerySnapshot> qs = FirebaseFirestore.instance
.collection("$mypath")
.orderBy(order)
.limit(10)
.startAfterDocument(lastDoc)
.snapshots();
When I pass qs to a StreamBuilder, the returned snapshot can do snapshot.hasError.
StreamBuilder(
stream: qs,
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) ... // hasError works
},
)
However when I listen to the stream, things like hasError, hasData ..., are not recognized anymore
qs.listen((event) {
if (event.hasError) // error: The getter 'hasError' isn't defined for the type 'QuerySnapshot<Object?>'.
});
I still can do event.docs and I get the data successfully, but I can't listen for errors. Am I doing something wrong?
The hasError and hasData are properties defined on the AsyncSnapshot object, and only exist when you're inside the StreamBuilder, where it essentially wraps the state of the asynchronous operation. When you call AsyncSnapshot.data in your code, you get back the QuerySnapshot that encapsulates the data from Firebase.
When you listen to the stream yourself, there is no AsyncSnapshot and you start with a QuerySnapshot, which is a Firestore object defined here. As you can see, that doesn't have hasError or hasData as those are exposed different.
This is definitely initially confusing as there are quite a few types of snapshots involved here, so I recommend checking out What is the difference between existing types of snapshots in Firebase?

Two StreamBuilderon on one screen with default empty screen shown when neither has data

I'm trying to create a Split View with two ListViews, one of them showing Tasks which are not completed and the second one containing completed tasks. I managed to make this work with a Column containing two Streambuilder. The problem I don't know how to solve is how to show a single default empty screen when neither of the two Streams have any values, due to the way Flutter works, I can't just return null. So I end up having two Empty default screens in my Column and on my screen.
What would be the right approach to make something like shown in the GIF with Firestore?
If I need to work with a single Stream and filter it inside dart, how can I make it work with ListView ?
I'd highly appreciate an example.
My Job class contains a boolean value jobDone which tells me in which list the Job has to go.
My current code:
return Column(
children: [
StreamBuilder<List<Job>>(
stream: getPendingJobsStream(database),
builder: (context, snapshot) {
return ListItemsBuilder<Job>(
...
);
},
),
ExpansionTile(
title: Text('Completed Tasks'),
children: [
StreamBuilder<List<Job>>(
stream: getCompletedJobsStream(database),
builder: (context, snapshot) {
return ListItemsBuilder<Job>(
...
);
},
),
],
),
],
);
You can check for snapshot state
builder: (context, snapshot) {
if(snapshot.connectionState ==ConnectionState.waiting){
return Center(child:CircularProgressIndicator();
}
if(snapshot.connectionState ==ConnectionState.done){
//check if snapshot has data
if(snapshot.hasData){
return ListItemsBuilder<Job>( ..

How to get access to a collection inside the start collection by using a StreamBuilder

I would like to know how can I get access to the fields of a collection that is inside the start collection? (see image below)
This is the streamBuilder I use to get access to the start(first) collection (posts) but I want a way to transform this streamBuilder so that I can get access to another collection inside the posts location. Thank you
StreamBuilder(
///IF YOU WANT TO CHANGE THE COLECCTION LIST THIS IS THE PLACE TO DO IT
stream: Firestore.instance.collection('posts').snapshots(),
builder: (context, snapshot) {
///THIS IS THE PLACE WHEN YOU CAN ADD AN ANIMATION
if (!snapshot.hasData) return const Text('Loading...');
return ListView.builder(
itemExtent: 100.0,
itemCount: snapshot.data.documents.length,
itemBuilder: (BuildContext context, int index) {
Post post = Post.fromDoc(snapshot.data.documents[index]);
return _buildUserTile(post);
},
);
},[![enter image description here][1]][1]
),
I want to be able to get the data that is inside a colection inside the first colection (posts).
See below my firebase database
I am not sure but maybe you can get an idea from the below link:
https://groups.google.com/forum/#!topic/flutter-dev/ayIxrLiz1eQ