2
bool connectionStatus = true;
Future check() async {
  try {
    final result = await InternetAddress.lookup('google.com');
    if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
      connectionStatus = true;
    }
  } on SocketException catch (_) {
    connectionStatus = false;
  }
}

class _BackButtonState extends State<BackButton> {
  DateTime backbuttonpressedTime;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PreferredSize(
        preferredSize: Size(double.infinity, 0),
        child: AppBar(
          title: Text(""),
          backgroundColor: Colors.deepPurple,
        ),
      ),
      body: FutureBuilder(
          future: check(), // a previously-obtained Future or null
          builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
            if (connectionStatus == true) {
              return WillPopScope(
                onWillPop: onWillPop,
                child: WebviewScaffold(
                  url: 'https://www.theonlineindia.co.in',
                  hidden: true,
                  initialChild: Container(
                    child: const Center(
                      child: CircularProgressIndicator(
                          valueColor:
                              AlwaysStoppedAnimation<Color>(Colors.deepPurple)),
                    ),
                  ),
                ),
              );
            } else {
              return Center(
                  child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Container(
                    child: Text('No internet connection !!!',
                        style: TextStyle(
                          // your text
                          fontFamily: 'Aleo',
                          fontStyle: FontStyle.normal,
                          fontWeight: FontWeight.bold,
                          fontSize: 25.0,
                        )),
                  ),
                  /* RaisedButton(
                    onPressed: () {
                      setState(() {});
                    },
                    color: Color(0xFF673AB7),
                    textColor: Colors.white,
                    child: Text('Refresh'),
                  ), */
                  // your button beneath text
                ],
              ));
            }
          }),
    );
  }

  Future<bool> onWillPop() async {
    DateTime currentTime = DateTime.now();

    //ifbackbuttonhasnotbeenpreedOrToasthasbeenclosed
    //Statement 1 Or statement2
    bool backButton = backbuttonpressedTime == null ||
        currentTime.difference(backbuttonpressedTime) > Duration(seconds: 2);
    if (backButton) {
      backbuttonpressedTime = currentTime;
      Fluttertoast.showToast(
          msg: "Double tap to exit the app",
          backgroundColor: Colors.deepPurple,
          textColor: Colors.white);
      return false;
    }
    exit(0);
    return true;
  }
}

In the above code I am able to display the message "No internet" only at the time of launching the app. I want to display the same message after app is launched and if the internet connection is lost while visiting the web pages within the webview.

I would prefer to achieve the above via code itself not looking for any plugins. Plugins will be secondary option.

*

atif shaikh
  • 127
  • 3
  • 10

1 Answers1

4

Option 1

Define a timer that periodically check the connection

  const period= const Duration(seconds:5);
  new Timer.periodic(period, (Timer t) => check());

Option 2

Use the connectivity plugin and define a stream in your app main widget

    StreamSubscription<ConnectivityResult> networkSubscription;
    @override
      void initState() {
        super.initState();
        networkSubscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
          check();
        });
        checkNetwork(); // Needed for the check on start
      } 
Tom Rivoire
  • 627
  • 5
  • 6
  • Thanks a lot it worked for me. Timer.periodic(new Duration(seconds: 10), (time) async { final flutterWebViewPlugin = FlutterWebviewPlugin(); if (connectionStatus == false) flutterWebViewPlugin.reload(); try { final result = await InternetAddress.lookup('google.com'); if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) { connectionStatus = true; } } on SocketException catch (_) { connectionStatus = false; Fluttertoast.showToast( msg: "No internet connection", ); } }); – atif shaikh Jul 26 '20 at 19:43
  • 1
    @atifshaikh You're welcome, glad it helps ! Could you mark the answer as accepted ? if it completely answer you question of course – Tom Rivoire Jul 27 '20 at 06:49
  • I cant find the option to do that. – atif shaikh Jul 27 '20 at 18:54
  • 1
    @atifshaikh https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – Tom Rivoire Jul 28 '20 at 07:08