Siddharth Porwal
Siddharth Porwal

Reputation: 41

Not able to display native ads in listView.builder in flutter?

 Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  final initFuture = MobileAds.instance.initialize();
  final adState = Adv(initFuture);

  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  await flutterLocalNotificationsPlugin
      .resolvePlatformSpecificImplementation<
          AndroidFlutterLocalNotificationsPlugin>()
      ?.createNotificationChannel(channel);
  initScreen = await Authenticate().readStorage('initScreen');
  print(initScreen);
  await Authenticate().writeStorage('initScreen', "true");

  runApp(MyApp(
    appRouter: AppRouter(),
    connectivity: Connectivity(),
    drawerBloc: DrawerBloc(DrawerState(NavItem.homepage)),
  ));
}

This is my code of main.dart

    import 'dart:io';

import 'package:google_mobile_ads/google_mobile_ads.dart';

class Adv {
  Future<InitializationStatus> initialization;

  Adv(this.initialization);

  static String get categoriesNativeAdUnitId {
    if (Platform.isAndroid) {
      return 'ca-app-pub-3940256099942544/6300978111';
    } else if (Platform.isIOS) {
      return 'ca-app-pub-3940256099942544/2934735716';
    }
    throw new UnsupportedError("Unsupported platform");
  }

  static String get homeNativeAdUnitId {
    if (Platform.isAndroid) {
      return 'ca-app-pub-3940256099942544/2247696110';
    } else if (Platform.isIOS) {
      return 'ca-app-pub-3940256099942544/3986624511';
    }
    throw new UnsupportedError("Unsupported platform");
  }

  static String get newsPageNativeAdUnitId {
    if (Platform.isAndroid) {
      return 'ca-app-pub-3940256099942544/2247696110';
    } else if (Platform.isIOS) {
      return 'ca-app-pub-3940256099942544/3986624511';
    }
    throw new UnsupportedError("Unsupported platform");
  }

  static String get blogsBannerAdUnitId {
    if (Platform.isAndroid) {
      return 'ca-app-pub-3940256099942544/2247696110';
    } else if (Platform.isIOS) {
      return 'ca-app-pub-3940256099942544/3986624511';
    }
    throw new UnsupportedError("Unsupported platform");
  }

  static String get publisherListPageNativeAdUnitId {
    if (Platform.isAndroid) {
      return 'ca-app-pub-3940256099942544/2247696110';
    } else if (Platform.isIOS) {
      return 'ca-app-pub-3940256099942544/3986624511';
    }
    throw new UnsupportedError("Unsupported platform");
  }

  
}

This is the code of my adhelper.dart

     class ShowHomeNews extends StatefulWidget {
  final List<NewsModel> newsModel;
  final int index;
  const ShowHomeNews({
    Key key,
    @required this.newsModel,
    this.index,
  }) : super(key: key);

  @override
  _ShowHomeNewsState createState() => _ShowHomeNewsState();
}

class _ShowHomeNewsState extends State<ShowHomeNews> {
  int adCountTrack = 0;

  bool _isAdLoaded = false;
  List<NativeAd> adList = [];
  @override
  void initState() {
    super.initState();
    adLoader();
  }

  adLoader() {
    setState(() {
      int len = ((widget.newsModel.length) / 4).floor();
      for (int i = 0; i < len; i++) {
        print(i.toString());
        print("i ki vaues:" + i.toString());
        adList.add(
          NativeAd(
              adUnitId: Adv.homeNativeAdUnitId,
              factoryId: 'listTile',
              listener: AdListener(
                onAdLoaded: (_) {
                  setState(() {
                    _isAdLoaded = true;
                  });
                },
                onAdFailedToLoad: (ad, error) {
                  // Releases an ad resource when it fails to load

                  print(
                      'Ad load failed (code=${error.code} message=${error.message})');
                },
              ),
              request: AdRequest())
            ..load(),
        );
      }
    });

    print("AdList size: " + adList.length.toString());
  }

  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
      onRefresh: () async => BlocProvider.of<TabbarblocBloc>(context).add(
        PageTapped(index: widget.index),
      ),
      child: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Padding(
              padding: const EdgeInsets.fromLTRB(10, 5, 10, 0),
              child: Text(
                "Trending",
                style: TextStyle(fontWeight: FontWeight.w600),
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Container(
                height: 200,
                child: ListView.builder(
                  physics: ClampingScrollPhysics(),
                  primary: false,
                  itemCount: widget.newsModel.length,
                  shrinkWrap: true,
                  scrollDirection: Axis.horizontal,
                  itemBuilder: (context, index) {
                    return TrendingTile(
                      newsModel: widget.newsModel[index],
                    );
                  },
                ),
              ),
            ),
            Container(
              child: ListView.builder(
                  primary: false,
                  itemCount: widget.newsModel.length,
                  shrinkWrap: true,
                  itemBuilder: (context, index) {
                    print(widget.newsModel.length);
                    if (index % 4 == 0 && adCountTrack < adList.length) {
                      return Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Container(
                          height: 120.0,
                          width: 120.0,
                          decoration: BoxDecoration(
                            color: whiteTextColor,
                            borderRadius: BorderRadius.circular(12),
                            boxShadow: [
                              BoxShadow(
                                  spreadRadius: 1,
                                  blurRadius: 5.0, // soften the shadow
                                  offset: Offset(
                                    1.0, // Move to right 10  horizontally
                                    2.0, // Move to bottom 10 Vertically
                                  ),
                                  color: Colors.grey[350])
                            ],
                          ),
                          child: AdWidget(
                            ad: adList[adCountTrack++],
                          ),
                        ),
                      );
                    } else if (widget.newsModel[index].views <=
                        compareTotalViewForGrid) {
                      return Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: NewsTileSmall(
                          newsModel: widget.newsModel[index],
                        ),
                      );
                    } else {
                      return Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: NewsTileBig(
                          newsModel: widget.newsModel[index],
                        ),
                      );
                    }
                  }),
            ),
          ],
        ),
      ),
    );
  }
}

This is the code of my file where I am trying to show the native ads in a list, but no native adv. is displayed.

Below i have added debug console log

