在颤抖中检查互联网连接

时间:2019-12-16 23:29:58

标签: flutter dart

我正在尝试使用以下代码来检查Internet连接是否不稳定,我们希望使我们的应用程序可以脱机使用,但此代码似乎只是在循环。有一个更好的方法吗?我在调用http api之前先按下按钮就调用它。

程序包=连接:^ 0.4.6 + 1

library(data.table)
DT = data.table(mydf)

w  = DT[is.na(associatedid), which=TRUE]
dn = DT[w, DT[-w][.SD, on=.(id, year), roll=TRUE, x.associatedid]]
up = DT[w, DT[-w][.SD, on=.(id, year), roll=-Inf, x.associatedid]]
ww = na.omit(w[up == dn])
DT[ww, associatedid := dn[ww]]

    id year associatedid
 1:  1 2000         <NA>
 2:  1 2001       ABC123
 3:  1 2002       ABC123
 4:  1 2003       ABC123
 5:  1 2004       ABC123
 6:  1 2005       ABC123
 7:  2 2000         <NA>
 8:  2 2001       ABC123
 9:  2 2002       ABC123
10:  2 2003         <NA>
11:  2 2004       DEF456
12:  2 2005       DEF456
13:  3 2000         <NA>
14:  3 2001       ABC123
15:  3 2002       ABC123
16:  3 2003         <NA>
17:  3 2004         <NA>
18:  3 2005       ABC123

1 个答案:

答案 0 :(得分:0)

您应该监听网络连接事件,而不是直接调用它。

尝试一下:

import 'dart:async';

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

class CheckNetworkPage extends StatefulWidget {
  @override
  _CheckNetworkPageState createState() => _CheckNetworkPageState();
}

class _CheckNetworkPageState extends State<CheckNetworkPage> {
  StreamSubscription<ConnectivityResult> _networkSubscription;


  @override
  initState() {
    super.initState();

    _networkSubscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
      if (result == ConnectivityResult.mobile) {
        // I am connected to a mobile network.
      } else if (result == ConnectivityResult.wifi) {
        // I am connected to a wifi network.
      } else if (result == ConnectivityResult.none) {
        // I am not connected any network.
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }

// Be sure to cancel subscription after you are done
  @override
  dispose() {
    super.dispose();

    _networkSubscription.cancel();
  }
}