How to disable admob for flutter web

Viewed 44

i have a flutter app. It's working on web browsers and mobile devices. I have added ad mob for showing banner ads. But i cant run the project because of google_mobile_ads doesn't support web. I'm starting google mobile ads if the current platform is a mobile device. I have an export.dart like this:

export 'ad_mobile.dart' if (dart.library.html) 'ad_web.dart';

ad_mobile.dart:

import 'package:google_mobile_ads/google_mobile_ads.dart';

Future<dynamic> initAds() async {
  await _initGoogleMobileAds();
 }

Future<InitializationStatus> _initGoogleMobileAds() {
 RequestConfiguration configuration = RequestConfiguration(
 testDeviceIds: <String>[
  testDeviceId,
],);

 MobileAds.instance.updateRequestConfiguration(configuration);
 return MobileAds.instance.initialize();

}

and ad_web.dart is:

import 'dart:developer';

 Future initAds() async {
 log('ADS DOES\'NT SUPPORTED FOR WEB PLATFORMS');
 }

When i run the app on Chrome, app starts but stuck at white screen. And i get this error on debug console:

Error: MissingPluginException(No implementation found for method _init on channel plugins.flutter.io/google_mobile_ads)

1 Answers

There are ways to make it work with less code but if this way it is easier to maintain and extend your code.
You need to change how you import your files based on the platform.

First create an abstract class around Admob:

abstract class AdmobWrapper{
  factory AdmobWrapper() => createAdmobWrapper();
  Future<dynamic> init();
}

Second create the platform files:
Generic platform:

AdmobWrapper createAdmobWrapper() =>  throw UnimplementedError('createAdmobWrapper()'); 

IO (Mobile) platform:

    AdmobWrapper createAdmobWrapper() => AdmobWrapperIO();
    class AdmobWrapperIO() implements AdmobWrapper(){
        factory AdmobWrapperIO() => _instance;
        AdmobWrapperIO._internal();
        static final AdmobWrapperIO_instance = AdmobWrapperIO._internal();
       
        Future<dynamic> init(){
         .... do init here
         }
    }

Web platform:

    AdmobWrapper createAdmobWrapper() => AdmobWrapperWeb();
    class AdmobWrapperWeb implements AdmobWrapper {
        factory AdmobWrapperWeb() => _instance;
        AdmobWrapperWeb._internal();
        static final AdmobWrapperWeb _instance = AdmobWrapperWeb._internal();
       
        Future<dynamic> init(){
         // nothing here
         }
       }

Third add platform imports to your abstract class:

import 'package:genericPlatform.dart' //   <-- this 2 slash is important
  if(dart.library.io) 'package:yourRealAdmobPackage'
  if(dart.library.html) 'package:yourWebPackage'
 abstract class AdmobWrapper(){ /// rest of the code we made in first step

You can call AdmobWrapper().init() now.

Related