flutter 使onPressed等待广告加载

t5fffqht  于 2023-01-18  发布在  Flutter
关注(0)|答案(1)|浏览(122)

让我告诉你我想要的过程和正在发生的事情

**过程:**按ElevatedButton,然后显示adScreenLoadingDialog,直到_isAdLoaded=true,然后显示广告并转到下一屏幕。
正在发生的事情:有两个条件:
首先,如果用户打开屏幕并滚动或等待大约5秒,然后点击ElevatedButton,该过程工作正常,一切正常。
其次,如果用户打开屏幕并立即点击ElevatedButton,则adScreenLoadingDialog出现,但过程停止,因为_isAdLoaded还不是真的,过程出错。
**我需要您的帮助:**如何使onPressed显示adScreenLoadingDialog,并等待_isAdLoaded变为真,以便广告可以显示并转到下一个屏幕。

我尝试使用while循环,但它不工作。
如果有人能帮忙我真的很感激。
谢谢
这是我的屏幕代码

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,
            ),
          ),
        );
      });
}

所以

gfttwv5a

gfttwv5a1#

由于您只想让onPressed显示adScreenLoadingDialog,并等待_isAdLoaded变为true,因此可以使用此Function添加延迟,直到_isAdLoaded变为true

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

像这样将其添加到onPressed中,

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

您也可以使用Completer,但这需要更多的代码更改。
另外,将_isAdLoaded = true; Package 为setState((){})

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

相关问题