Flutter gives null error, but works after restart - firebase

I am new to Flutter, I am trying to fetch data from firestore collection. I am using FutureBuilder with Provider, but it shows null error on initial & runs perfectly after restarting the app.
Here is the code to fetch the data:
FutureBuilder<QuerySnapshot>(
future: FirebaseFirestore.instance
.collection(collec.collectionProducts)
.get(),
builder: (context, snapshot) {
return Consumer<CartItemCounter>(
builder: (BuildContext context, CartItemCounter cart, _) {
if (cart.checkProductAddedToCart(model.productId)) {
return Row(....);
Error
code for futurebuilder
code for ui
(here i have changed the collection name)
How can i solve it. I have tried every solution available on online. Thank you

Where is the error coming from?
According to this, the issue is coming from your Consumer<CartItemCounter>.
What does the error mean?
This error, The method 'x' was called on null., means that the class where this x function is written, that class is null.
What is the reason for this error in my code?
Your Consumer<CartItemCounter> provides an instance of CartItemCounter by the name cart. Then, you call function checkProductAddedToCart.
The error message is telling you that cart is null which is being given to you by the Consumer widget. This means that Consumer probably also did not find that Provider. I expect that there should be an error log by Provider, telling you that CartItemCounter was not found.
Possible Solution
Try 'providing' CartItemCounter.
How do you do that? Go to the top of your app's widget tree to MaterialApp, wrap it inside a MultiProvider or ChangeNotifierProvider and then pass your new CartItemCounter as value.
Read Official Provider Docs for more info on how to expose a provider.
You need to upload your complete log, so that I can further help you.

Always check the result for the future builder, ie snapshot has data.
Place a switch condition or if-else bock depending on the status of the snapshot.
check the example from the official doc here

Related

I got a error on code data.docs . I want to display all data from firestore

I have an error on data.docs . It always show an error on the docs code. i want to display all the data from firestore
Looking at it, it seems you have not set a return type for your FutureBuilder or StreamBuilder. If you wish to access properties on snapshot.data, you should type the future or stream. For example doing
FutureBuilder<QuerySnapshot>
allows you to access methods on the QuerySnapshot class like
snapshot.data!.docs

Fetching rows with a particular value of child Firebase Flutter

I'm working with Flutter and Firebase (Real-time database). There is some data stored in the db and I want to compare the email (child) of the parent and only want to display the parents containing that particular email. Currently, it is fetching all rows. I think fetching through key value pair would do the work. But I dont know the syntax and unable to find help regarding it. Please help me out.
void myfunc() {
databaseReference.once().then((DataSnapshot snapshot) {
print('Data : ${snapshot.value}');
});
}
try with
yourRef.orderByChild("email").equalTo('abs#abc.com');
Read Query Data

.once() doesn't seem to work / recognized while working with Flutter & Firebase

I am trying to fetch some data from FireStore and store it in a local list to be displayed later in the form of cards. I have seen many tutorials where people have used .once() to fetch data.
Now, when I am trying to do the same then getting error like the word isn't recognized.
#override
void initState() {
super.initState();
CollectionReference dbRefItem = FirebaseFirestore.instance.collection("items");
***dbRefItem.once().then***
}
I cant seem to find any documentation if it has been deprecated or am I doing something wrong! Hovering cursor on the error says
"The method 'once' isn't defined for the type 'CollectionReference'.
Try correcting the name to the name of an existing method, or defining
a method named 'once'."
.get() did the same job as .once()
However, .once() syntax is not being accepted by Flutter's latest SDK while worked on the previous one. Have raised a ticket with Flutter Dev forum.

Flutter and Firebase: Return all images from Firebase Storage

I have seen a few articles written online by people pertaining to be able to do this, but they only tell you how to do this with a specific, controlled list of images where they also know all the filenames beforehand.
There is also this "answer" posted here: Flutter - Get all images from firebase storage which does not actually resolve this issue at all as it suggests a .listAll() method for the recommended plugin, but there is no such method as .listAll() using the suggested plugin.
I need to be able to not know how many images are in Firebase storage, or what they might be called, just to return everything stored there.
UPDATE:
So because Firebase is full of so many limitations that it hardly qualifies as a database at all, it seems we may have to keep the images in Firebase Storage and a reference list of these in a Firebase Realtime Database Document.
I am stuck on the actual implementation of this however, as I am not even sure firstly how best to go about this. What I am attempting to do is store all the Storage image URLs in an array (if this is not the best way to do this, let me know!):
Firebase Structure
collection -> document -> fields
userData profileImages URLs (array)
My first issue is that I don't know how to append new data to the existing array, it seems to just overwrite it each time I add a new item so that I only ever have one string in the array in the database:
Firestore.instance.collection('userData').document('profileImages').updateData({
'URLs': _uploadedFileURL,
});
Then after this I am also not sure how to actually retrieve the full array of data later when I need it:
Container(
child: StreamBuilder(
stream: Firestore.instance.collection('userData').document('profileImages').snapshots(),
builder: (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
if (!snapshot.hasData) {
return LoadingAnimationBasic();
}
if (snapshot.data.data == null) {
return LoadingAnimationBasic();
} else {
return ListView(
shrinkWrap: true,
children: _buildProfileGallery(snapshot),
);
}
},
),
),
And then the function:
_buildProfileGallery(AsyncSnapshot<DocumentSnapshot> snapshot) {
int test = snapshot.data["URLs"].length;
print('URLs in List: ' + test.toString());
return snapshot.data.data.map(???);
}
I have no idea what to put as the parameters of this map, as the hint text is insane:
MapEntry(K2, V2> f(String key, V value)
I can't even begin to guess what this means.
Am I on the right track? Am I on the right planet?
The ability to list files was added to Firebase's client-side SDKs for Android, iOS and JavaScript last year, but has not yet landed in the FlutterFire bindings.
The answer to the question you linked, refers to a pull request on the FlutterFire open-source project that adds this functionality. So while somebody wrote code to allow listing of files in Flutter too, this code hasn't been added to a release so far. So the only way to use that code now, is to build your own version of the FlutterFire library for firebase_storage.
Without the ability to list files in the Firebase Storage API, you'll have to revert back to what everyone did before this feature was added: keeping a list of the files in a secondary location, such as the Firebase Realtime Database or Cloud Firestore.

Flutter: PlatformException(error, Invalid document reference. Document references must have an even number of segments, but <x> has 1, null)

I have the following in my app:
stream: Firestore.instance.collection('stores').document(currentUserUID).snapshots(),
builder: (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
if (snapshot.hasData) {
return ListView.builder(
//do some stuff here with the data
} else {
return LoadingAnimation();
}
}
}
}
Pretty standard, but I am getting the error listed above.
I have vertified that currentUserID populates with the correct data before this stream is called.
In testing I have found that this error is perhaps likely caused by the fact that at runtime, "if (snapshot.hasData) {" shows me that there is no data in the snapshot yet. If I do anything at all, like minimise the app and refocus it again, all the data loads. So it simply just needs a redraw.
Is there a way to do an "await" or something on this? There must be a simple fix for this problem, seems to be a simple issue, but I just can't find a solution in any of the other threads about this.
Anyone have any ideas on how I can either do an await on this stream, or force it to update when it receives data (I kinda thought that was the whole point of a stream, but this examples proves that it doesn't do this).
If the error message actually refers to this code, that means currentUserUID is probably an empty string. This is a very common mistake - if you do a Google search for the error message, you will see many others making the same mistake.
Print the value of currentUserUID just before you use it in order to verify that it contains the value that you expect.

Resources