简体   繁体   English

互联网连接颤抖

[英]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.如果计数器变量有它的默认值,你就知道你收到了初始事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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