flutter - an issue with Future.builder in Cloud Firestore 0.14 - firebase

I updated the cloud firestore yesterday. And, I surprised everything about firestore became wrong. I tried to update my code but I still getting an error with the Future builder. Here is the code and the error. The code was ok before the update.
Future getposts() async{
await Firebase.initializeApp();
var firestore = FirebaseFirestore.instance;
QuerySnapshot qn = await firestore.collection("Restaurants").get();
return qn.docs;}
FutureBuilder(
future: getposts(),
builder: (_,snapshot){
if(snapshot.connectionState == ConnectionState.waiting){
return Center(
child: CircularProgressIndicator(),
);}
else{
return ListView.builder(
itemCount: snapshot.data().length,
itemBuilder: (_,index){
return Center(
child: Text(snapshot.data()[index].data()["name"]),
);
},);
}
},
),
════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following NoSuchMethodError was thrown building FutureBuilder(dirty, state: _FutureBuilderState#2c7a5):
Class 'List' has no instance method 'call'.
Receiver: Instance(length:2) of '_GrowableList'
Tried calling: call()
The relevant error-causing widget was:
FutureBuilder file:///C:/Users/youse/AndroidStudioProjects/new_app/lib/screens/main_page.dart:226:23
When the exception was thrown, this was the stack:
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1 _MainPageState.build. (package:new_app/screens/main_page.dart:235:55)
#2 _FutureBuilderState.build (package:flutter/src/widgets/async.dart:740:55)
#3 StatefulElement.build (package:flutter/src/widgets/framework.dart:4663:28)
#4 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4546:15)
...
════════════════════════════════════════════════════════════════════════════════════════════════════

Thanks for help. I solved the issue by removing the parenthesis in the first data. And here is the correct code.
Future getposts() async{
await Firebase.initializeApp();
var firestore = FirebaseFirestore.instance;
QuerySnapshot qn = await firestore.collection("Restaurants").get();
return qn.docs;}
FutureBuilder(
future: getposts(),
builder: (_,snapshot){
if(snapshot.connectionState == ConnectionState.waiting){
return Center(
child: CircularProgressIndicator(),
);}
else{
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (_,index){
return Center(
child: Text(snapshot.data[index].data()["name"]),
);
},);
}
},
),

Related

Firebase firestore on Flutter Web NoSuchMethodError. 'docs'

I'm trying to run my flutter chat app on web but I encountered this error
════════ Exception caught by widgets library ═══════════════════════════════════
'docs'
method not found
Receiver: null
Arguments: []
The relevant error-causing widget was
StreamBuilder
Error Message Screenshot
It is working on my android emulator so maybe there's missing on my web configuration so what I've tried is adding the firebase on my index.html and following https://stackoverflow.com/a/67518124/15916393 advice but still the error occurs.
<script src="https://www.gstatic.com/firebasejs/8.8.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.5/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.5/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.8.1/firebase-messaging.js"></script>
here is my code
class Messages extends StatelessWidget {
#override
Widget build(BuildContext context) {
final user = FirebaseAuth.instance.currentUser;
return StreamBuilder(
stream: FirebaseFirestore.instance
.collection('chat')
.orderBy(
'createdAt',
descending: true,
)
.snapshots(),
builder: (ctx, chatSnapshot) {
if (chatSnapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
}
final chatDocs = chatSnapshot.data.docs ?? 'default data';
return ListView.builder(
reverse: true,
itemCount: chatDocs.length,
itemBuilder: (ctx, index) => MessageBubble(
chatDocs[index].data()['text'],
chatDocs[index].data()['username'],
chatDocs[index].data()['userImage'],
chatDocs[index].data()['userId'] == user.uid,
key: ValueKey(chatDocs[index].id),
),
);
},
);
}
}
You're ignoring the case where there is an error in loading the data
builder: (ctx, chatSnapshot) {
if (chatSnapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
}
// 👇 Check if there was an error
if (snapshot.hasError) {
return Text('Error loading data: ${snapshot.error!}');
}
final chatDocs = chatSnapshot.data.docs ?? 'default data';
...
I highly recommend following the patterns outline in the samples in the FlutterFire documentation like the above from reading realtime changes.

How to fix flutter firestore stream builder error?

I tired to get data from firestore in flutter app.
This is my code
body: StreamBuilder(
stream:
FirebaseFirestore.instance.collection('my_contact').snapshots(),
builder: (context, AsyncSnapshot<QuerySnapshot> streamSnapshot) {
return ListView.builder(
itemCount: streamSnapshot.data.docs.length,
itemBuilder: (ctx, index) => SettingRowWidget(
"Call",
vPadding: 0,
showDivider: false,
onPressed: () {
Utility.launchURL((streamSnapshot.data.docs[index]['phone']));
},
),
);
},
));
and this code getting right data but problem is i'm getting error like this.
════════ Exception caught by widgets library ═══════════════════════════════════
The following NoSuchMethodError was thrown building StreamBuilder<QuerySnapshot>(dirty, state: _StreamBuilderBaseState<QuerySnapshot, AsyncSnapshot<QuerySnapshot>>#7adda):
The getter 'docs' was called on null.
Receiver: null
Tried calling: docs
I dont know how to solve it. Can anyone guide me to solve this?
Check if it's null while loading the data from firestore
StreamBuilder(
stream:
FirebaseFirestore.instance.collection('my_contact').snapshots(),
builder: (context, AsyncSnapshot<QuerySnapshot> streamSnapshot) {
if (!streamSnapshot.hasData) return Center();
if (streamSnapshot.data.docs.length!=0) {
return ListView.builder(
itemCount: streamSnapshot.data.docs.length,
itemBuilder: (ctx, index) => SettingRowWidget(
"Call",
vPadding: 0,
showDivider: false,
onPressed: () {
Utility.launchURL((streamSnapshot.data.docs[index]['phone']));
},
),
);
}else{
return Center(child:Text('No data found'));
}
},
));

