Flutter - Connectivity

Hey guys, 

Have a good day. It's my 100th post. Hope I'll post more good contents in future. 

Today we going to see the flutter connectivity. In mobile platform, internet connectivity is major role. Most of developers check and validate the internet all time. 

In flutter, use connectivity library to achieve it. Use provider for more efficient.

In pubspec.yaml

connectivity: ^2.0.0
provider: ^4.3.2+2

For check the internet and attempt tasks,

Create the class somewhere, write this method.

Future<bool> check() async {
   var connectivityResult = await (Connectivity().checkConnectivity());
    if (connectivityResult == ConnectivityResult.mobile) {
      return true;
    } else if (connectivityResult == ConnectivityResult.wifi) {
      return true;
    }
    return false;
}


ConnectivityService().check().then((value) {
      if (value != null && value) {
        // do task 
      } else {
        // show the error message, internet not connected.      }
    });

For broadcasting.

class NetworkProvider {
  StreamSubscription<ConnectivityResult> _subscription;
  StreamController<ConnectivityResult> _networkStatusController;
  StreamSubscription<ConnectivityResult> get subscription => _subscription;
  StreamController<ConnectivityResult> get networkStatusController =>
      _networkStatusController;
  NetworkProvider() {
  _networkStatusController = StreamController<ConnectivityResult>.broadcast();
  _invokeNetworkCheck();
  }
  void _invokeNetworkCheck() async {
  _networkStatusController.sink.add(await Connectivity().checkConnectivity());
  _subscription = Connectivity().onConnectivityChanged.listen((event) {
  _networkStatusController.sink.add(event);
  });
  }
  void disposeStream() {
  _subscription.cancel();
  _networkStatusController.close();
  }
  }

In main.dart:

child: Provider<NetworkProvider>(
   create: (context) => NetworkProvider(),
      child: Consumer<NetworkProvider>(
        builder: (context, value, _) => 
                    MaterialApp(home: HomePage());
),
));

Homepage.dart:

return StreamProvider<ConnectivityResult>.value(
      value: _networkProvider.networkStatusController.stream,
      child: Consumer<ConnectivityResult>(
        builder: (context, value, _){
  return Container();
},
    ),
 );


Sometimes broadcast is not best option, better use RxDart library to sort out the issues.

DON'T WASTE FOODS

Comments

Popular posts from this blog

Flutter Bloc - Clean Architecture

What's new in android 14?

Dependencies vs Dev Dependencies in Flutter