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"));
});
}
}
@andre-nk
Copy link

Cool! Thanks for the help

@pishguy
Copy link

pishguy commented Jul 19, 2021

@sbosell
@fullstack-dre

how can we use in HookWidget and how can we dispose controller?

@AErmek
Copy link

AErmek commented Nov 29, 2021

@pishguy
From official Riverpod documentation
Depending on the provider used, it may already take care of the clean-up process. For example, StateNotifierProvider will call the dispose method of a StateNotifier.

So, In NetworkDetectorNotifier we can add:

@override
  void dispose() {
    super.dispose();
    subscription.cancel();
  }

and provider should be:

  final networkAwareProvider = StateNotifierProvider.autoDispose<NetworkDetectorNotifier, NetworkStatus>((ref) {
  return NetworkDetectorNotifier();
});

@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