Flutter 检测网络
https://pub.dev/packages/connectivity
案例代码
import 'package:flutter/material.dart';
import 'package:connectivity/connectivity.dart';
class CameraPage extends StatefulWidget{
CameraPage({Key key});
_CameraPage createState() => _CameraPage();
}
class _CameraPage extends State {
var subscription ;
var whatNetwork = '未检测网络';
initState() {
super.initState();
getNetwork();
}
dispose() {
super.dispose();
subscription .cancel();
}
@override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
appBar: AppBar(
title: Text('设备硬件')
),
body: ListView(
children: <Widget>[
Text('${whatNetwork}'),
]
)
);
}
// 网络监测
getNetwork() async{
subscription = await (Connectivity().checkConnectivity());
// Got a new connectivity status!
switch(subscription) {
case ConnectivityResult.mobile:
setState(() {whatNetwork = '手机网络';});
break;
case ConnectivityResult.wifi:
setState(() {whatNetwork = '网络WIFI';});
break;
default:
setState(() {whatNetwork = '无网络';});
}
}
}