Flutter Firebase failed assertion: line 360 pos 10: 'data != null' - firebase

Widget BlogsList() {
return Container(
color: UniversalVariables.blackColor,
child: blogsStream != null
? Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
StreamBuilder(
stream: blogsStream,
builder: (context, snapshot) {
if (!snapshot.hasData || snapshot.data.documents.isEmpty) ;
return ListView.builder(
padding: EdgeInsets.symmetric(horizontal: 16),
itemCount: snapshot.data.documents.length,
shrinkWrap: true,
itemBuilder: (context, index) {
return BlogsTile(
authorName: snapshot
.data.documents[index].data['authorName'],
title: snapshot.data.documents[index].data["title"],
description:
snapshot.data.documents[index].data['desc'],
imgUrl:
snapshot.data.documents[index].data['imgUrl'],
);
});
},
)
],
)
: Container(
alignment: Alignment.center,
child: CircularProgressIndicator(),
),
); }
I want to make it mandatory. giving a red screen and open.I want to solve this problem. I am pulling data with Firebase. I'm having trouble switching between pages, but could not solve my error.

The error occurred is in your builder, you returned the ListView whether snapshot.hasData is true or not.
Try
builder: (context, snapshot) {
if (!snapshot.hasData || snapshot.data.documents.isEmpty){
return Center(child: Text("Loadin..."));
}
return ListView.builder(
padding: EdgeInsets.symmetric(horizontal: 16),
itemCount: snapshot.data.documents.length,
shrinkWrap: true,
itemBuilder: (context, index) {
return BlogsTile(
authorName: snapshot.data.documents[index].data['authorName'],
title: snapshot.data.documents[index].data["title"],
description:snapshot.data.documents[index].data['desc'],
imgUrl:snapshot.data.documents[index].data['imgUrl'],
);
});
},

Related

flutter on click download image from firebase

Here, when I add a new picture, it appears here and it can be opened to a full screen, but when I click I want to download the picture that I long pressed on to the phone storage
StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance.collection('gallery').snapshots(),
builder: (context, snapshot) {
return !snapshot.hasData ? Center(
child: CircularProgressIndicator(),
) : Container(
child: GridView.builder(
itemCount: snapshot.data!.docs.length,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3
),
itemBuilder: (context, index) {
return Container(
margin: EdgeInsets.all(3),
child: FullScreenWidget(
backgroundColor: Colors.white,
child: FadeInImage.assetNetwork(
fit: BoxFit.contain,
placeholder: 'assets/loading.gif',
imageErrorBuilder:
(context, error, stackTrace) {
return Image.asset(
'assets/error.gif',
fit: BoxFit.fitWidth);
},
image: snapshot.data!.docs[index].get('url')),
),
);
}),
);
},
);

admob bannerads do not show in dynamic list

