我正在使用连接性:^ 0.4.6插件,用于检查flutter应用程序中的连接性。我的代码如下:
Future<void> main() async {
StreamSubscription connectivitySubscription;
ConnectivityResult _previousResult;
connectivitySubscription = Connectivity()
.onConnectivityChanged
.listen((ConnectivityResult connectivityResult) {
if (connectivityResult == ConnectivityResult.none) {
nav.currentState.push(CupertinoPageRoute(
builder: (BuildContext _) => NoConnectivityView()));
} else if (_previousResult == ConnectivityResult.none) {
nav.currentState.push(CupertinoPageRoute(
builder: (BuildContext _) => LoginScreen()));
}
_previousResult = connectivityResult;
});
Future.delayed(Duration(seconds: 3));
runApp(MyApp());
}
在应用启动后连接发生更改时,它可以完美地工作。但是,如果在初始状态下没有任何连接,它将无法正常工作。 connectivityResult
这次为空。
我该如何解决?
答案 0 :(得分:0)
由于您正在侦听设备的连接性,因此此回调将触发多次,因此在某一时刻它可能为null,但在另一时刻它不会为null。
我为您添加了一个空的情况:
Future<void> main() async {
StreamSubscription connectivitySubscription;
ConnectivityResult _previousResult;
connectivitySubscription = Connectivity()
.onConnectivityChanged
.listen((ConnectivityResult connectivityResult) {
if (connectivityResult == null || connectivityResult == ConnectivityResult.none) {
nav.currentState.push(CupertinoPageRoute(
builder: (BuildContext _) => NoConnectivityView()));
} else if (_previousResult == ConnectivityResult.none) {
nav.currentState.push(CupertinoPageRoute(
builder: (BuildContext _) => LoginScreen()));
}
_previousResult = connectivityResult;
});
Future.delayed(Duration(seconds: 3));
runApp(MyApp());
}