'I want to Implement flutter_bloc and connectivity_plus to check for network connections. how to do it?
I have tried out tons of blogs and stuff to do this but none of them work or are outdated or throw unknown errors. I am instructed to create network connection checker using bloc. however, I have little to no knowledge of bloc. Please share any git repo or code that explains how to do this. #Flutter
Solution 1:[1]
Register a streamSubscription in bloc and listen connections changed.
When connections changed, run event to update state
class NetworkChangeBloc extends Bloc<NetworkChangeEvent, NetworkChangeState> {
final ConnectivityService _service;
late StreamSubscription<bool> _subscription;
NetworkChangeBloc()
: _service = ConnectivityService(),
super(NetworkChangeInitial()) {
on<NetworkChangeEvent>(_mapEventNetworkChange);
_subscription = _service.initStream().listen((isNetworkConnected) {
add(NetworkChangeEvent(isNetworkConnected));
});
}
@override
Future<void> close() async {
await _service.dispose();
await _subscription.cancel();
return super.close();
}
void _mapEventNetworkChange(
NetworkChangeEvent event,
Emitter<NetworkChangeState> emit,
) async {
bool isNetworkConnected = event.isNetworkConnected;
emit(NetworkChangeState(isConnected: isNetworkConnected));
}
}
I don't use connectivity_plus package here but you can apply this solution
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Saitoh Akira |
