【问题标题】:Flutter Web- How to check internet connectivity?Flutter Web - 如何检查互联网连接?
【发布时间】:2020-04-17 21:38:42
【问题描述】:

对于移动应用,connectivity 插件工作正常。

import 'package:connectivity/connectivity.dart';

var connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.mobile) {
  // I am connected to a mobile network.
} else if (connectivityResult == ConnectivityResult.wifi) {
  // I am connected to a wifi network.
}

但是有什么方法可以检测 Flutter web 中按钮的onPressed 上的互联网连接吗?

【问题讨论】:

    标签: flutter dart flutter-dependencies flutter-web


    【解决方案1】:

    flutter web 互联网检查。

    如果您想在 index.html 上检查互联网连接。

    类型 1:

    <script>
        var isOnline = navigator.onLine
    </script>
    

    如果您想通过侦听器进行检查,请这样做。

    类型 2:

    <script>
    
        var isOnline = navigator.onLine
        window.addEventListener('online', function () {
            this.isOnline = true
            var x = document.getElementById("noInternet")
            x.style.display = "none"
            console.log('Became online')
        })
        window.addEventListener('offline', function () {
            this.isOnline = false
            var x = document.getElementById("noInternet")
            x.style.display = "block"
            console.log('Became offline')
        })
    
        function checkConnection() {
            if (isOnline) {
                var x = document.getElementById("noInternet")
                x.style.display = "none"
    
            }
            else {
                var x = document.getElementById("noInternet")
                x.style.display = "block"
            }
        }
    
    </script>
    
    <body onload="checkConnection()">
        <div class="centerPosition" id="noInternet">
            <img src="cloud.png">
            <h1>Uh-oh! No Internet</h1>
            <h3>Please check your connection and try again</h3>
            <button class="button buttonInternetConnection " onclick="checkConnection()">Try again</button>
        </div>
    </body>
    

    类型 3:

    检查 dart 文件中的互联网连接:

    import 'dart:html';   //Important to add this line
    
    import 'package:flutter/foundation.dart';
    import 'package:flutter/material.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      // This widget is the root of your application.
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: MyHomePage(title: 'Flutter Demo Home Page'),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      MyHomePage({Key? key, required this.title}) : super(key: key);
    
      final String title;
    
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: const Text('Connectivity example app'),
          ),
          body: Center(
              child: ElevatedButton(
                  onPressed: () {
                    print("Connection Status:${window.navigator.onLine}"); //Important to add this line
                  },
                  child: Text('Check Connection'))),
        );
      }
    }
    

    【讨论】:

      【解决方案2】:

      也许你可以使用 html 库

      import 'dart:html' as html;
      html.window.navigator.connection
      

      你可以结帐和玩这个对象

      【讨论】:

        【解决方案3】:

        使用这个插件在 Flutter 中检查网络连接

        https://pub.dev/packages/network_state

        检查网络连接你的代码看起来像

        NetworkState.startPolling();
        
        final ns = new NetworkState();
        
        ns.addListener(() async {
        final hasConnection = await ns.isConnected;
        });
        

        【讨论】:

          【解决方案4】:

          您可以创建一个方法,在单击按钮或小部件时调用该方法

          示例代码

          class MyApp extends StatefulWidget {
            @override
            _State createState() => _State();
          }
          
          class _State extends State<MyApp> {
            Future<bool> getStatus() async {
              var connectivityResult = await (Connectivity().checkConnectivity());
              if (connectivityResult == ConnectivityResult.mobile) {
                debugPrint("network available using mobile");
                return true;
              } else if (connectivityResult == ConnectivityResult.wifi) {
                debugPrint("network available using wifi");
                return true;
              } else {
                debugPrint("network not available");
                return false;
              }
            }
          
            @override
            Widget build(BuildContext context) {
              return Scaffold(
                appBar: AppBar(
                  title: Text('Connectivity Demo'),
                ),
                body: SingleChildScrollView(
                  child: Container(
                    padding: EdgeInsets.all(32.0),
                    child: Column(
                      children: <Widget>[
                        GestureDetector(
                          onTap: () {
                            Future<bool> status =  getStatus();
                            // now you can use status as per your requirement
                          },
                          child: Text("Get Internet Status"),
                        )
                      ],
                    ),
                  ),
                ),
              );
            }
          }
          

          【讨论】:

            猜你喜欢
            • 2019-07-27
            • 2022-11-05
            • 2023-01-13
            • 1970-01-01
            • 1970-01-01
            • 2013-02-02
            • 1970-01-01
            • 2019-07-30
            • 2022-12-01
            相关资源
            最近更新 更多