Make onPressed wait for ads to be loaded

277 Views Asked by At

let me tell you the process I want and what is happening

Process: Press the ElevatedButton then show adScreenLoadingDialog till _isAdLoaded=true then display the ad and go to the next screen.

What is happening: there are two conditions:

First, if the user opens the screen and scrolls or waits for maybe 5 seconds, Then clicks on ElevatedButton, The process works fine everything is ok.

Second, if the user opens the screen and clicks on ElevatedButton immediately, Then adScreenLoadingDialog appears but the process stops because _isAdLoaded is not true yet and the process goes wrong.

What I need your help for: How to make onPressed display adScreenLoadingDialog and wait till _isAdLoaded become true so the ad is ready to display and go to the next screen.

I tried to use while loop but it didn't work.

I really appreciate it if someone could help.

Thanks

This is my screen code

import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';

class BusTest extends StatefulWidget {
  @override
  _BusTestState createState() => _BusTestState();
}

class _BusTestState extends State<BusTest> {
  ////////////////////ADS////////////////
  InterstitialAd _interstitialAd;
  bool _isAdLoaded = false;

  ///ToDo  Interstitial Ad Unite
  void _initAd() {
    InterstitialAd.load(
      adUnitId: 'ca-app-pub-3940256099942544/1033173712',
      request: AdRequest(),
      adLoadCallback: InterstitialAdLoadCallback(
        onAdLoaded: onAdLoaded,
        onAdFailedToLoad: (error) {
          print(error);
        },
      ),
    );
  }

  void onAdLoaded(InterstitialAd ad) {
    _interstitialAd = ad;
    _isAdLoaded = true;
    _interstitialAd.fullScreenContentCallback = FullScreenContentCallback(
      onAdDismissedFullScreenContent: (ad) {
        _initAd();
        //_interstitialAd.dispose();
      },
      onAdFailedToShowFullScreenContent: (ad, error) {
        _initAd();
        //_interstitialAd.dispose();
      },
    );
  }

