Flutter 檢測網絡 connectivity
Flutter 檢測網絡完整 demo
import 'package:connectivity/connectivity.dart';
_NetworkPageState createState() => _NetworkPageState(); }
class _NetworkPageState extends State<NetworkPage> { String _state;
var _subscription;
@override initState() {
super.initState();
_subscription=Connectivity().onConnectivityChanged.listen((ConnectivityResult result) { // Got a new connectivity status!
if (result == ConnectivityResult.mobile) {
setState(() { _state="手機網絡";
});
// I am connected to a mobile network. } else if (result == ConnectivityResult.wifi) {
setState(() { _state="Wifi 網絡";
});
// I am connected to a wifi network. }else{
setState(() { _state="沒有網絡";
}); }
}); }
@override dispose() {
super.dispose();
_subscription.cancel(); }
Widget build(BuildContext context) {
return Scaffold( appBar: AppBar(
title: Text("檢測網絡變化"), ),
body:Text("${_state}"), );
} }