0

I want to check if there an internet connection on my device I already try the Connectivity but it doesn't help me because it check if the device is connecting to wifi or not, but doesn't discover if there an internet problem my code :

import 'dart:async';
import 'package:connectivity/connectivity.dart';
import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:flutter/services.dart';
class WebviewUi extends StatefulWidget {

@override
_WebviewState createState() => _WebviewState();
}

class _WebviewState extends State<WebviewUi> {
String _connectionStatus;
final Connectivity _connectivity = new Connectivity();
StreamSubscription<ConnectivityResult> _connectivitySubscription;
@override
void initState() {
super.initState();
SystemChrome.setSystemUIOverlayStyle(
SystemUiOverlayStyle(statusBarColor: Colors.deepOrangeAccent)
);

_connectivitySubscription =          
_connectivity.onConnectivityChanged.listen((ConnectivityResult result){
  setState(() {
    _connectionStatus = result.toString();
    print('Connection Status : $_connectionStatus');
  });
});
}

@override
void dispose() {
_connectivitySubscription.cancel();
super.dispose();
}

@override
Widget build(BuildContext context) {
return Scaffold(
    appBar: PreferredSize(
      preferredSize: Size.fromHeight(0),
      child: AppBar(
      ),

    ),
    body: (_connectionStatus == "ConnectivityResult.mobile" || 
_connectionStatus == "ConnectivityResult.wifi") ?
    WebviewScaffold(
      /*appBar: AppBar(
    title: Text(''),
    backgroundColor: Colors.deepOrangeAccent,

  ),*/

      url: "https://www.google.net/",

      withJavascript: true,
    )

        :
    Container(
        child: Image.asset(
          'assets/Internet-Access-Error.jpg',
        )
    )


);
}
}

when I tried this code on the emulator I switched to airplane mode on my labtop it's show:

net::ERR_NAME_NOT_RESOLVED

but I want to display an widget that tell the there's an internet problem or no internet. How can I preform this I searched a lot over the websites and facebook groups I didn't find any solution

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Ghost
  • 45
  • 1
  • 8

1 Answers1

0

Use connectivity package Flutter team. This package can identify whether wifi or mobile data is enabled or not. But if internet actualy can reach or not cannot be identified. In that case @Günter solution is great. Note that you can also use http package http.get() in a try catch block and identify SocketException(Im not sure that this is reusable great solution.).

Simple example:

import 'dart:async';

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

class SplashPage extends StatefulWidget {
  @override
  _SplashPageState createState() => _SplashPageState();
}

class _SplashPageState extends State<SplashPage> {
  BuildContext ctx;
  bool canProceed = true;

  bool isOffline = false;
  bool dialogIsVisible = false;

  final Connectivity _connectivity = Connectivity();
  StreamSubscription<ConnectivityResult> _connectivitySubscription;

  @override
  void initState() {
    initConnectivity();
    _connectivitySubscription =
        _connectivity.onConnectivityChanged.listen(_updateConnectionStatus);
    super.initState();
  }

  @override
  void dispose() {
    _connectivitySubscription.cancel();
    super.dispose();
  }

  Future<void> initConnectivity() async {
    ConnectivityResult result;
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      result = await _connectivity.checkConnectivity();
    } on PlatformException catch (e) {
      print(e.toString());
    }

    if (!mounted) {
      return;
    }

    _updateConnectionStatus(result);
  }

  Future<void> _updateConnectionStatus(ConnectivityResult result) async {
    switch (result) {
      case ConnectivityResult.wifi:
        setState(() {
          isOffline = false;
          dialogIsVisible = false;
        });
        break;
      case ConnectivityResult.mobile:
        setState(() {
          isOffline = false;
          dialogIsVisible = false;
        });
        break;
      case ConnectivityResult.none:
        setState(() => isOffline = true);
        buildAlertDialog("Internet connection cannot be establised!");
        break;
      default:
        setState(() => isOffline = true);
        break;
    }
  }

  void buildAlertDialog(String message) {
    SchedulerBinding.instance.addPostFrameCallback((_) => setState(() {
      if (isOffline && !dialogIsVisible) {
        dialogIsVisible = true;
        showDialog(
            barrierDismissible: false,
            context: ctx,
            builder: (BuildContext context) {
              return AlertDialog(
                title: Text(message, textAlign: TextAlign.center, style: TextStyle(fontSize: 14.0),),
                content: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    Icon(Icons.portable_wifi_off, color: Colors.redAccent, size: 36.0,),
                    canProceed ? Text(
                      "Check your internet connection before proceeding.", textAlign: TextAlign.center, style: TextStyle(fontSize: 12.0),) : Text(
                      "Please! proceed by connecting to a internet connection", textAlign: TextAlign.center, style: TextStyle(fontSize: 12.0, color: Colors.red),),
                  ],
                ),
                actions: <Widget>[
                  RaisedButton(
                    onPressed: () {
                      SystemChannels.platform
                          .invokeMethod('SystemNavigator.pop');
                    },
                    child: Text(
                      "CLOSE THE APP",
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                  RaisedButton(
                    onPressed: () {
                      if (isOffline) {
                        setState(() {
                          canProceed = false;
                        });
                      } else {
                        Navigator.pop(ctx);
                        //your code
                      }
                    },
                    child: Text(
                      "PROCEED",
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                ],
              );
            });
      }
    }));
  }

  @override
  Widget build(BuildContext context) {
    ctx = context;
    return Scaffold(
        body: Center(
          child: CircularProgressIndicator(),
        ),
    );
  }
}
Blasanka
  • 21,001
  • 12
  • 102
  • 104