Problem with AdWidget in Flutter Dart (AdWidget requires Ad.load to be called before...)

Viewed 87

I get the error in the picture from the code that follows.

The app is useing WordPress REST API to get titles and pics from a wp site. Then puts them in Cards. All works as intended until I try to show an ad in bottomNavigationBar...

I think the problem is that I'm trying to put the ad in FutureBuilder. But can't figure it out.

Any thoughts?

AdWidget requires Ad.load to be called before AdWidget is inserted into the tree


// @dart=2.9
// this downgrade is necessary because of the damn null safety

import...

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  final initFuture = MobileAds.instance.initialize();
  final adState = AdState(initFuture);

  runApp(
    Provider.value(value: adState, builder: (context, child) => MyApp()),
  );
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(primarySwatch: Colors.yellow),
      home: MyHomePage(),
    );
  }
}

// some code...

class _MyHomePageState extends State<MyHomePage> {
  BannerAd banner;
  bool _bannerIsLoaded = false;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final adState = Provider.of<AdState>(context);
    adState.initialization.then((status) {
      setState(() {
        banner = BannerAd(
            size: AdSize.banner,
            adUnitId: adState.bannerAdUnitId,
            listener: BannerAdListener(onAdLoaded: (Ad ad) {
              print('$BannerAd loaded.');
              setState(() {
                _bannerIsLoaded = true;
              });
            }),
            request: AdRequest());
        banner.load();
      });
    });
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(

// some code...

            ),
          ])),
      body: Column(
          children: [
            Expanded(
                child: FutureBuilder(
                    future: fetchWpPosts(),
                    builder: (context, snapshot) {
                      if (snapshot.hasData && snapshot.data != null) {
                        return ListView.builder(

                          // some code...

                                        ])));
                          },
                        );
                      }

                      return Container(
                          color: Colors.black,
                          child: Center(
                            child: CircularProgressIndicator(strokeWidth: 5.0),
                          ));
                    }))
          ]),
      bottomNavigationBar: _bannerIsLoaded
          ? SizedBox(height: 50, child: AdWidget(ad: banner))
          : SizedBox(height: 50),
    );
  }
}


0 Answers
Related