Flutter Web- How to check internet connectivity?
Asked Answered
K

5

7

For mobile apps connectivity plugin is working fine.

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.
}

But is there is any way to detect internet connectivity on onPressed of button in Flutter web?

Kiger answered 28/12, 2019 at 7:3 Comment(0)
L
3

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'))),
    );
  }
}
Langton answered 26/10, 2021 at 12:7 Comment(0)
G
2

maybe you can use html library

import 'dart:html' as html;
html.window.navigator.connection

you can checkout and play with this object

Golliner answered 7/1, 2020 at 15:39 Comment(0)
V
1

to check network Connectivity in flutter for web use this plugin

https://pub.dev/packages/network_state

to check network Connectivity your code looks like

NetworkState.startPolling();

final ns = new NetworkState();

ns.addListener(() async {
final hasConnection = await ns.isConnected;
});
Vedetta answered 28/12, 2019 at 15:57 Comment(0)
M
0

You can create a method, call that method on click of a button or widget

Sample code

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"),
              )
            ],
          ),
        ),
      ),
    );
  }
}
Mckim answered 28/12, 2019 at 7:16 Comment(0)
E
0

This post might be helpful. It uses internet_connection_checker package. However, it doesn't have full web support, but the forked package described here seems to work fine.

Alternatively you might want to use network_state package.

Ermin answered 2/11, 2022 at 11:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.