'How to add adaptive banner ads in my flutter app using google mobile ads?
I am using google_mobile_ads with flutter. I want to know how to add adaptive banner ads. this is my code.
@override
Widget build(BuildContext context) {
TargetPlatform os = Theme.of(context).platform;
BannerAd banner = BannerAd(
listener: BannerAdListener(
onAdFailedToLoad: (Ad ad, LoadAdError error) {},
onAdLoaded: (_) {},
),
size: AdSize.banner,
adUnitId: UNIT_ID[os == TargetPlatform.iOS ? 'ios' : 'android']!,
request: AdRequest(),
)..load();
return Scaffold(
appBar: AppBar(…),
body:SafeArea(
child: Column(
children:[
SizedBox(…),
SizedBox(
child:AdWidget(
ad:banner)
),))]
Solution 1:[1]
Try this:
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);
@override
_BodyState createState() => _BodyState();
}
class _BodyState extends State< HomeScreen > {
BannerAd? _bannerAd = BannerAd(
adUnitId: Platform.isAndroid
? 'ca-app-pub-3940256099942544/6300978111'
: 'ca-app-pub-3940256099942544/2934735716',
size: AdSize.banner,
request: AdRequest(),
listener: BannerAdListener(),
);
@override
void initState() {
super.initState();
_bannerAd?.load();
}
@override
Widget build(BuildContext context) {
return Column(
children: [
Container(
alignment: Alignment.center,
child: AdWidget(ad: _bannerAd!);,
width: size.width,
height: 70,
),
],
);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Saitoh Akira |
