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.
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();
}
}
create: (context) => NetworkProvider(),
child: Consumer<NetworkProvider>(
builder: (context, value, _) =>
),
return StreamProvider<ConnectivityResult>.value(
DON'T WASTE FOODS
Comments