flutter web internet check.
if you want to check the internet connection on index.html.
Type 1:
<script>
var isOnline = navigator.onLine
</script>
if you want to check via listener then do like this.
Type 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>
Type 3:
check internet connection in dart file:
import 'dart:html'; //Important to add this line
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@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}"); //Important to add this line
},
child: Text('Check Connection'))),
);
}
}