How to warn user about no internet connection before firebase initialization in flutter

Issue

I am using firebase for push notification.To do that, I was following a tutorial where they stated that, Firebase.initializeApp(); must be declared before runApp(MyApp());.
The push notification scenario is working just fine, but the problem is, if there is no internet connection, the app stuck in splash screen.
Now I want to know, is there any standard procedure to warn the user about no internet connection before runApp(MyApp()); ? or the rule ‘ Firebase.initializeApp(); must be declared before runApp(MyApp()); ‘ I know is wrong?
Or I am missing some standard procedure ?

My code scenario –

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  try {
    await Firebase.initializeApp();
  } on SocketException {
    print('socket exception'); 

  }
  FirebaseMessaging.onBackgroundMessage(_firebaseMessegingBackgroundHandler);

  await FirebaseMessaging.instance.subscribeToTopic('all');
  // await FirebaseMessaging.instance.subscribeToTopic('fluttertest');

  // runApp(MyApp());

  await SentryFlutter.init(
    (options) {
      options.dsn =
          '',
      options.tracesSampleRate = 1.0;
    },
    appRunner: () => runApp(MyApp()),
  );
  SystemChrome.setSystemUIOverlayStyle(
    SystemUiOverlayStyle.dark.copyWith(
      systemNavigationBarColor: GlobalColor.primaryTitle,
      statusBarColor: GlobalColor.statusBarColor,
    ),
  );

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

  await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
    alert: true,
    badge: true,
    sound: true,
  );
}

Please be noted, I know how to check connectivity state, my goal is how to implement this with firebase!

Solution

My guess is that the call to await FirebaseMessaging.instance.subscribeToTopic('all') doesn’t succeed until there is an internet connection.

If you want the subscription to complete once a connection is available, but continue to use the app normally until then: remove the await from that call.

If you want the subscription to not even be tried later when there is no connection to the internet now, detect whether there’s an internet connection (in the way you already say you know) and skip the subscribeToTopic call when there is no internet connection.

Answered By – Frank van Puffelen

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published