简体   繁体   English

flutter 中的互联网连接

[英]Internet connectivity in flutter

How to implement continuous Internet connectivity check in flutter only once for whole app, I have almost complete app, now I need to add Internet connectivity check, Please help, thanks in advance如何在 flutter 中实现对整个应用程序的持续互联网连接检查,我几乎完整的应用程序,现在我需要添加互联网连接检查,请帮助,提前谢谢

  @override
  Widget build(BuildContext context) {
      return StreamBuilder<ConnectivityResult>(
          stream: connectivityStream,
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              final connectivityResult = snapshot.data;
              if (connectivityResult == ConnectivityResult.none) {
                return MaterialApp(
                  debugShowCheckedModeBanner: false,
                  home: NoInternetConnectionScreen(),
                );
              }
              return MaterialApp(
                debugShowCheckedModeBanner: false,
                home: SplashScreen(),
                routes: routes,
              );

            } else if (snapshot.hasError) {

              return MaterialApp(
                debugShowCheckedModeBanner: false,
                home: NoInternetConnectionScreen(),
              );
            }

            return Center(child: CircularProgressIndicator());
          }
      );
  }

The connectivity plugin states in its docs that it only provides information if there is a network connection, but not if the network is connected to the Internet连接插件在其文档中声明它仅在有网络连接时提供信息,而不在网络连接到 Internet 时提供信息

Note that on Android, this does not guarantee connection to Internet.请注意,在 Android 上,这并不能保证连接到 Internet。 For instance, the app might have wifi access but it might be a VPN or a hotel WiFi with no access.例如,该应用程序可能具有 wifi 访问权限,但它可能是无法访问的 VPN 或酒店 WiFi。

You can use您可以使用

import 'dart:io';
...
try {
  final result = await InternetAddress.lookup('google.com');
  if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
    print('connected');
  }
} on SocketException catch (_) {
  print('not connected');
}

I think that the best practice would be using connectivity plugin and wrapping your app in a stream builder我认为最好的做法是使用连接插件并将您的应用程序包装在流构建器中

https://pub.dev/packages/connectivity https://pub.dev/packages/connectivity

Your main screen / main page should be something like this:您的主屏幕/主页应该是这样的:

class MainScreen extends StatelessWidget {

  Stream connectivityStream = Connectivity().onConnectivityChanged;
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppStyle.backgroundColor,
      body: StreamBuilder<ConnectivityResult>(
        stream: connectivityStream,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            final connectivityResult = snapshot.data;

            if (connectivityResult == ConnectivityResult.none) {
              return NoConnectionPage();
            }
            return HomePage();

          } else if (snapshot.hasError) {

            return NoConnectionPage(); 
            // or some error page, but I think no connection page is what you
            // want here
          } 

          return Center(child: CircularProgressIndicator());
        }
      )
    );
  }
}

In NoConnectionPage() you can have a button that retries the connection with a method like this:在 NoConnectionPage() 中,您可以使用一个按钮来使用如下方法重试连接:

void _retryConnection() async {
      try {
        final result = await InternetAddress.lookup('example.com');
      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
        print('connected');
        Navigator.of(context).pop(); // going back to MainScreen()
      }
    } on SocketException catch (_) {
      print('not connected');
    }
  }

Simply use the internet_connectivity_checker package like this:只需像这样使用internet_connectivity_checker package:

class Hello extends StatelessWidget {
  const Hello({super.key});

  @override
  Widget build(BuildContext context) {
    return internetConnectivityBuilder(
      (status) {
        bool connected = status == ConnectivityStatus.online;
        return Text(connected ? "Online" : "Offline");
      },
    );
  }
}

Get more info about this package here .在此处获取有关此 package 的更多信息。

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

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