Skip to content

Instantly share code, notes, and snippets.

@sbosell
Created September 22, 2020 11:50
Show Gist options
  • Save sbosell/d47b5c4a6fb2be90a686e0fcc95b9bc0 to your computer and use it in GitHub Desktop.
Save sbosell/d47b5c4a6fb2be90a686e0fcc95b9bc0 to your computer and use it in GitHub Desktop.
Riverpod Network Detection Example
import 'dart:async';
import 'package:connectivity/connectivity.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
enum NetworkStatus { NotDetermined, On, Off }
class NetworkDetectorNotifier extends StateNotifier<NetworkStatus> {
StreamController<ConnectivityResult> controller =
StreamController<ConnectivityResult>();
NetworkStatus lastResult;
NetworkDetectorNotifier() : super(NetworkStatus.NotDetermined) {
lastResult = NetworkStatus.NotDetermined;
Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
// Use Connectivity() here to gather more info if you need t
NetworkStatus newState;
switch (result) {
case ConnectivityResult.mobile:
case ConnectivityResult.wifi:
newState = NetworkStatus.On;
break;
case ConnectivityResult.none:
newState = NetworkStatus.Off;
// TODO: Handle this case.
break;
}
if (newState != state) {
state = newState;
}
});
}
}
final networkAwareProvider = StateNotifierProvider((ref) {
return NetworkDetectorNotifier();
});
class YourScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Consumer(builder: (context, watch, child) {
var network = watch(networkAwareProvider).state;
if (network == NetworkStatus.Off) {
return Center(child: Text("No network"));
}
return Container(child: Text("Normal stuff"));
});
}
}
@pishguy
Copy link

pishguy commented Nov 29, 2021

@AErmek Thanks so much :) , let me try

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment