Flutter Web - 如何检查网络连接?

6

对于移动应用程序,连接插件运行良好。

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 上检测网络连接?
5个回答

3

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

您可以结账并使用此对象


1

要在Flutter Web中检查网络连接,请使用此插件。

https://pub.dev/packages/network_state

检查网络连接的代码如下:

NetworkState.startPolling();

final ns = new NetworkState();

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

0

0
你可以创建一个方法,在点击按钮或小部件时调用该方法。 示例代码
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"),
              )
            ],
          ),
        ),
      ),
    );
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接