Created
September 22, 2020 11:50
-
-
Save sbosell/d47b5c4a6fb2be90a686e0fcc95b9bc0 to your computer and use it in GitHub Desktop.
Riverpod Network Detection Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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")); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@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:
and provider should be: