Flutter-手机网络状态监听

前言

在Android中会在基础类中监听手机的网络状态,并作出相应的提示,在Flutter 中也提供了相应的package,但是略有不同;

1.依赖

dependencies:
  connectivity: ^0.3.2

2.导入

import 'package:flutter_cache_manager/flutter_cache_manager.dart';

3.简单使用

检查当前网络状态

注意:在Android上,这并不保证连接到Internet。例如,该应用程序可能有WiFi接入,但可能是VPN或没有接入的酒店WiFi。也就是说网络状态是'wifi',也不代表你的手机能进行网络访问。

import 'package:connectivity/connectivity.dart';

var connectivityResult = await (new 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.
}

监听网络状态

请注意,不应该使用当前的网络状态来决定是否可以可靠地进行网络连接。
网络层可能会出现超时和错误,需要在应用程序代码中做好异常处理;

import 'package:connectivity/connectivity.dart';

initState() {
  subscription = new Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
    // Got a new connectivity status!
  })
}

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

4.例子

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:connectivity/connectivity.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, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String _connectionStatus = 'Unknown';
  final Connectivity _connectivity = Connectivity();
  StreamSubscription<ConnectivityResult> _connectivitySubscription;

  @override
  void initState() {
    super.initState();
    initConnectivity();
    _connectivitySubscription =
        _connectivity.onConnectivityChanged.listen((ConnectivityResult result) {
      setState(() => _connectionStatus = result.toString());
    });
  }

  @override
  void dispose() {
    _connectivitySubscription.cancel();
    super.dispose();
  }

   //平台消息是异步的,所以我们用异步方法初始化。
  Future<Null> initConnectivity() async {
    String connectionStatus;
    //平台消息可能会失败,因此我们使用Try/Catch PlatformException。
    try {
      connectionStatus = (await _connectivity.checkConnectivity()).toString();
    } on PlatformException catch (e) {
      print(e.toString());
      connectionStatus = 'Failed to get connectivity.';
    }

    // 如果在异步平台消息运行时从树中删除了该小部件,
    // 那么我们希望放弃回复,而不是调用setstate来更新我们不存在的外观。
    if (!mounted) {
      return;
    }

    setState(() {
      _connectionStatus = connectionStatus;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Plugin example app'),
      ),
      body: Center(child: Text('Connection Status: $_connectionStatus\n')),
    );
  }
}

5.tips

wifi移动网络 同时存在时,监听中提示当前网络wifi;并且此时断开或者连接移动网络无回调

6.资料参考

https://pub.dartlang.org/packages/connectivity

  • 这个网址提供了很多兼容Android 和 IOS 的 package;

推荐阅读更多精彩内容