"NoSuchMethodError: The getter 'docs' was called on null" Error Flutter Firebase

I'm getting the error "NoSuchMethodError: The getter 'docs' was called on null. Receiver: null Tried Calling: docs" whenever I try to use .orderby("POST_ID", descending: true. If someone has an answer to why I'm getting this error and how to fix it please help!
Here is my code:
Container(
margin: EdgeInsets.only(top: 100.0),
child: StreamBuilder(
stream: FirebaseFirestore.instance
.collection("Cities")
.doc(globals.selectedCity)
.collection("Posts")
.orderBy("POST_ID", descending: true)
.where("Category", isEqualTo: globals.selectedCategory)
.snapshots(),
builder: (context, postSnapshot) {
return ListView.builder(
itemCount: postSnapshot.data.docs.length,
itemBuilder: (BuildContext context, int index) {
switch (postSnapshot.data.docs[index]["Type"]) {
case "Image":
return new ImageCard(
imageLink: postSnapshot.data.docs[index]
["ImageLink"],
imageDescription: postSnapshot.data.docs[index]
["ImageDescription"],
posterName: postSnapshot.data.docs[index]
["PosterName"],
);
break;
case "Text":
return new TextCard(
postText: postSnapshot.data.docs[index]
["PostText"],
posterName: postSnapshot.data.docs[index]
["PosterName"],
);
break;
Problem is here:
(postSnapshot.data.docs[index]["Type"])
You have to ensure first that you got the data from firestore. In your case when connection state is connecting or if snapshot has error you invoke docs on null object. Consider building widget tree with checks like this:
class UserInformation extends StatelessWidget {
#override
Widget build(BuildContext context) {
CollectionReference users = FirebaseFirestore.instance.collection('users');
return StreamBuilder<QuerySnapshot>(
stream: users.snapshots(),
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()['full_name']),
subtitle: new Text(document.data()['company']),
);
}).toList(),
);
},
);
}
}

Firebase Real Time Database triggers `null` error if there is no matching data