I am trying to display a bannerAd between every 3 posts. But ads do not show. I presume, that the list could be empty, as this list is a list build from the posts user likes and saves.
#override
Widget build(BuildContext context) {
return Expanded(
child: ListView(
padding: EdgeInsets.symmetric(horizontal: 10.0),
children: [
StreamBuilderWrapper(
shrinkWrap: true,
stream: postRef
.where("bookmarks",
arrayContains: FirebaseAuth.instance.currentUser.uid)
.orderBy('timestamp', descending: true)
.snapshots(),
physics: NeverScrollableScrollPhysics(),
itemBuilder: (_, DocumentSnapshot snapshot) {
internetChecker(context);
Review posts = Review.fromJson(snapshot.data());
return Padding(
padding: const EdgeInsets.only(bottom: 10.0),
child: Posts(post: posts),
);
},
),
ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemBuilder: (context, index) {
return Column(
children: [
if (index % 3 == 0 && index != 0)
AdWidget(ad: ad)
],);})
]));
}
This is my first time working with flutter, and i am new to coding. I am trying to display the bannerAds, however, they do not show and no log is displayed. This is probably due to the render error I have:
The following _CastError was thrown during paint():
Null check operator used on a null value
The relevant error-causing widget was:
ListView
When the exception was thrown, this was the stack:
#0 RenderViewportBase._paintContents
(package:flutter/src/rendering/viewport.dart:653:25)
#1 RenderViewportBase.paint
(package:flutter/src/rendering/viewport.dart:645:7)
#2 RenderObject._paintWithContext
(package:flutter/src/rendering/object.dart:2317:7)
#3 PaintingContext._repaintCompositedChild
(package:flutter/src/rendering/object.dart:139:11)
#4 PaintingContext.repaintCompositedChild
(package:flutter/src/rendering/object.dart:100:5)
...
The following RenderObject was being processed when the exception was
fired:
RenderViewport#ae00e
... needs compositing
... parentData: <none> (can use size)
... constraints: BoxConstraints(w=360.0, h=507.0)
... layer: OffsetLayer#0dfc7 DETACHED
... engine layer: Null#007db
... offset: Offset(0.0, 0.0)
... size: Size(360.0, 507.0)
... axisDirection: down
... crossAxisDirection: right
... offset: ScrollPositionWithSingleContext#1c5d2(offset: 0.0, range:
null..null, viewport: 507.0, ScrollableState,
AlwaysScrollableScrollPhysics
-> ClampingScrollPhysics -> RangeMaintainingScrollPhysics,
IdleScrollActivity#40f4c, ScrollDirection.idle)
I am confused with the widgets and views. Help me, please! Thank you!
i didn't understand clearly what you re doing, i assume you re doing this wrong way,I edited the whole code this may help .
#override
Widget build(BuildContext context) {
return Expanded(
child: StreamBuilder(
stream: postRef
.where("bookmarks",
arrayContains: FirebaseAuth.instance.currentUser!.uid)
.orderBy('timestamp', descending: true)
.snapshots(),
builder: (_, DocumentSnapshot snapshot) {
if (snapshot.hasData) {
return ListView.separated(itemCount: snapshot.data.docs.length,
itemBuilder: (
context,
index,
) {
internetChecker(context);
Review posts = Review.fromJson(snapshot.data());
return Padding(
padding: const EdgeInsets.only(bottom: 10.0),
child: Posts(post: posts),
);
}, separatorBuilder: (context, index) {
if (index % 3 == 0 && index != 0)
return
AdWidget(ad: ad);
}, );
}else if (snapshot.hasError) {
return Center(
child: Text("error"),
);
} else {
return Center(
child: Text("loading"),
);
}
},
),);

The getter 'documents' was called on null shown for a while

Im trying to retrieve name of user from firebase on appBar. It successfully retrieves it. But it displays an error on screen for few seconds before showing name of user successfully. The error os
I/flutter (24143): The following NoSuchMethodError was thrown building
StreamBuilder(dirty, state:
I/flutter (24143): _StreamBuilderBaseState<QuerySnapshot,
AsyncSnapshot>#c10cf):
I/flutter (24143): The getter 'documents' was called on null.
I/flutter (24143): Receiver: null
I/flutter (24143): Tried calling: documents
Class Data{
Widget build(BuildContext context) {
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
]);
CurrentUser _currentUser = Provider.of<CurrentUser>(context, listen: false);
return Scaffold(
backgroundColor: Colors.grey[600],
resizeToAvoidBottomPadding: false,
appBar: AppBar(
title: Text('Property Host'),
centerTitle: true,
actions: <Widget>[
Expanded(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Container(
margin: new EdgeInsets.only(left: 50),
child: Text('Property Host',style: TextStyle(fontWeight: FontWeight.bold,fontSize: 19),)),
StreamBuilder(stream: Firestore.instance.collection('users').where("uid", isEqualTo: userid).snapshots(),
// ignore: missing_return
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.data == null)
CircularProgressIndicator();
//final userDocument = snapshot.data;
//final title= snapshot.data.userocument['displayName']);
//CircularProgressIndicator();
return Expanded(
child: ListView.builder(
itemCount: snapshot.data.documents.length,
// ignore: missing_return
itemBuilder: (BuildContext context, int index) {
print(user.uid);
return user != null
? Container(
margin: EdgeInsets.only(top: 17, left: 40),
child: Text(
snapshot.data.documents.elementAt(index)['displayName']),
)
: IconButton(
icon: Icon(Icons.person),
// ignore: missing_return
onPressed: () {
Navigator.pushNamed(context, '/LoginScreen');
},
);
}
),
);
}
Use snapshot.hasData to ensure that you build the main widget (Expanded) after the data has been retrieved and use CircularProgessIndicator to hold its position before the data is returned
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasData){
return Expanded(
child: ListView.builder(
itemCount: snapshot.data.documents.length,
// ignore: missing_return
itemBuilder: (BuildContext context, int index) {
print(user.uid);
return user != null
? Container(
margin: EdgeInsets.only(top: 17, left: 40),
child: Text(
snapshot.data.documents.elementAt(index)['displayName']),
)
: IconButton(
icon: Icon(Icons.person),
// ignore: missing_return
onPressed: () {
Navigator.pushNamed(context, '/LoginScreen');
},
);
}
),
);
}
else {
return CircularProgressIndicator();
}
}

how to convert the data coming from snapshot into List to fit in this column?

my this code is showing me error that querysnapshot is not a subtype of a list. can you edit my code and tell me how to make this error free.
buildProfilePosts() {
if (_isLoading) {
return Center(
child: Text(
"Loading...",
style: TextStyle(fontFamily: "QuickSand"),
),
);
}
return StreamBuilder(
stream: postsRef.document(widget.profileId).collection('userPosts').orderBy('timestamp', descending: true).snapshots(),
builder: (context, snapshot) {
return Column(
children: snapshot.data,
);
}
);
}
children is a property inside the widget Column, it takes a list of widgets. You should do the following:
child: Column(children: <Widget>[
StreamBuilder(
stream: postsRef.document(widget.profileId).collection('userPosts').orderBy('timestamp', descending: true).snapshots(),,
builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return ListView.builder(
shrinkWrap: true,
itemCount: snapshot.data.documents.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
contentPadding: EdgeInsets.all(8.0),
title:
Text(snapshot.data.documents[index].data["name"]),
);
});
} else if (snapshot.connectionState == ConnectionState.none) {
return Text("No data");
}
return CircularProgressIndicator();
},
),
]),
Assuming you have a name field in your document.
Try
Column(
children: <Widget>[
...List.generate(
snapshot.data.length,
(index) {
return Container(
child: Text(snapshot.data[index].yourobject),
);
},
),
],
),

NoSuchMethodError: Class 'QuerySnapshot' has no instance method '[]'

Im trying to get posts(images) for every user.User's id are stored in posts collection and every userid document will have a subcollection will contains all posts document.but im getting this error.
The following NoSuchMethodError was thrown building:
Class 'QuerySnapshot' has no instance method '[]'.
Receiver: Instance of 'QuerySnapshot'
Tried calling: []("mediaUrl")
this is the code.
getPost(){
return FutureBuilder(
future: Firestore.instance.collection('posts').document(user.id
).collection('userPosts').getDocuments(),
// ignore: missing_return
builder: (context,snapshot) {
if (snapshot.hasData) {
return
Container(
height: 200,
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[ListView.builder(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
itemCount: snapshot.data.documents.length,
itemBuilder: (context, index) {
child: Image.network(snapshot.data["mediaUrl"],)
);
}
),
],
),
);
}
if (!snapshot.data ) {
return Text('No posts');
} else {
return CircularProgressIndicator();
}
}
);
}`
If your media url is inside a document then try this :
Image.network(snapshot.data.documents[index]["mediaUrl"],)
Full code with another approach :
getPost(){
return FutureBuilder(
future: Firestore.instance.collection('posts').document(user.id
).collection('userPosts').getDocuments(),
// ignore: missing_return
builder: (context,snapshot) {
if (snapshot.hasData) {
return
Container(
height: 200,
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[ListView.builder(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
itemCount: snapshot.data.documents.length,
itemBuilder: (context, index) {
DocumentSnapshot docSnapshot = snapshot.data.documents[index];
return Image.network(docSnapshot["mediaUrl"],)
);
}
),
],
),
);
}
if (!snapshot.data ) {
return Text('No posts');
} else {
return CircularProgressIndicator();
}
}
);
}

Resources