How to pop dialog in Flutter if internet connection goes off suddenly?

Issue

What I’m trying to implement is something like this,

showDialog();
await firebaseFunction();
await apiFunction();
hideDialog();

This will work properly if the internet connection is on. But what should I do if the internet connection is turned off suddenly? As if that happens, the app will get stuck on the future functions and the screen of the app will be stuck on the dialog.
I want to pop the dialog whenever the internet connection goes off.
Are there an dependencies that’ll help me do that?

Solution

try connectivity_plus, listen to the cellular vs WiFi connection, if none, pop the dialog:

import 'package:connectivity_plus/connectivity_plus.dart';

@override
initState() {
  super.initState();

  subscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
    if (result == ConnectivityResult.none) {
    hideDailog();
    showToast("No internet connection");
  }
  });
}

// Be sure to cancel subscription after you are done
@override
dispose() {
  super.dispose();

  subscription.cancel();
}

Answered By – Jim

Answer Checked By – Jay B. (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *