Anonymous
Anonymous

Reputation: 317

Showing dialog when user loses internet connection in flutter

Is it possible to listen to the entire application in flutter and showing the dialog in case of loss of connection?

Upvotes: 0

Views: 1564

Answers (1)

Ariel
Ariel

Reputation: 2752

Yes it is possible. And you will need one package for this to work.

  1. Internet Connection Checker

You can listen to the stream onConnectivityChanged from InternetConnectionChecker.

@override
void initState(){
super.initState();
var isDeviceConnected = false;

var subscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) async {
  if(result != ConnectivityResult.none) {
    isDeviceConnected = await InternetConnectionChecker().hasConnection;

    if(!isDeviceConnected){
        showDialog(
           context,
           // Your Dialog Here
    );
    }

  }
});
}

Some things to consider here.

  1. showDialog() needs a context, so put all of this code on the main widget with MaterialApp.
  2. You need to dismiss the dialog by yourself. You wont know if there is a dialog up or not at all. So, do it in your own discretion. Try not to pop() the MaterialApp itself.

Upvotes: 1

Related Questions