Home > Mobile >  Null check operator used on a null value. Error thrown null in platform_views.dart
Null check operator used on a null value. Error thrown null in platform_views.dart

Time:04-10

App is crashing a lot while starting it. In my app, I am using Crashlytics to log the errors.
As I can see in Crashlytics, users are getting below errors and app is unresponsive.

Non-fatal Exception: io.flutter.plugins.firebase.crashlytics.FlutterError: Null check operator used on a null value. Error thrown null.
       at State.setState(framework.dart:1141)
       at _PlatformViewLinkState._onPlatformViewCreated(platform_view.dart:898)
       at AndroidViewController.create(platform_views.dart:775)

Seems like this error is getting occured on app load only. enter image description here

main.dart file

import 'dart:async';

import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_crashlytics/firebase_crashlytics.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:my_app/Home_screen.dart';
import 'package:my_app/utils/helpers/admob_helper.dart';
import 'package:my_app/utils/helpers/interstitial_ad_helper.dart';
import 'package:my_app/utils/helpers/notification_helper.dart';
import 'package:my_app/widgets/shared/rate_my_app.dart';
import 'config/theme_config.dart';
import 'utils/helpers/dark_theme_listener.dart';

const AndroidNotificationChannel channel = AndroidNotificationChannel(
  'high_importance_channel', // id
  'High Importance Notifications', // title
  description:
      'This channel is used for important notifications.', // description
  importance: Importance.high,
  playSound: true,
);

final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
    FlutterLocalNotificationsPlugin();

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp();

  print('A bg message just showed up :  ${message.messageId}');
}

Future<void> main() async {
  runZonedGuarded(() async {
    WidgetsFlutterBinding.ensureInitialized();
    await Firebase.initializeApp();
    FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
    FirebaseMessaging.instance.subscribeToTopic(
      "ScratchNotiftest"); //Replace with JHNotifTest for Live

    await flutterLocalNotificationsPlugin
        .resolvePlatformSpecificImplementation<
            AndroidFlutterLocalNotificationsPlugin>()
        ?.createNotificationChannel(channel);

    await FirebaseMessaging.instance
        .setForegroundNotificationPresentationOptions(
      alert: true,
      badge: true,
      sound: true,
    );
    AdmobHelper.initialize();
    await new ThemeHelper().initialize();
    InterstitialAdHelper.calculateNextAdDisplay();
    FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterError;
    runApp(MyApp());
    SystemChrome.setSystemUIOverlayStyle(
        SystemUiOverlayStyle(statusBarColor: Color(0xff004175)));
  }, (Object error, StackTrace stack) {
    FirebaseCrashlytics.instance.recordError(error, stack);
  });
}

class MyApp extends StatefulWidget {
  MyApp({
    Key? key,
  }) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      RemoteNotification notification = message.notification!;
      flutterLocalNotificationsPlugin.show(
          notification.hashCode,
          notification.title,
          notification.body,
          NotificationDetails(
            android: NotificationHelper.getAndroidNotificationDetails(channel),
          ));
    });

    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
      print('A new onMessageOpenedApp event was published!');
      RemoteNotification notification = message.notification!;
      showDialog(
          context: context,
          builder: (_) {
            return AlertDialog(
              title: Text(notification.title ?? 'my_app'),
              content: SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [Text(notification.body ?? 'New Notification')],
                ),
              ),
            );
          });
    });
  }

  @override
  Widget build(BuildContext context) {
    // Only call clearSavedSettings() during testing to reset internal values.
    // Upgrader().clearSavedSettings(); // REMOVE this for release builds

    return ValueListenableBuilder<bool>(
      valueListenable: isDark,
      builder: (ctx, theme, child) => MaterialApp(
        themeMode: theme ? ThemeMode.dark : ThemeMode.light,
        debugShowCheckedModeBanner: false,
        title: 'my_app',
        theme: lightThemeData(context),
        darkTheme: darkThemeData(context),
        home: RateAppInitWidget(
          builder: (rateMyApp) => HomeScreen(
            rateMyApp: rateMyApp,
          ),
        ),
      ),
    );
  }
}

My Qestions:

  1. Is there anything wrong in my main.dart file?
  2. If flutter is null safe, then why it is breaking? (Again if bang operator is not that safe to use, why it is getting used everywhere).

I really appricate any help. Thanks in advance.

CodePudding user response:

Try Removing the ! from this line & Pass Some Default Value for RemoteNotification Type:

RemoteNotification notification = message.notification!;

  • Related