Ahmad Mohy
Ahmad Mohy

Reputation: 401

Flutter : is it possible to implement a snackbar one time in main.dart for example for all screen when the connectivity status changed

enum ConnectivityStatus{
  Wifi,
  Cellular,
  Offline
}
import 'dart:async';

import 'package:Zabatnee/activities_app/enum/connectivity_status.dart';
import 'package:connectivity/connectivity.dart';

class ConnectivityService{

StreamController<ConnectivityStatus> connectionStatusController = StreamController<ConnectivityStatus>();

ConnectivityService(){
  Connectivity().onConnectivityChanged.listen((ConnectivityResult result) { 
    var connectionStatus = _getStatusFromResult(result);
    connectionStatusController.add(connectionStatus);
  });
}
  ConnectivityStatus _getStatusFromResult(ConnectivityResult result) {
    switch (result) {
      case ConnectivityResult.mobile:
        return ConnectivityStatus.Cellular;
      case ConnectivityResult.wifi:
        return ConnectivityStatus.Wifi;
      case ConnectivityResult.none:
        return ConnectivityStatus.Offline;
      default:
        return ConnectivityStatus.Offline;
    }
  }
}

Upvotes: 0

Views: 161

Answers (1)

Ravi Singh Lodhi
Ravi Singh Lodhi

Reputation: 2793

You can check the connectivity status once & that will be implemented for all of your app.

You just have to create a wrapper class & subscribe to the Connectivity stream & apply the logic in this wrapper class.

Your whole widget will be wrapped by this widget.

MaterialApp(
  ..
  home: ConnectivityWrapper(
    childWidget: YourWidget(), // replace this with your own home widget
  ),
);

The wrapper widget will look something like this:

class ConnectivityWrapper extends StatefulWidget {
  
  ConnectivityWrapper(this.childWidget);
  
  final Widget childWidget;

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

class _ConnectivityWrapperState extends State<ConnectivityWrapper> {

  StreamSubscription<ConnectivityStatus> subscription;

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

    subscription = connectionStatusController.stream.listen((status) 
      {
        if(status == ConnectivityStatus.Offline) {
          // Your logic here (Toast message or something else)
        }
      }, 
      onDone() {
        // Your logic here
      }, 
      onError: () {
        // Your logic here
      });
  }

  @override
  Widget build(BuildContext context) {
    return widget.childWidget;
  }

  @override
  void dispose() {
    // unsubscribe to the stream
    subscription.cancel();
    super.dispose();
  }
}

Upvotes: 2

Related Questions