Not getting data in latest firestore flutter library - firebase

While implementing the latest firestore library for flutter project, I am getting the the below error
Bad state: field does not exist within the DocumentSnapshotPlatform
CODE IMPLEMENTED
return ListView.builder(
itemCount: snapshot.data.docs.length,
itemBuilder: (context, index){
String itemTitle = snapshot.data.docs[index]['postContent'];
return ContentList(postContent: postContent);
});
Please guide me how to resolve, I am using Firestore ^0.14.3 dependency

The error is on this line String itemTitle = snapshot.data.docs[index]['postContent']; where Flutter tries to look for an item in the map with the key of 'postContent' but it is not found.
It is up to you to figure out why this so but I would also like refrain against asking questions which have already been asked. Next time just a tip, paste the error into Google and review the top links. :)
Below is a duplicate:
https://github.com/FirebaseExtended/flutterfire/issues/3826

Related

Flutter SteamBuilder throwing error on first argument context

I have a problem here with flutter (v2.8.1) on my windows.
I am trying to use StreamBuilder class to fetch data from firebase but it is not working anyhow. I tried to use BuildContext context but it is still throwing me error on context.
Please have a look at my code and let me know what I am doing wrong. Answers are appreciated. Thanks in advance.
StreamBuilder(builder: (BuildContext context, snapshot), stream: _firestore.collection('messages').snapshots()),
Error :
The argument type 'Type' can't be assigned to the parameter type 'Widget Function(BuildContext, AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>>)'.
Please check the image : https://imgur.com/a/QJs6hS9
The builder argument should be a function that returns a widget.
builder: (context, snapshot) {
// return a widget that uses the snapshot
// for example
return Text(snapshot.data().title);
}

Retrieving firebase firestore documents in Flutter / Dart and Sound Null

