How to fix flutter firestore stream builder error? - firebase

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'));
}
},
));

Related

Failed assertion: line 1702 pos 12: 'center!.parent == this': is not true

What is the reason for getting the error?
And when I put the debug flag in the Streambuilder line, my application freezes before it comes to the main screen.
body: CustomScrollView(
slivers: [
StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection('posts')
.limit(10)
.orderBy('id', descending: true)
.snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> dataSnapshot) {
return !dataSnapshot.hasData
? SliverToBoxAdapter(
child: linearProgress(),
)
: SliverStaggeredGrid.countBuilder(
crossAxisCount: 1,
staggeredTileBuilder: (val) => StaggeredTile.fit(1),
itemBuilder: (context, index) {
DataModel model = DataModel.fromJson(
dataSnapshot.data!.docs[index].data()
as Map<String, dynamic>);
return sourceInfo(model, context);
},
itemCount: dataSnapshot.data!.docs.length);
},
),
],
),
There was no problem when I imported the relevant codes into SliverPadding. Edited code.
StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection('posts')
.limit(10)
.orderBy('id', descending: true)
.snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> dataSnapshot) {
return !dataSnapshot.hasData
? SliverPadding(
sliver: SliverToBoxAdapter(
child: ColorLoader(),
),
padding: EdgeInsets.all(0),
)
: SliverPadding(
sliver: SliverStaggeredGrid.countBuilder(
crossAxisCount: 1,
staggeredTileBuilder: (_) => StaggeredTile.fit(1),
itemBuilder: (context, index) {
DataModel model = DataModel.fromJson(
dataSnapshot.data!.docs[index].data()
as Map<String, dynamic>);
return sourceInfo(model, context);
},
itemCount: dataSnapshot.data!.docs.length),
padding: EdgeInsets.all(0),
);
},
),
According to this comment in a Github thread for a similar issue if the sliver being replaced is not the first it should work fine.
So a possible workaround is to add empty SliverToBoxAdapter() as first sliver before BodyContent().
There is more information and possible solutions in the Github thread, I recommend taking a look at it.

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.

Flutter Firebase: Getting snapshot's data in flutter not working

I'm trying to get the length for ListViewBuilder ItemCount with snapshot.data.docs.length but I get the error:
"The getter 'docs' isn't defined for the class 'Object'."
Here is my code:
StreamBuilder<Object>(
stream: FirebaseFirestore.instance.collection('recipe').doc(_user).collection('Food').snapshots(),
builder: (context, snapshot) {
return ListView.builder(
padding: EdgeInsets.only(left: 15),
shrinkWrap: true,
scrollDirection: Axis.horizontal,
itemCount: snapshot.data.docs.length,
itemBuilder: (context, index) {
return RecipeCards(
);
},
);
}
),
I solved the problem by using:
StreamBuilder<QuerySnapshot>
Instead of:
StreamBuilder<Object>

i got this error when i am trying to use snapshot.data.docs.length in listview.buider: The getter 'docs' isn't defined for the type 'Object'

I am trying to fetch data from firebase to list all the documents in a listview builder the code is still not completed in term of displaying the database filed in the code. this is the error: The getter 'docs' isn't defined for the type 'Object'
Container(
child: StreamBuilder<Object>(
stream: _firestore
.collection('Patient')
.doc(_auth.currentUser.email)
.collection("Diabetes")
.snapshots(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
reverse: true,
shrinkWrap: true,
itemCount:
snapshot.data.docs.length, // here is the error "docs"
itemBuilder: (context, index) {
DocumentSnapshot documentSnapshot =
snapshot.data.docs[index]; // also another error "docs"
return Container();
});
}
return Center(
child: CircularProgressIndicator(),
);
}),
)
You should replace snapshot.data.docs.length with snapshot.data.length
Container(
child: StreamBuilder<Object>(
stream: _firestore
.collection('Patient')
.doc(_auth.currentUser.email)
.collection("Diabetes")
.snapshots(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
reverse: true,
shrinkWrap: true,
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
DocumentSnapshot documentSnapshot = snapshot.data[index];
return Container();
});
}
return Center(
child: CircularProgressIndicator(),
);
}),
)
I solved the problem by replacing StreamBuilder<Object> with StreamBuilder<QuerySnapshot>. by default the StreamBuilder comes in this form StreamBuilder<Object>

Error: Class '_JsonDocumentSnapshot' has no instance getter 'docs'

i am trying to get list of a particular uid document from firebase here is the code
StreamBuilder(
stream: firestore
.collection('interest')
.doc('${auth.currentUser.uid}')
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
}
return ListView.builder(
itemCount: snapshot.data.docs.length,
itemBuilder: (context, index) {
return Container();
});
}),
Error:
Class '_JsonDocumentSnapshot' has no instance getter 'docs'.
Receiver: Instance of '_JsonDocumentSnapshot'
Tried calling: docs
my collection
i am try to get the list from this document uid
Thanks
I had a similar issue and I tried using explicit (BuildContext context, AsyncSnapshot snapshot) and it worked for me, also I create the listview without the builder:
ListView(
children: myList.map((object) {
return myWidget(object: object);
}).toList(),

Resources