Flutter 检测网络连接

交流
siman 2020-3-30 10:45:25 4204 1 来自河北
  1. import 'package:flutter/material.dart';
  2. import 'package:connectivity/connectivity.dart';

  3. class ConnectivityPage extends StatefulWidget {
  4.   ConnectivityPage({Key key}) : super(key: key);

  5.   _ConnectivityPageState createState() => _ConnectivityPageState();
  6. }

  7. class _ConnectivityPageState extends State<ConnectivityPage> {
  8.   //网络状态描述
  9.   String _connectStateDescription;

  10.   var subscription;

  11.   @override
  12.   void initState() {
  13.     super.initState();
  14.     //监测网络变化
  15.     subscription = Connectivity()
  16.         .onConnectivityChanged
  17.         .listen((ConnectivityResult result) {
  18.       if (result == ConnectivityResult.mobile) {
  19.         setState(() {
  20.           _connectStateDescription = "手机网络";
  21.         });
  22.       } else if (result == ConnectivityResult.wifi) {
  23.         setState(() {
  24.           _connectStateDescription = "Wifi网络";
  25.         });
  26.       } else {
  27.         setState(() {
  28.           _connectStateDescription = "无网络";
  29.         });
  30.       }
  31.       print(_connectStateDescription);
  32.     });
  33.   }

  34.   @override
  35.   Widget build(BuildContext context) {
  36.     return Scaffold(
  37.       appBar: AppBar(title: Text("监测网络")),
  38.       body: Center(
  39.         // 显示网络状态
  40.         child: Text("$_connectStateDescription"),
  41.       ),
  42.     );
  43.   }

  44.   @override
  45.   void dispose() {
  46.     super.dispose();
  47.     //在页面销毁的时候一定要取消网络状态的监听
  48.     subscription.cancle();
  49.   }
  50. }
复制代码
我们使用 connectivity 这个插件来监测网络。 藏宝库28xin.com
您需要登录后才可以回帖 登录 | 立即注册
感谢分享
2022-8-4 21:48:30 回复

Powered by CangBaoKu v1.0 小黑屋 藏宝库It社区 ( 冀ICP备14008649号 )

GMT+8, 2024-5-14 23:20 , Processed in 0.163951 second(s), 37 queries . © 2003-2025 cbk Team.

快速回复 返回顶部 返回列表