You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何在GridView末尾添加BannerAd广告?

Add BannerAd at the Bottom of GridView in Flutter

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 itemCount to homeList.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 StatefulWidget ensures we properly initialize and dispose the ad, preventing memory leaks.
  • Spacing: Adjust the margin on 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 10:07:48