In my flutter code, I am trying to get data from the Firebase Real-Time Database. Below is my code.
final DatabaseReference reference = FirebaseDatabase.instance.reference().child('chat_room');
return Scaffold(
body: StreamBuilder(
stream:
reference.orderByChild("email").equalTo("abcd#test.com").onValue,
builder: (context, snapshot) {
if (snapshot == null || !snapshot.hasData) {
return Container(child: Center(child: Text("No data")));
} else {
Map<dynamic, dynamic> map = snapshot.data.snapshot.value;
return ListView.builder(
itemCount: map.values.toList().length,
itemBuilder: (context, index) {
String imageURL = map.values.toList()[index]["imageUrl"];
return Container(
margin: EdgeInsets.only(top: 10),
child: ListTile(
leading: CircleAvatar(
radius: 30.0,
backgroundImage: NetworkImage(imageURL),
backgroundColor: Colors.transparent,
),
title: Text(
map.values.toList()[index]["email"],
),
),
);
});
}
}),
);
Notice, I am loading data where the email is equal to abcd#test.com. The code works great if there are record for abcd#test.com. But if the database is empty or no records for abcd#test.com, I AM getting the below error
The following NoSuchMethodError was thrown building StreamBuilder<Event>(dirty, state: _StreamBuilderBaseState<Event, AsyncSnapshot<Event>>#ad47f):
The getter 'values' was called on null.
Receiver: null
Tried calling: values
The relevant error-causing widget was
StreamBuilder<Event>
package:xxx/…/chat/chat_list_supplier.dart:19
When the exception was thrown, this was the stack
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1 _ChatListSupplierState.build.<anonymous closure>
package:xxx/…/chat/chat_list_supplier.dart:28
How can I fix this?
The problem is that there is a snapshot, but the snapshot contains no data. It's easiest to catch this in:
builder: (context, snapshot) {
if (snapshot == null || !snapshot.hasData || snapshot.data.snapshot.value == null) {
return Container(child: Center(child: Text("No data")));
} else {
...

RangeError when querying for Document in Firebase

I'm trying to query for data in Firebase with the following method:
static Future<QuerySnapshot> getUserData(String creatorId) {
Future<QuerySnapshot> data = _firestore
.collection('users')
.where('creatorId', isEqualTo: creatorId)
.getDocuments();
return data;
}
I'm then trying to access the data via this FutureBuilder:
body: FutureBuilder(
future: DatabaseService.getUserData(widget.ride.creatorId),
//future: DatabaseService.getUserData(widget.ride.creatorId),
builder: (context, snapshot) {
// if (!snapshot.hasData) {
// }
//User user = User.fromDoc(snapshot.data);
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(
backgroundColor: Color(0xff192C43),
valueColor: AlwaysStoppedAnimation(
Color(0xff213a59),
),
),
);
}
User user = User.fromDoc(snapshot.data.documents[0]);
return SearchCardItemExtended(user: user, ride: widget.ride,);
},
),
There is always only one User with the same creatorId. That is why I am calling the document on [0].
When I tap on the button that calls the FutureBuilder I get the following Exception:
════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following RangeError was thrown building FutureBuilder<QuerySnapshot>(dirty, state: _FutureBuilderState<QuerySnapshot>#cff34):
RangeError (index): Invalid value: Valid value range is empty: 0
The relevant error-causing widget was:
FutureBuilder<QuerySnapshot> file:///C:/Users/Paul/AndroidStudioProjects/leaf/leaf/lib/screens/search_card_info.dart:61:13
When the exception was thrown, this was the stack:
#0 List.[] (dart:core-patch/growable_array.dart:149:60)
#1 _SearchCardInfoState.build.<anonymous closure> (package:leaf/screens/search_card_info.dart:80:59)
#2 _FutureBuilderState.build (package:flutter/src/widgets/async.dart)
#3 StatefulElement.build (package:flutter/src/widgets/framework.dart:4334:27)
#4 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4223:15)
...
════════════════════════════════════════════════════════════════════════════════════════════════════
A very similar query and FutureBuilder elsewhere in the Code work.
This is the other FutureBuilder:
body: FutureBuilder(
future: DatabaseService.searchRides(origin, destination, date, time),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(
backgroundColor: Color(0xff192C43),
valueColor: AlwaysStoppedAnimation(
Color(0xff213a59),
),
),
);
}
if (snapshot.data.documents.length == 0) {
return Center(
child: Text(
'Uppss...\n'
'Leider wurden keine passenden Fahrten gefunden.\n'
'Schau doch später noch mal vorbei.',
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: 'UbuntuLight',
fontSize: 14,
color: Color(0xffE6EFE9),
height: 1.6,
),
),
);
}
return ListView.builder(
physics: new BouncingScrollPhysics(),
itemCount: snapshot.data.documents.length,
itemBuilder: (BuildContext context, int index) {
Ride ride = Ride.fromDoc(snapshot.data.documents[index]);
return SearchCardItem(num: index, ride: ride);
},
);
},
),
What could be the problem here?
Jus change your code like this.
if (snapshot.hasData && snapshot.data.length>0) {
User user = User.fromDoc(snapshot.data.documents[0]);
//..Implement what you want here}
You are facing this error because there is no result from firebase then your are trying to call |0]but there is no element at 0. You have to wrap it in a conditinnal way. So it will be executed only when there are more then on user in snapshot.data
Plese check condition snapshot.data.documents.isEmpty or not
if(snapshot.data.documents.length!=0){
User user = User.fromDoc(snapshot.data.documents[0]);
return SearchCardItemExtended(user: user, ride: widget.ride,);
}
return new Container();

Resources