【发布时间】:2020-08-21 04:43:22
【问题描述】:
假设我想在每次调用 Api 时检查互联网连接,如果没有互联网,则调用抛出异常,如 NoInternetException,然后向用户显示状态屏幕,告诉他检查他们的连接。
如何在不为 flutter_bloc 库中的每个块创建新状态的情况下实现这一目标?
【问题讨论】:
标签: flutter dart bloc flutter-bloc
假设我想在每次调用 Api 时检查互联网连接,如果没有互联网,则调用抛出异常,如 NoInternetException,然后向用户显示状态屏幕,告诉他检查他们的连接。
如何在不为 flutter_bloc 库中的每个块创建新状态的情况下实现这一目标?
【问题讨论】:
标签: flutter dart bloc flutter-bloc
您可以在管理您的根页面(如 authentication_page 和 homepage)的区域中执行此操作。
为 noConnectivity 创建一个state。
NoConnectivity extends AuthenticationState{
final String message;
const NoConnectivity({ this.message });
}
现在为 noConnectivity 创建一个event。
NoConnectivityEvent extends AuthenticationEvent{}
最后,在您的AuthenticationBloc 中创建一个 StreamSubscription 以持续监听connecitvityState 的变化,如果状态为connectivity.none,我们将触发NoConnecitivity 状态。
class AuthenticationBloc
extends Bloc<AuthenticationEvent, AuthenticationState> {
StreamSubscription subscription;
@override
AuthenticationState get initialState => initialState();
@override
Stream<AuthenticationState> mapEventToState(
AuthenticationEvent event,
) async* {
// ... all other state map
else if(event is NoConnectivityEvent) {
yield* _mapNoConnectivityEventToState();
}
Stream<AuthenticationState> _mapNoConnectivityEventToState() async * {
subscription?.cancel();
//Edit to handle android internet connectivity.
subscription = Connectivity()
.onConnectivityChanged
.listen((ConnectivityResult result) {
if(Platform.isAndroid) {
try {
final lookupResult = InternetAddress.lookup('google.com');
if (lookupResult.isNotEmpty && lookupResult[0].rawAddress.isNotEmpty) {
print('connected');
}
} on SocketException catch (error) {
return add(NoConnectivityState(message: error.message ));
}
} else if(result == ConnectivityResult.none ) {
return add(NoConnectivityState(message: "Noconnection")) ;
}
print("Connected");
});
}
@override
Future<void> close() {
subscription?.cancel();
return super.close();
}
}
此订阅 Stream 将永远收听 no connection 并将您喜欢的相应页面推送到该州。
必需的包
希望对你有帮助!
【讨论】:
你需要基类bloc,比如说他的名字“BaseBloc”,他应该继承“Bloc”类,并实现“mapToStateEvent”方法来处理“noInternet”异常,然后调用方法让我们说你创建的他的名字“internalMapToStateEvent”,这个方法是覆盖方法,并从 "BaseBloc" 继承了你所有的 bloc 类,你需要相同的页面来绘制一个小部件 "noInternetWidget "
【讨论】: