admob bannerads do not show in dynamic list - firebase

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

Related

How can use firestore using where and orderby in flutter?

How can use firestore using where and orderby in flutter?
When I wanna to use both, I got the error.
Exception has occurred.
_CastError (Null check operator used on a null value)
code
StreamBuilder(
stream: FirebaseFirestore.instance
.collection('Posts')
.where('country', isEqualTo: user.country)
//.where('country', isEqualTo: 'Australia')
.orderBy('time', descending: true)
.snapshots(),
builder: (context,
AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(
child: CircularProgressIndicator(),
);
}
//print(user.country);
return ListView.builder(
itemCount: snapshot.data!.docs.length,
itemBuilder: (context, index) => Container(
margin: EdgeInsets.symmetric(
horizontal: width > webScreenSize ? width * 0.3 : 0,
vertical: width > webScreenSize ? 15 : 0),
child: PostCard(
snap: snapshot.data!.docs[index],
),
),
);
},
So, why I could not got the data? I'd got the user.value.
The problem is that you're telling Flutter that snapshot.data is guaranteed to have a value, when in reality it doesn't here:
return ListView.builder(
itemCount: snapshot.data!.docs.length,
I recommend reading the documentation for StreamBuilder again, as there are many more states than snapshot.connectionState == ConnectionState.waiting that you need to handle.
For example, there could be an error, or there could be no data for another reason:
StreamBuilder(
stream: FirebaseFirestore.instance
.collection('Posts')
.where('country', isEqualTo: user.country)
.orderBy('time', descending: true)
.snapshots(),
builder: (context, AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(
child: CircularProgressIndicator(),
);
}
// 👇 Handle error
if (snapshot.hasError) {
return const Center(
child: Text(snapshot.error),
);
}
// 👇 Handle lack of data
if (!snapshot.hasData) {
return const Center(
child: Text("Something when wrong - no data available"),
);
}
return ListView.builder(
itemCount: snapshot.data!.docs.length,
itemBuilder: (context, index) => Container(
margin: EdgeInsets.symmetric(
horizontal: width > webScreenSize ? width * 0.3 : 0,
vertical: width > webScreenSize ? 15 : 0),
child: PostCard(
snap: snapshot.data!.docs[index],
),
),
);

How to show data in Flutter from Firestore collection based on the value in the array?

I need to remove documents - reviews/posts - from the stream, which the user has hidden. When a user decides to hide the post, the post collection's post-doc creates an array 'hidingUserId' of userIDs that has hidden it. refer to the pic, pls.
now I need to remove the post where the array 'hidingUserId' contains the currentUserId. I have tried the following, but it does not display errors in the log and it does not display the posts. Just circular progress circling on the screen.
Stream streams = postRef
.orderBy('stars', descending: false)
.orderBy('timestamp', descending: true)
.snapshots();
#override
Widget build(BuildContext context) {
return ListView(
shrinkWrap: true,
padding: EdgeInsets.symmetric(horizontal: 10.0),
children: [
StreamBuilderWrapper(
shrinkWrap: true,
stream: streams.where((event) => event.data()['hidingUserId']
== null
|| event.data()['hidingUserId'].contains(!currentUserId()) ?
streams.forEach((event) => print(event))
: Container(
child: Center(
child: Text('Nothing to show'),))),
physics: NeverScrollableScrollPhysics(),
itemBuilder: (_, DocumentSnapshot snapshot) {
internetChecker();
Review posts = Review.fromJson(snapshot.data());
return posts.postId != null
? Padding(
padding: const EdgeInsets.only(bottom: 12.0),
child: Posts(post: posts),
)
: Container(
child: Center(
child: Text('Nothing to show'),
),
);
},
),
],
);
}
am new to Firestore, and I can't find the information I need. help appreciated very much! Thanks!

How to retrieve data from Firebase Realtime to the flutter app in a lisview

I am looking to retrieve data stored in Firebase Realtime database and display it in a new page in a lisview, how can I achieve that. So far I can retrieve and print it out in a console terminal.
My code is below:
class BarcodesResultPreviewWidget extends StatelessWidget {
FirebaseDatabase.instance.reference().child('ScannedResults');
body: Column(
children: <Widget>[
previewView,
//printing scanned results
Expanded(
child: ListView.builder(
itemBuilder: (context, position) {
return BarcodeItemWidget(preview.barcodeItems[position]);
},
itemCount: preview.barcodeItems.length,
),
),
FlatButton(
color: Colors.grey,
child: Text('Save',),
onPressed: () {
databaseRef.push().set({
'ScannedItem': preview.barcodeItems
.map((barCodeItem) => barCodeItem.toJson())
.toString(),
});
},
),
To fetch the data into a new page and build listview, try something like this:
return Scaffold(
body: FutureBuilder(
future: databaseRef.once(),
// future: FirebaseDatabase.instance
// .reference()
// .child("ScannedResults")
// .once(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.connectionState == ConnectionState.waiting)
return new Text('Loading....');
if (snapshot.hasError) return new Text('Error: ${snapshot.error}');
List scannedItemsValues = [];
snapshot.data.value.forEach(
(_, values) => scannedItemsValues.add(values["ScannedItem"]));
print(scannedItemsValues);
return ListView.builder(
itemCount: scannedItemsValues.length,
itemBuilder: (BuildContext context, int index) {
// build your listView here
print(scannedItemsValues[index]);
return Text(scannedItemsValues[index]);
},
);
},
),
);

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

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

Gridview.builder with Firebase realtime database and futurebuilder

Coming from Firestore, I am a little bit struggling how to receive data from Firebase real time database. I just want a nice grid view of images which are loaded from the realtime database.
Error: flutter: The following NoSuchMethodError was thrown building:
flutter: Class 'DataSnapshot' has no instance method '[]'.
flutter: Receiver: Instance of 'DataSnapshot'
I guess it's index related. No idea how to correctly map it within a list.
import 'package:cached_network_image/cached_network_image.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
class Test extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new Container(
alignment: Alignment.center,
padding: const EdgeInsets.all(16.0),
child: new FutureBuilder(
future: FirebaseDatabase.instance
.reference()
.child('messages')
.child('1551276762582')
.orderByChild('messagetype')
.equalTo('1')
.once(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
if (snapshot.data != null) {
return new Column(
children: <Widget>[
new Expanded(
child: new GridView.builder(
// itemCount: item.length,
gridDelegate:
new SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2),
itemBuilder: (context, index) {
return GridTile(
child: CachedNetworkImage(
imageUrl: snapshot.data[index]['imageUrl']
.toString()));
},
),
)
],
);
} else {
return new CircularProgressIndicator();
}
} else {
return new CircularProgressIndicator();
}
}));
}
}
I could solve it with the following code. Again, I have to say that the Firebase documentation really lacks, which is quite disappointing, since Firebase is a great tool. Moreover, I do not understand, that there is no documentation on 'How to use Firebase with Flutter' (we are talking about both Google products.) Notwithstanding, here is the working code for anyone, who likes to use Streambuilder with Gridview.builder with the Realtime Database in Flutter:
StreamBuilder(
stream: FirebaseDatabase.instance
.reference()
.child('messages')
.child(groupId)
.orderByChild('messagetype')
.equalTo(1)
.onValue,
builder: (BuildContext context, AsyncSnapshot<Event> snapshot) {
if (snapshot.hasData) {
if (snapshot.data.snapshot.value != null) {
Map<dynamic, dynamic> map = snapshot.data.snapshot.value;
List<dynamic> list = map.values.toList()
..sort(
(a, b) => b['timestamp'].compareTo(a['timestamp']));
return GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3),
itemCount: list.length,
padding: EdgeInsets.all(2.0),
itemBuilder: (BuildContext context, int index) {
return Container(
child: GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SecondScreen(
imageUrl: list[index]["imageUrl"])),
);
},
child: CachedNetworkImage(
imageUrl: list[index]["imageUrl"],
fit: BoxFit.cover,
),
),
padding: EdgeInsets.all(2.0),
);
},
);
} else {
return Container(
child: Center(
child: Text(
'Es wurden noch keine Fotos im Chat gepostet.',
style: TextStyle(fontSize: 20.0, color: Colors.grey),
textAlign: TextAlign.center,
)));
}
} else {
return CircularProgressIndicator();
}
})),
Something that I do that helps me solve issues, is by explicitly turning snapshots into Maps the following way.
Map yourModel = Map.from(datasnapshot);
also many times when handling null data or so on I have to turn the asyncSnap value that comes from the future Builder into a Datasnapshot from firebase in the following way
Datasnapshot snap = asyncSnap.data;
then handle for snap being null
if(snap.value!=null){}
Hope this helps! if you need help send me a message

Resources