对于移动应用,connectivity插件可以正常工作。
import 'package:connectivity/connectivity.dart';
var connectivityResult = await (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.
}
但是有什么方法可以检测Flutter网站中的按钮onPressed
上的Internet连接吗?
答案 0 :(得分:0)
您可以创建一个方法,只需单击按钮或小部件即可调用该方法
示例代码
class MyApp extends StatefulWidget {
@override
_State createState() => _State();
}
class _State extends State<MyApp> {
Future<bool> getStatus() async {
var connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.mobile) {
debugPrint("network available using mobile");
return true;
} else if (connectivityResult == ConnectivityResult.wifi) {
debugPrint("network available using wifi");
return true;
} else {
debugPrint("network not available");
return false;
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Connectivity Demo'),
),
body: SingleChildScrollView(
child: Container(
padding: EdgeInsets.all(32.0),
child: Column(
children: <Widget>[
GestureDetector(
onTap: () {
Future<bool> status = getStatus();
// now you can use status as per your requirement
},
child: Text("Get Internet Status"),
)
],
),
),
),
);
}
}
答案 1 :(得分:0)
要检查网络中的网络连通性,请使用此插件
https://pub.dev/packages/network_state
检查网络连接,您的代码看起来像
NetworkState.startPolling();
final ns = new NetworkState();
ns.addListener(() async {
final hasConnection = await ns.isConnected;
});
答案 2 :(得分:0)
也许您可以使用html库
import 'dart:html' as html;
html.window.navigator.connection
您可以签出并玩这个对象