Flutter Web 检查网络连接。
如果您想要在 index.html 上检查网络连接。
类型 1:
<script>
var isOnline = navigator.onLine
</script>
如果你想通过监听器进行检查,那么可以按照以下方式操作。
类型2:
<script>
var isOnline = navigator.onLine
window.addEventListener('online', function () {
this.isOnline = true
var x = document.getElementById("noInternet")
x.style.display = "none"
console.log('Became online')
})
window.addEventListener('offline', function () {
this.isOnline = false
var x = document.getElementById("noInternet")
x.style.display = "block"
console.log('Became offline')
})
function checkConnection() {
if (isOnline) {
var x = document.getElementById("noInternet")
x.style.display = "none"
}
else {
var x = document.getElementById("noInternet")
x.style.display = "block"
}
}
</script>
<body onload="checkConnection()">
<div class="centerPosition" id="noInternet">
<img src="cloud.png">
<h1>Uh-oh! No Internet</h1>
<h3>Please check your connection and try again</h3>
<button class="button buttonInternetConnection " onclick="checkConnection()">Try again</button>
</div>
</body>
类型3:
在Dart文件中检查网络连接:
import 'dart:html';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Connectivity example app'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
print("Connection Status:${window.navigator.onLine}");
},
child: Text('Check Connection'))),
);
}
}