简体   繁体   English

Flutter - 检查互联网连接时出错

[英]Flutter - Error in checking internet connectivity

I have implemented the below given code to check if the user is connected to the internet or not, and if the user is not connected then display a no internet screen otherwise show the apps content.我已经实现了下面给定的代码来检查用户是否连接到互联网,如果用户没有连接,则显示无互联网屏幕,否则显示应用程序内容。 but the setState is not updating the connection status.但是 setState 没有更新连接状态。 It works fine when using on a single screen, but when I open another screen and then return to this screen again it always return internet connection as false, which is the initial value.在单个屏幕上使用时它工作正常,但是当我打开另一个屏幕然后再次返回此屏幕时,它总是将互联网连接返回为 false,这是初始值。 I implemented the same code for every screen I have.我为我拥有的每个屏幕实现了相同的代码。

[Edit: I noticed that it only happens if i implement the same code for every screen that I have, if I implement this code on a single screen, than it works fine.] [编辑:我注意到只有当我为我拥有的每个屏幕实现相同的代码时才会发生这种情况,如果我在单个屏幕上实现此代码,它就会正常工作。]

bool hasInternet = false;
  late StreamSubscription internetSubscription;

  @override
  void initState() {
    super.initState();
    debugPrint(hasInternet.toString());
    internetSubscription =
        InternetConnectionChecker().onStatusChange.listen((status) {
      final hasInternet = status == InternetConnectionStatus.connected;
      setState(() => this.hasInternet = hasInternet);
    });
  }

  @override
  void dispose() {
    super.dispose();
    internetSubscription.cancel();
  }

@override
  Widget build(BuildContext context) {
    return hasInternet
        ? [App Content]
        : const NoInternetScreen();
  }

The error was occuring because I used that code on every screen that my app had.发生错误是因为我在我的应用程序的每个屏幕上都使用了该代码。 I solved it by wrapping the MaterialApp's home widget.我通过包装 MaterialApp 的 home 小部件解决了这个问题。

MaterialApp(
          theme: ThemeData.dark(),
          home: hasInternet ? const MainScreen() : const NoInternetScreen(),

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM