简体   繁体   中英

Internet Connectivity flutter

This is the code i use to check for internet connectivity in flutter

import 'dart:async';
import 'package:internet_connection_checker/internet_connection_checker.dart';
import 'package:flutter/material.dart';

class CheckingConnectivity {
  late InternetConnectionChecker internetConnectionChecker;
  late StreamSubscription<InternetConnectionStatus> connectionStatusListener;
  bool hasInternetConnection = false;
  var onStatusChange = InternetConnectionChecker().onStatusChange;
  //Checking Internet connection
  internetChecker(BuildContext context) async {
    var connectionChanging = onStatusChange.listen((event) async {
      hasInternetConnection = event == InternetConnectionStatus.connected;

      if(hasInternetConnection == true) {
        showSnackBar(context, "Connected");
      } else if(hasInternetConnection == false) {
        showSnackBar(context, "Disconnected");
      } 
    });
  }
  showSnackBar(BuildContext context, String message) {
    final snackBar = SnackBar(content:  Text(message,
      style: TextStyle(color: Colors.white, backgroundColor: Colors.grey),));
    ScaffoldMessenger.of(context).showSnackBar(snackBar);
  }
}

When the application launches, it shows connected even when i am already connected to the internet. I want it to show connected only when i reconnect to the internet. Thank you very much. I appreciate

So, when looking through the library's code, I see that they initially always send a status update. A simple workaround would be to have a counter variable that increments every time you receive a status change event. If the counter variable has its default value, you know you received the initial event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM