此实现代码是一个简单的 Riverpod
提供程序,我们可以检测互联网连接:
enum NetworkStatus { NotDetermined, On, Off }
final networkAwareProvider = StateNotifierProvider((ref)=>NetworkDetectorNotifier());
class NetworkDetectorNotifier extends StateNotifier<NetworkStatus> {
StreamController<ConnectivityResult> controller =
StreamController<ConnectivityResult>();
NetworkStatus lastResult = NetworkStatus.NotDetermined;
NetworkDetectorNotifier() : super(NetworkStatus.NotDetermined) {
Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
NetworkStatus newState;
switch (result) {
case ConnectivityResult.mobile:
case ConnectivityResult.wifi:
newState = NetworkStatus.On;
break;
case ConnectivityResult.none:
newState = NetworkStatus.Off;
break;
}
if (newState != state) {
state = newState;
}
});
}
}
在这里我如何处理 controller
并且基本上当我们想在 ConsumerWidget
中使用它时,我们可以拥有:
class Screen 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"));
});
}
}
with Riverpod
kook 如何在其中使用 whatch
方法?例如:
class Profile extends HookWidget {
@override
Widget build(BuildContext context) {
final _network = useProvider(networkAwareProvider);
final connected = _network.watch(networkAwareProvider).state;
if(connected){
print ('connected');
}else{
print ('not connected');
}
}
}
我收到此错误:
Class 'NetworkStatus' has no instance method 'watch'.
Receiver: Instance of 'NetworkStatus'
Tried calling: watch(Instance of 'StateNotifierProvider<NetworkDetectorNotifier, dynamic>')
提前致谢
答案 0 :(得分:1)
useProvider
的工作方式与 ref.watch
相同,因此您只需:
final status = useProvider(networkAwareProvider);
if (status == ...) {
...
}