Flutter桌面软件开发如何监听网络变化
Flutter桌面软件开发如何监听网络变化呢?其实在Flutter中可以使用connectivity_plus监听网络变化
地址: https://pub.dev/packages/connectivity_plus
1、安装依赖
dependencies:
connectivity_plus: ^2.3.6+1
2、使用connectivity_plus监听Flutter桌面软件网络变化
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
class NetworkPage extends StatefulWidget {
const NetworkPage({super.key});
@override
State<NetworkPage> createState() => _NetworkPageState();
}
class _NetworkPageState extends State<NetworkPage> {
dynamic subscription;
String _stateText = "检测中...";
@override
void initState() {
super.initState();
subscription = Connectivity()
.onConnectivityChanged
.listen((ConnectivityResult result) {
if (result == ConnectivityResult.wifi) {
setState(() {
_stateText = "已连接 wifi";
});
} else if (result == ConnectivityResult.mobile) {
setState(() {
_stateText = "处于手机网络";
});
} else {
setState(() {
_stateText = "没有网络";
});
}
});
}
@override
void dispose() {
// TODO: implement dispose
super.dispose();
subscription.cancel();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('检测网络'),
),
body: Center(
child: Text(_stateText),
),
);
}
}