D/DynamitePackage(19276): Instantiating com.google.android.gms.ads.ChimeraAdLoaderBuilderCreatorImpl I/Ads
(19276): Use RequestConfiguration.Builder().setTestDeviceIds(Arrays.asList("FA6C491A794C3455DA1F640FE2E82C3A")) to get test ads on this device. I/DynamiteModule(19276): Considering local module com.google.android.gms.ads.dynamite:0 and remote module com.google.android.gms.ads.dynamite:210890500 I/DynamiteModule(19276): Selected remote version of com.google.android.gms.ads.dynamite, version >= 210890500 W/Parcel (19276): **** enforceInterface() expected 'com.google.android.gms.ads.clearcut.IClearcut' but read 'com.google.android.gms.gass.internal.clearcut.IClearcut' I/DynamiteModule(19276): Considering local module com.google.android.gms.ads.dynamite:0 and remote module com.google.android.gms.ads.dynamite:210890500 I/DynamiteModule(19276): Selected remote version of com.google.android.gms.ads.dynamite, version >= 210890500 I/DynamiteModule(19276): Considering local module com.google.android.gms.ads.dynamite:0 and remote module com.google.android.gms.ads.dynamite:210890500 I/DynamiteModule(19276): Selected remote version of com.google.android.gms.ads.dynamite, version >= 210890500 W/Parcel (19276): **** enforceInterface() expected 'com.google.android.gms.ads.clearcut.IClearcut' but read 'com.google.android.gms.gass.internal.clearcut.IClearcut' I/AudioManager(19276): In isSpeakerphoneOn(), calling application: com.indiary.indiary D/DynamitePackage(19276): Instantiating com.google.android.gms.ads.ChimeraAdLoaderBuilderCreatorImpl I/Ads
(19276): Use RequestConfiguration.Builder().setTestDeviceIds(Arrays.asList("FA6C491A794C3455DA1F640FE2E82C3A")) to get test ads on this device. I/AudioManager(19276): In isSpeakerphoneOn(), calling application: com.indiary.indiary I/flutter (19276): 26 D/DynamitePackage(19276): Instantiating com.google.android.gms.ads.ChimeraAdLoaderBuilderCreatorImpl I/Ads
(19276): Use RequestConfiguration.Builder().setTestDeviceIds(Arrays.asList("FA6C491A794C3455DA1F640FE2E82C3A")) to get test ads on this device. I/AudioManager(19276): In isSpeakerphoneOn(), calling application: com.indiary.indiary D/DynamitePackage(19276): Instantiating com.google.android.gms.ads.ChimeraAdLoaderBuilderCreatorImpl /Ads
(19276): Use RequestConfiguration.Builder().setTestDeviceIds(Arrays.asList("FA6C491A794C3455DA1F640FE2E82C3A")) to get test ads on this device. I/AudioManager(19276): In isSpeakerphoneOn(), calling application: com.indiary.indiary 2 I/flutter (19276): 26 D/DynamitePackage(19276): Instantiating com.google.android.gms.ads.ChimeraAdLoaderBuilderCreatorImpl I/Ads
(19276): Use RequestConfiguration.Builder().setTestDeviceIds(Arrays.asList("FA6C491A794C3455DA1F640FE2E82C3A")) to get test ads on this device. I/flutter (19276): 26 I/AudioManager(19276): In isSpeakerphoneOn(), calling application: com.indiary.indiary D/DynamitePackage(19276): Instantiating com.google.android.gms.ads.ChimeraAdLoaderBuilderCreatorImpl I/Ads
(19276): Use RequestConfiguration.Builder().setTestDeviceIds(Arrays.asList("FA6C491A794C3455DA1F640FE2E82C3A")) to get test ads on this device. I/AudioManager(19276): In isSpeakerphoneOn(), calling application: com.indiary.indiary W/pool-30-thread-(19276): type=1400 audit(0.0:6476): avc: granted { execute } for path="/data/data/com.indiary.indiary/app_pccache/5/CCFA22EBAF6E1880534512380E8EF01170FD9593/pcam.jar" dev="dm-14" ino=5090217 scontext=u:r:untrusted_app:s0:c250,c257,c512,c768 tcontext=u:object_r:app_data_file:s0:c250,c257,c512,c768 tclass=file app=com.indiary.indiary 7 I/flutter (19276): 26 E/flutter (19276): [ERROR:flutter/shell/platform/android/platform_view_android_jni_impl.cc(49)] java.lang.IllegalStateException: PlatformView#getView() returned null, but an Android view reference was expected. E/flutter (19276): at io.flutter.plugin.platform.PlatformViewsController.initializePlatformViewIfNeeded(PlatformViewsController.java:717) E/flutter (19276): at io.flutter.plugin.platform.PlatformViewsController.onDisplayPlatformView(PlatformViewsController.java:746) E/flutter (19276): at io.flutter.embedding.engine.FlutterJNI.onDisplayPlatformView(FlutterJNI.java:1195) E/flutter (19276): at android.os.MessageQueue.nativePollOnce(Native Method) E/flutter (19276): at android.os.MessageQueue.next(MessageQueue.java:335) E/flutter (19276): at android.os.Looper.loop(Looper.java:183) E/flutter (19276): at android.app.ActivityThread.main(ActivityThread.java:8010) E/flutter (19276): at java.lang.reflect.Method.invoke(Native Method) E/flutter (19276): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:631) E/flutter (19276): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:978) E/flutter (19276): F/flutter (19276): [FATAL:flutter/shell/platform/android/platform_view_android_jni_impl.cc(1395)] Check failed: CheckException(env). F/libc (19276): Fatal signal 6 (SIGABRT), code -6 (SI_TKILL) in tid 19276 (indiary.indiary), pid 19276 (indiary.indiary)

I am try to display google native ads using google_mobile_ads sdk and I want show n number of ads in between the list like after every 4 item native ad should be displayed, but i am not able to display them and my application is crashing?

Upvotes: 3

Views: 1279

Answers (1)

Huthaifa Muayyad
Huthaifa Muayyad

Reputation: 12353

Change

List<Object> adList;

To this:

List<NativeAd> adList = [];

Since you are getting a null error, it means you are trying to add NativeAd objects, to your list, but it still hasn't been initialized.

Upvotes: 1

Related Questions