简体   繁体   中英

'Null check operator used on a null value' while creating Interstitial Ads

I'm trying to add an interstitial ads, but got 'Null check operator used on a null value' error.

Error

E/flutter (21082): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Null check operator used on a null value

Code problem

onTap: () async {
                    isInterstitialVideoAvailable =
                        (await FlutterApplovinMax.isInterstitialLoaded(
                            listener!))!;

                    if (isInterstitialVideoAvailable) {
                      FlutterApplovinMax.showInterstitialVideo(
                          (AppLovinAdListener? event) => listener!(event));
                    }

Main code involved

class CollectionCard extends StatefulWidget {
  const CollectionCard();

  @override
  State<CollectionCard> createState() => _CollectionCardState();
}

class _CollectionCardState extends State<CollectionCard> {
  AppLovinListener? get listener => null;

  // AppLovinListener get listener => null;

  void initState() {
    super.initState();
    FlutterApplovinMax.initInterstitialAd('91b26a5859e1b480');
  }

  bool isInterstitialVideoAvailable = false;

  @override
  Widget build(BuildContext context) {
    var size = MediaQuery.of(context).size;

    /*24 is for notifications bar on Android */
    final double itemHeight = (size.height - kToolbarHeight - 28) / 2;
    final double itemWidth = size.width / 4;

    // var len = listener?.length ?? 0;

    return Container(
        child: Padding(
      padding: const EdgeInsets.fromLTRB(10.0, 0.0, 10.0, 10.0),
      child: Column(
        children: <Widget>[
          GridView.count(
            primary: true,
            padding: const EdgeInsets.fromLTRB(20, 0, 20, 20),
            crossAxisSpacing: 10, //Reduce Horizontal Spacing
            mainAxisSpacing: 10, //Reduce Vertical Spacing
            crossAxisCount: 3,
            physics: ScrollPhysics(),
            childAspectRatio: (6 / 8),
            // (itemWidth / itemHeight),
            shrinkWrap: true,
            children: <Widget>[
              Card(
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(15.0),
                ),
                elevation: 2,
                color: Theme.of(context).scaffoldBackgroundColor,
                child: InkWell(
                   onTap: () async {
                    isInterstitialVideoAvailable =
                        (await FlutterApplovinMax.isInterstitialLoaded(
                            listener!))!;

                    if (isInterstitialVideoAvailable) {
                      FlutterApplovinMax.showInterstitialVideo(
                          (AppLovinAdListener? event) => listener!(event));
                    }


                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (ctx) => LearnPage(),
                      ),
                    );
                  },
                  child: Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [
                        ImageIcon(
                          AssetImage('assets/icons/learn.png'),
                          color: kLightPrimary,
                          size: 60,
                        ), // Icon(
                        //   layout.icon,
                        //   size: 40,
                        // ),
                        Text(
                          'Learn',
                          style: TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),

Can anyone provide a solution for this?

You have to init a Interstitial Ads before use it,

Example:

Init Ads on initState()

InterstitialAd? _interstitialAd;
int _countMaxAdFailedToLoad = 3;
int _countAdInitialToLoad = 0;

@override
void initState() {
  super.initState();
  _createAds();
}

void _createAds(){
  InterstitialAd.load(
    adUnitId: Platform.isAndroid 
      ? 'ca-app-pub-3940256099942544/1033173712' 
      : 'ca-app-pub-3940256099942544/4411468910',
    request: AdRequest(),
    adLoadCallback: InterstitialAdLoadCallback(
      onAdLoaded: (InterstitialAd ad) {
        _interstitialAd = ad;
        _countAdInitialToLoad = 0;
      },
      onAdFailedToLoad: (LoadAdError error) {
        print('InterstitialAd failed to load: $error');
        _countAdInitialToLoad += 1;
        _interstitialAd = null;
        if (_countAdInitialToLoad >= _countMaxAdFailedToLoad) {
          _createInterstitialAds();
        }
      },
    ),
  );
}

And you can show this ads.

onTap: (){
if (_interstitialAd != null) {
   _interstitialAd?.fullScreenContentCallback =
       FullScreenContentCallback(
         onAdDismissedFullScreenContent: (InterstitialAd ad) {
           print('$ad onAdDismissedFullScreenContent.');
           ad.dispose();
           _createAds();
        }, 
         onAdFailedToShowFullScreenContent:
           (InterstitialAd ad, AdError error) {
           print('$ad onAdFailedToShowFullScreenContent: $error');
           ad.dispose();
           _createAds();
              });
     _interstitialAd?.show();
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM