如何连续检查Flutter上的Internet连接或不连接?

时间:2019-03-08 10:13:25

标签: dart flutter

我使用此代码检查互联网。我也将此函数包装到initState中。当互联网不可用时,小吃栏始终显示。但是,连接到互联网后,小吃店并没有消失。我无法使用连通性插件,因为他们在Android上表示,该插件不能保证可以连接到Internet。

 checking1(TextEditingController usernameController, BuildContext context,
      String _url, GlobalKey<ScaffoldState> _scaffoldKey) async {
    try {
      final result = await InternetAddress.lookup('google.com');
      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
        usernameController.text == '' ?
        showDialog(...some code...) :
        usernameValidation(usernameController.text, context, _url);
      }
    }
    on SocketException
    catch (_) {
      _showSnackBar(_scaffoldKey);
    }
  }

4 个答案:

答案 0 :(得分:1)

enter image description here

完整的示例,演示了Internet连接及其源的侦听器。

Original post

import 'dart:async';
import 'dart:io';
import 'package:connectivity/connectivity.dart';
import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(home: HomePage()));

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  Map _source = {ConnectivityResult.none: false};
  MyConnectivity _connectivity = MyConnectivity.instance;

  @override
  void initState() {
    super.initState();
    _connectivity.initialise();
    _connectivity.myStream.listen((source) {
      setState(() => _source = source);
    });
  }

  @override
  Widget build(BuildContext context) {
    String string;
    switch (_source.keys.toList()[0]) {
      case ConnectivityResult.none:
        string = "Offline";
        break;
      case ConnectivityResult.mobile:
        string = "Mobile: Online";
        break;
      case ConnectivityResult.wifi:
        string = "WiFi: Online";
    }

    return Scaffold(
      appBar: AppBar(title: Text("Internet")),
      body: Center(child: Text("$string", style: TextStyle(fontSize: 36))),
    );
  }

  @override
  void dispose() {
    _connectivity.disposeStream();
    super.dispose();
  }
}

class MyConnectivity {
  MyConnectivity._internal();

  static final MyConnectivity _instance = MyConnectivity._internal();

  static MyConnectivity get instance => _instance;

  Connectivity connectivity = Connectivity();

  StreamController controller = StreamController.broadcast();

  Stream get myStream => controller.stream;

  void initialise() async {
    ConnectivityResult result = await connectivity.checkConnectivity();
    _checkStatus(result);
    connectivity.onConnectivityChanged.listen((result) {
      _checkStatus(result);
    });
  }

  void _checkStatus(ConnectivityResult result) async {
    bool isOnline = false;
    try {
      final result = await InternetAddress.lookup('example.com');
      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
        isOnline = true;
      } else
        isOnline = false;
    } on SocketException catch (_) {
      isOnline = false;
    }
    controller.sink.add({result: isOnline});
  }

  void disposeStream() => controller.close();
}

答案 1 :(得分:0)

connectivity软件包将完成您想要的。它有一个onConnectivityChanged流,您可以订阅。当连接状态更改时,这将通知您的应用程序。但是,仅仅因为您的设备已连接到网络并不意味着它可以访问服务器并已连接。因此,在更新应用程序的内部状态之前,DNS查询将是一个好主意。

https://pub.dartlang.org/documentation/connectivity/latest/connectivity/Connectivity-class.html

答案 2 :(得分:0)

此软件包的另一个选择也可以是:https://pub.dartlang.org/packages/flutter_offline,这个问题的处理非常简单。

您首先需要导入软件包'package:flutter_offline / flutter_offline.dart';

之后,在Widget build(BuildContext上下文)上包含OfflineBuilder,它将连续读取ConnectivityResult的所有所有流更改。

就像链接上的示例一样,或类似于以下示例

      @override
  Widget build(BuildContext context) {
    return OfflineBuilder(

        debounceDuration: Duration.zero,
        connectivityBuilder: (
            BuildContext context,
            ConnectivityResult connectivity,
            Widget child,
            ) {
          if (connectivity == ConnectivityResult.none) {

            return Scaffold(
              appBar: AppBar(
                title: const Text('Home'),
              ),
              body: Center(child: Text('Please check your internet connection!')),
            );
          }
          return child;
        },


        child: Scaffold(
          resizeToAvoidBottomPadding: false,
          appBar: AppBar(
              title: Text("Home")
          ),
          body: new Column(
            children: <Widget>[
              new Container(
                decoration: new BoxDecoration(color: Theme.of(context).cardColor),
                child: _buildTxtSearchBox(),
              ),
              new Divider(height: 10.0),
              new FloatingActionButton.extended(
                icon: Icon(Icons.camera_alt),
              ),
              new Container(
              ... 
              ),
            ],
          ),
          floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
          drawer: MenuDrawer(),
        )
    );
  }

答案 3 :(得分:0)

我认为这是可靠且更具说服力的:

Future<bool> connectivityChecker() async {
  var connected = false;
  print("Checking internet...");
  try {
    final result = await InternetAddress.lookup('google.com');
    final result2 = await InternetAddress.lookup('facebook.com');
    final result3 = await InternetAddress.lookup('microsoft.com');
    if ((result.isNotEmpty && result[0].rawAddress.isNotEmpty) ||
        (result2.isNotEmpty && result2[0].rawAddress.isNotEmpty) ||
        (result3.isNotEmpty && result3[0].rawAddress.isNotEmpty)) {
      print('connected..');
      connected = true;
    } else {
      print("not connected from else..");
      connected = false;
    }
  } on SocketException catch (_) {
    print('not connected...');
    connected = false;
  }
  return connected;
}

基于返回的connect的bool值,我将运行基于计时器的循环以再次检查Internet,直到其连接为止。公开接受任何建议