  ////////////////////ADS////////////////

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text(
          "Bus Test",
          style: TextStyle(
            fontSize: 20,
          ),
        ),
      ),

      body: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 16),
              child: Column(
                children: [
                  ElevatedButton(
                    style: ButtonStyle(
                      shape: MaterialStateProperty.all(
                        RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(10),
                        ),
                      ),
                      maximumSize: MaterialStateProperty.resolveWith(
                        (states) {
                          if (states.contains(MaterialState.disabled)) {
                            return Size(double.infinity, 60);
                          }
                          return Size(double.infinity, 60);
                        },
                      ),
                      padding: MaterialStateProperty.all(EdgeInsets.all(0)),
                      backgroundColor: MaterialStateProperty.resolveWith(
                        (states) {
                          // If the button is pressed, return green, otherwise blue
                          if (states.contains(MaterialState.pressed)) {
                            return Color(0xff795368);
                          }
                          return Color(0xff3E2A35);
                        },
                      ),
                    ),
                    onPressed: () async {
                      adScreenLoadingDialog(context);
                      if (_isAdLoaded) {
                        await _interstitialAd.show();
                        Navigator.pop(context);
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => BusTest1(),
                          ),
                        );
                      }
                    },
                    child: Container(
                      height: 40,
                      child: Center(
                        child: Text(
                          'Bus Test 1',
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: 15,
                          ),
                          textAlign: TextAlign.center,
                        ),
                      ),
                    ),
                  ),
                  SizedBox(
                    height: 10,
                  ),
                  ElevatedButton(
                    style: ButtonStyle(
                      shape: MaterialStateProperty.all(
                        RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(10),
                        ),
                      ),
                      maximumSize: MaterialStateProperty.resolveWith(
                        (states) {
                          if (states.contains(MaterialState.disabled)) {
                            return Size(double.infinity, 60);
                          }
                          return Size(double.infinity, 60);
                        },
                      ),
                      padding: MaterialStateProperty.all(EdgeInsets.all(0)),
                      backgroundColor: MaterialStateProperty.resolveWith(
                        (states) {
                          // If the button is pressed, return green, otherwise blue
                          if (states.contains(MaterialState.pressed)) {
                            return Color(0xff795368);
                          }
                          return Color(0xff3E2A35);
                        },
                      ),
                    ),
                    onPressed: () async {
                      adScreenLoadingDialog(context);
                      if (_isAdLoaded) {
                        await _interstitialAd.show();
                        Navigator.pop(context);
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => BusTest2(),
                          ),
                        );
                      }
                    },
                    child: Container(
                      height: 40,
                      child: Center(
                        child: Text(
                          'Bus Test 2',
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: 15,
                          ),
                          textAlign: TextAlign.center,
                        ),
                      ),
                    ),
                  ),
                  SizedBox(
                    height: 10,
                  ),
                  ElevatedButton(
                    style: ButtonStyle(
                      shape: MaterialStateProperty.all(
                        RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(10),
                        ),
                      ),
                      maximumSize: MaterialStateProperty.resolveWith(
                        (states) {
                          if (states.contains(MaterialState.disabled)) {
                            return Size(double.infinity, 60);
                          }
                          return Size(double.infinity, 60);
                        },
                      ),
                      padding: MaterialStateProperty.all(EdgeInsets.all(0)),
                      backgroundColor: MaterialStateProperty.resolveWith(
                        (states) {
                          // If the button is pressed, return green, otherwise blue
                          if (states.contains(MaterialState.pressed)) {
                            return Color(0xff795368);
                          }
                          return Color(0xff3E2A35);
                        },
                      ),
                    ),
                    onPressed: () async {
                      adScreenLoadingDialog(context);
                      if (_isAdLoaded) {
                        await _interstitialAd.show();
                        Navigator.pop(context);
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => BusTest3(),
                          ),
                        );
                      }
                    },
                    child: Container(
                      height: 40,
                      child: Center(
                        child: Text(
                          'Bus Test 3',
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: 15,
                          ),
                          textAlign: TextAlign.center,
                        ),
                      ),
                    ),
                  ),
                  SizedBox(
                    height: 10,
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

adScreenLoadingDialog(context) {
  return showDialog(
      barrierDismissible: false,
      context: context,
      builder: (context) {
        return AlertDialog(
          elevation: 0,
          backgroundColor: Colors.transparent,
          content: Container(
            height: 100,
            width: 100,
            child: SpinKitCircle(
              color: Color(0xffd88820),
              size: 100,
            ),
          ),
        );
      });
}

so

1

There are 1 best solutions below

2
On

Since you just want to make onPressed display adScreenLoadingDialog and wait till _isAdLoaded become true, you can use this Function to add delays until _isAdLoaded is true.

 Future<void> checkIfAdLoaded() async {
    if (_isAdLoaded) {
      return;
    } else {
      await Future.delayed(const Duration(seconds: 1));
      checkIfAdLoaded();
    }
  }

Add it to onPressed like this,

                    onPressed: () async {
                      adScreenLoadingDialog(context);
                      checkIfAdLoaded();
                      if (_isAdLoaded) {
                        await _interstitialAd.show();
                        Navigator.pop(context);
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => BusTest2(),
                          ),
                        );
                      }
                    },

You can also use use a Completer but that would need more code changes.

Also, wrap _isAdLoaded = true; in setState((){}),

void onAdLoaded(InterstitialAd ad) {
  setState((){
    _interstitialAd = ad;
    _isAdLoaded = true;
  });
  _interstitialAd.fullScreenContentCallback = FullScreenContentCallback(
    onAdDismissedFullScreenContent: (ad) {
      _initAd();
      //_interstitialAd.dispose();
      },
      onAdFailedToShowFullScreenContent: (ad, error) {
      _initAd();
      //_interstitialAd.dispose();
    },
  );
}