0

我正在使用连接:^0.4.6 插件来检查颤振应用程序中的连接。我的代码如下:

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这次为空。

我该如何解决这个问题?

4

1 回答 1

0

由于您正在监听设备的连接,因此此回调将触发多次,因此在某一时刻它可能为空,但在另一时刻它不会为空。

我为您添加了一个空案例:

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());
}
于 2019-12-17T12:39:56.123 回答