在Flutter应用程序上连续检查互联网断开连接

时间:2018-11-29 11:28:31

标签: dart flutter connectivity

我正在Flutter上创建一个移动应用程序,并调用在Node.js上创建的REST API,以便始终连接并查询我的Oracle DB。

到目前为止,我已经使用 connectivity 0.3.2 来在异步调用或登录操作之前检查网络连接。像下面的例子一样:

    checkConnectivity(context) async{

  String connectionStatus;
  StreamSubscription<ConnectivityResult> _connectivitySubscription;
  final Connectivity _connectivity = new Connectivity();
  try {
    connectionStatus = (await _connectivity.checkConnectivity()).toString();
    _connectivity.onConnectivityChanged.listen((ConnectivityResult result) {
      connectionStatus = result.toString();
      //   print(connectionStatus);
    });
  } on PlatformException catch (e) {
    print(e.toString());
    connectionStatus = 'Failed to get connectivity.';
  }
  if(connectionStatus == "ConnectivityResult.none"){
    components.alertPopup(context, "No Internet Connection available" , "Please check your internet connection and try again");}

}

我想问一下是否有任何可能的方式,使用户在每次使用该应用程序时(即使他只是在不进行API调用的情况下读取数据)都连续检查互联网断开连接所有)。

例如,使用SnackBar通知用户他离线。

3 个答案:

答案 0 :(得分:4)

您已经编写了代码来执行所需的操作。您可以轻松地将其包装在页面StateInheritedWidget或其他管理类中。< / p>

final Connectivity _connectivity;
final StreamSubscription<ConnectivityResult> _subscription;

ConstructorForWhateverClassThisIs() {
    _connectivity = new Connectivity();
    _subscription = _connectivity.onConnectivityChanged.listen(onConnectivityChange);
}

void onConnectivityChange(ConnectivityResult result) {
    // TODO: Show snackbar, etc if no connectivity
}

void dispose() {
    // Always remember to cancel your subscriptions when you're done.
    subscription.cancel();
}

根据documentationonConnectivityChanged将在更改后随新结果更新,这意味着您可以监听更改而不必手动查询。

文档摘录:

  

您还可以通过订阅以下内容来监听网络状态更改:   连接插件公开的流

答案 1 :(得分:0)

我刚刚实现了该软件包https://pub.dartlang.org/packages/flutter_offline,可以非常直接地解决这个问题。

请按步骤导入软件包 导入'package:flutter_offline / flutter_offline.dart';

您包含在项目中并开始使用该库,如以下示例所示:

此后,您在Widget build(BuildContext context)上包含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),
                label: Text("Barcode"),
                onPressed: _scanQR,
              ),
              new Container(
                // padding: EdgeInsets.only(left: 24.0, right: 24.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    Column(
                      children: [
                        Icon(Icons.hotel, color: Colors.blueGrey[600]),
                      ],
                    ),
                    Column(
                      children: [
                        Icon(Icons.hotel, color: Colors.blue[400]),
                      ],
                    ),
                  ],
                ),

                alignment: Alignment(0.0, 0.0),
              ),
            ],
          ),
          floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
          drawer: MenuDrawer(),
        )
    );
  }

答案 2 :(得分:0)

您的pubspec.yaml,将以下行添加为:

flutter_offline: "^0.3.0"

导入

import 'package:flutter_offline/flutter_offline.dart';

示例:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
          appBar: AppBar(
            title: Text("Connection status"),
          ),
          body: Builder(
            builder: (BuildContext context) {
              return OfflineBuilder(
                connectivityBuilder: (BuildContext context,
                    ConnectivityResult connectivity, Widget child) {
                  final bool connected =
                      connectivity != ConnectivityResult.none;
                  return Stack(
                    fit: StackFit.expand,
                    children: [
                      child,
                      Positioned(
                        left: 0.0,
                        right: 0.0,
                        height: 32.0,
                        child: AnimatedContainer(
                          duration: const Duration(milliseconds: 300),
                          color:
                              connected ? Colors.green : Colors.red,
                          child: connected
                              ? Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: <Widget>[
                                    Text(
                                      "YOU ARE OFFLINE",
                                      style: TextStyle(color: Colors.white),
                                    ),
                                  ],
                                )
                              : Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: <Widget>[
                                    Text(
                                      "YOU ARE OFFLINE",
                                      style: TextStyle(color: Colors.white),
                                    ),
                                    SizedBox(
                                      width: 8.0,
                                    ),
                                    SizedBox(
                                      width: 12.0,
                                      height: 12.0,
                                      child: CircularProgressIndicator(
                                        strokeWidth: 2.0,
                                        valueColor:
                                            AlwaysStoppedAnimation<Color>(
                                                Colors.white),
                                      ),
                                    ),
                                  ],
                                ),
                        ),
                      ),
                    ],
                  );
                },
                child: Center(
                  child: Text("ONLINE Or OFFLINE"),
                ),
              );
            },
          )),
    );
  }
}