I am working my way through a Udemy Flutter class and I am in a chapter dealing with Firebase. The class is about 3-4 years old and it seems is just old enough that the sample completed code crashes when accessing the Firebase portions. I started a new project from scratch and cobbled bits and pieces to get it mostly up and running but I have now hit a dead end. The new project and the firebase plugins are Sound Null and the class code is not. Getting and printing data from the database worked fine until I tried getting it hooked up to a stream. I am specifically running into a problem iterating over the received documents.
When I set up the message variable using (the Flutter) snapshot.data in a for-in loop and try to iterate over the returned documents (#1) I have a null problem. Without specifying the type (#1a) as AsyncSnapshot<dynamic> the for-in loop errors that I cannot iterate over a non nullable.
Changing the type gets rid of the compile time error but generates a runtime error of
Type _JsonQuerySnapshot is not a subtype of type Iterable
Dart is not my primary language and I have been pulling my hair out googling this for several hours to no avail. Any help is appreciated.
final _firestore = FirebaseFirestore.instance; //<-----earlier in the code
children: <Widget>[
StreamBuilder<QuerySnapshot>(
stream: _firestore.collection('messages').snapshots(),
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) { //<----Problem #1a here
List<Text> messageWidgets = [];
if (snapshot.hasData) {
final messages = snapshot.data;
for (var message in messages) { //<----------Problem #1 here
final messageText = message.data['text'];
final messageSender = message.data['sender'];
final messageWidget =
Text('$messageText from $messageSender');
messageWidgets.add(messageWidget);
}
}
return Column(
children: messageWidgets,
);
},
Well, after another hour or so of googling around I found the right place to look. The docs for the flutter plugin for firestore have a massive difference from the course I am taking. Reading(ctrl-c, ctrl-v) them I'm at least able to mostly understand and have the program back on track to finish my course.

The argument type 'User?' can't be assigned to the parameter type 'Future<Object?>?'

With reference to the recent changes regarding FirebaseUser to User. FirebaseAuth.instance.currentUser() is not found at all (while throughing error "The expression doesn't evaluate to a function, so it can't be invoked." The solution to that however was to simply remove the paranthesis as FirebaseAuth.instance.currentUser. But now we have another error that it isn't a future type i.e "The argument type User can't be assigned to the parameter type Future<Object?>?". Following is my code block.
return FutureBuilder(
future: FirebaseAuth.instance.currentUser,
builder: (ctx, futureSnapshot) => ListView.builder(
reverse: true, // So that 1st message goes to last.
itemCount: chatDocument.length,
itemBuilder: (ctx, index) => MessageBubble(
message: chatDocument[index]['text'],
isMe: chatDocument[index]['userId'],
),
),
);
In the above code block I intend to provide future to my `FutureBuilder`. In summary previously `FirebaseUser` object did return a future, but probably `User` doesn't anymore. How may I handle this case? Thanks in advance.
I don't typically do that with a FutureBuilder. Once you have a user, you don't need to async it.
final FirebaseAuth_auth = FirebaseAuth.instance();
final User? user;
user = _auth.currentUser;
Then, if user != null ....create your ListView else, return a CircularProgressIndicator or whatever.
Look up Net Ninja for some nice videos for getting yourself set up with all that, just having a stream based on userChanges() for your project. More robust setup.

Provider with loading widget in Flutter [duplicate]

This question already has an answer here:
How to create a StreamProvider and subscribe to it later, Flutter
(1 answer)
Closed 1 year ago.
I have a stream provider in my Flutter app which fetches data from my Firestore database.
I want to show a loading widget while loading the data until it is done loading. Similar to the Futurebuilder with the ConnectionState function for example.
Is this possible?
Thank you for help!
When you use a future builder you can check if your snapshot.data is null. If it is null you show the spinner, otherwise you show your content:
StreamBuilder(
stream: myStream, //YOUR STREAM
builder: (BuildContext context, AsyncSnapshot snapshot) {
return snapshot.data == null
? Spinner() //LOADING SPINNER
: Container() //AFTER RETRIEVING CONTENT
}
)
UPDATE
Since you mentioned Future builder I got mislead. This is the answer you are searching for:
How to create a StreamProvider and subscribe to it later, Flutter

Possible to get metadata from Firestore snapshot Flutter?

I need to get snapshot metadata so can check if write to Firestore successful. I look at source and see there is SnapshotMetadata and boolean hasPendingWrites(). But I cannot find how to implement. No open source dart project have used it.
Firebase doc say can use: .onSnapshot / .addSnapshotListenerto specify includeMetadataChanges: true.
But I need to make sure I get metadata when making a query for QuerySnapshot. I am use query for stream not addSnapshotListener.
Like this:
child: new FirestoreAnimatedList(
query: Firestore.instance.collection('Collection')
.orderBy('timestamp', descending: true)
.snapshots(),
padding: new EdgeInsets.all(8.0),
reverse: true,
itemBuilder: (_, DocumentSnapshot snapshot,
Animation<double> animation, int x) {
return new Chat(
snapshot: snapshot, animation: animation);
},
),
I have try specify:
query: Firestore.instance.collection('Collection')
.snapshots(includeMetadataChanges: true),
But this not possible:
error: The named parameter 'includeMetadataChanges' isn't defined.
I also try:
snapshot.getMetadata().hasPendingWrites()
But give error:
error: The method 'getMetaData' isn't defined for the class
'DocumentSnapshot'.
Does anyone know how do this in Flutter? Is possible?
I try so long but cannot find how.. Help!
Thanks!
includeMetadataChanges Parameter Added
Support in Flutter for the includeMetadataChanges parameter was added in the cloud_firestore package at version 0.12.9.
When you are calling your snapshots() function, you can now include it as a parameter.
This example returns a Stream of all documents in a collection, as a list of contacts. If includeMetadataChanges is false (default behavior) then the stream will not be updated when metadata changes (such as hasPendingWrites or isFromCache). If true, then the stream is updated by these changes.
Stream<List<Contact>> getAllContactsStream() {
return Firestore.instance.collection('contacts')
.orderBy('name', descending: false)
.snapshots(includeMetadataChanges: true)
.map((snapshot) => snapshot.documents.map((document) => Contact.fromFirestore(document)).toList())
}
With a single document snapshot, normal Firestore data is accessed with document.data. The metadata is accessed with document.metadata.
It looks like the DocumentSnapshot class in FlutterFire doesn't expose the metadata of the underlying document. I'd file a feature request for it on the Flutter repo.

Resources