0

I am trying to use the following code to check an internet connection in flutter, we want to make our application usable offline but this code just seems to loop. Is there a better way to do this? Im calling this on a button press before calling an http api.

package is = connectivity: ^0.4.6+1

  var connectivityResult = await (Connectivity().checkConnectivity());
 if (connectivityResult == ConnectivityResult.mobile || connectivityResult == ConnectivityResult.wifi) {

 //Connection Exists


} else {

//No connection


}
Sam Cromer
  • 2,063
  • 10
  • 28
  • 50
  • 1
    Does this answer your question? [Check whether there is an Internet connection available on Flutter app](https://stackoverflow.com/questions/49648022/check-whether-there-is-an-internet-connection-available-on-flutter-app) – Benjamin Dec 16 '19 at 23:53

1 Answers1

0

You should listen to network connection event instead of calling it directly.

Take a try with this:

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:connectivity/connectivity.dart';

class CheckNetworkPage extends StatefulWidget {
  @override
  _CheckNetworkPageState createState() => _CheckNetworkPageState();
}

class _CheckNetworkPageState extends State<CheckNetworkPage> {
  StreamSubscription<ConnectivityResult> _networkSubscription;


  @override
  initState() {
    super.initState();

    _networkSubscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
      if (result == ConnectivityResult.mobile) {
        // I am connected to a mobile network.
      } else if (result == ConnectivityResult.wifi) {
        // I am connected to a wifi network.
      } else if (result == ConnectivityResult.none) {
        // I am not connected any network.
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }

// Be sure to cancel subscription after you are done
  @override
  dispose() {
    super.dispose();

    _networkSubscription.cancel();
  }
}
duongdt3
  • 1,648
  • 11
  • 16