Home > Software design >  BannerAd variable has not initialized error
BannerAd variable has not initialized error

Time:04-01

i get an error that my BannerAd variable is not initialized and my app crash, so i move my _banner in top of code and still not work, i move it inside the state class and still not initialized what should need to do to be initialized ?

  class _MyHomePageState extends State<MyHomePage> {
  late BannerAd _banner;
  @override
  void didChangeDependencies(){
    super.didChangeDependencies();

    final adState = context.read(adStateProvider);
    adState.initialization.then((value)
    {
      setState(() {
        _banner = BannerAd(size: AdSize.banner, adUnitId: adState.bannerAdUniteId, listener: adState.adListener, request: AdRequest())..load();
      });
    });
  }
  @override
  Widget build(BuildContext context) {

    return Scaffold(

      body: Center(
        child: Column(

          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new Text('pub'),
          if(_banner == null)Text('null hhhhhhhhhhhhhhhhhhhhhhhhhhhhh')
      else Expanded(child: AdWidget(ad: _banner),),

CodePudding user response:

That's because your widget builds before _banner is initialized, even if you initialized it in initState, will still not work, because you initialize it after a future completes, and that future completes after the build method got executed. so the solution here is to remove the late keyword before BannerAd and also make it nullable. like this:

// this doesn't give you any initialization errors 
// because _banner will have a default value of null
BannerAd? _banner; 

now you will have a different problem, because AdWidget takes a non-null object, you need to assert that _banner is not null with null assertion operator !, like this:

AdWidget(ad: _banner!)

this way it's like you're telling the compiler that "I'm sure that _banner is not null", because you only build this widget if _banner is not null because of the if else clause

Note that when using !, you have to be completely sure that the object will actually be not null then, if it's null, it will throw a null assertion exception.

you can read and practice on null safety with this dart codelab

  • Related