Flutter中如何在GridView末尾添加BannerAd广告?
Hey there! Let's get that banner ad showing up when your GridView scrolls to the bottom. I'll break this down step by step so it's easy to follow as a Flutter beginner.
Step 1: Prepare the BannerAd Instance
First, you'll need to create and manage the BannerAd in your widget's state. Make sure your screen is a StatefulWidget (if it isn't already), then add this to your State class:
import 'package:admob_flutter/admob_flutter.dart'; class YourHomeScreenState extends State<YourHomeScreen> { BannerAd? _bannerAd; @override void initState() { super.initState(); // Initialize the banner ad _bannerAd = BannerAd( adUnitId: "your_ad_unit_id_here", // Replace with your actual AdMob ad unit ID size: AdmobBannerSize.BANNER, listener: (AdmobAdEvent event, Map<String, dynamic>? args) { // Optional: Handle ad events like loading status or errors switch (event) { case AdmobAdEvent.loaded: print('Banner ad loaded successfully'); break; case AdmobAdEvent.failedToLoad: print('Failed to load banner ad: ${args?['error']}'); break; default: break; } }, ); _bannerAd?.load(); } @override void dispose() { // Dispose the ad to free up resources when the widget is destroyed _bannerAd?.dispose(); super.dispose(); } // Your existing build method goes here }
Step 2: Modify the GridView to Include the Banner Ad
Now update your GridView.builder to add the banner as the last item. Here are the key changes:
- Increase
itemCounttohomeList.length + 1(to make space for the ad) - In
itemBuilder, check if we're at the last index — return the banner ad here, otherwise return your existing task card
Here's the updated GridView code:
GridView.builder( itemCount: homeList.length + 1, // Add 1 slot for the banner ad gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, mainAxisSpacing: 20, ), itemBuilder: (ctx, i) { // Check if we're at the last position (ad slot) if (i == homeList.length) { return Container( margin: EdgeInsets.symmetric(vertical: 10, horizontal: 11), child: AdmobBanner( ad: _bannerAd!, adSize: AdmobBannerSize.BANNER, ), ); } // Return your original task card for all other items return GestureDetector( onTap: () async { // Your existing onTap logic remains unchanged if (i == 0) { if (await interstitialAd.isLoaded) { interstitialAd.show(); } else { dailyRewardAlert(context); } } else if (i == 1) { FlutterPollfish.instance.show(); } else if (i == 2) { sendInvite(); } else if (i == 3) { hideBannerAd(); Navigator.push(context, MaterialPageRoute(builder: (context) => Roulette())); } else if (i == 4) { hideBannerAd(); Navigator.push(context, MaterialPageRoute(builder: (context) => Scratch())); } }, child: Container( // Your existing task card UI remains unchanged decoration: BoxDecoration( borderRadius: const BorderRadius.all(Radius.circular(16.0)), ), width: 150, margin: const EdgeInsets.symmetric(horizontal: 11.0), child: Container( child: ClipRRect( borderRadius: BorderRadius.circular(19.0), child: Stack( children: <Widget>[ Positioned.fill( child: Image.asset( homeList[i].imagePath, fit: BoxFit.cover, ), ), Positioned( bottom: 0, left: 0, right: 0, child: Container( padding: EdgeInsets.symmetric( horizontal: 9.0, vertical: 5.0), decoration: BoxDecoration( gradient: LinearGradient( colors: [ const Color(0xFFFF8C3B), const Color(0xFFFE524B) ], begin: Alignment.centerLeft, end: Alignment.centerRight, ), borderRadius: BorderRadius.only( topRight: Radius.circular(15))), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text( "${homeList[i].taskTitle}", style: TextStyle( fontFamily: "Netflix", fontWeight: FontWeight.w600, fontSize: 17, letterSpacing: 0.27, color: Colors.white, ), ), ], ), ), ), ], ), ), ), ), ); }, ),
Step 3: Quick Tips for Beginners
- Test Ad Unit ID: For testing, use AdMob's official test ID (e.g.,
ca-app-pub-3940256099942544/6300978111) instead of your live ID to avoid policy issues. - State Management: Using a
StatefulWidgetensures we properly initialize and dispose the ad, preventing memory leaks. - Spacing: Adjust the
marginon the ad container to match your app's design and avoid clipping.
That's all! Now when users scroll to the bottom of your GridView, the banner ad will appear. Let me know if you hit any snags — happy coding!
内容的提问来源于stack exchange,提问作者Simran Aswani
相关产品推荐
相关产品推荐

