【问题标题】:check internet connection in flutter在颤动中检查互联网连接
【发布时间】:2020-04-09 10:47:49
【问题描述】:

我正在尝试使用以下代码来检查互联网连接,我们希望使我们的应用程序可以离线使用,但这段代码似乎只是循环。有一个更好的方法吗?我在调用 http api 之前按下按钮调用它。

包是 = 连接性:^0.4.6+1

  var connectivityResult = await (Connectivity().checkConnectivity());
 if (connectivityResult == ConnectivityResult.mobile || connectivityResult == ConnectivityResult.wifi) {

 //Connection Exists


} else {

//No connection


}

【问题讨论】:

标签: flutter dart


【解决方案1】:

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

试试这个:

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();
  }
}

【讨论】:

    猜你喜欢
    • 2020-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多