1

I need to show the snackbar on launch of app in init in order to check the connectivity of internet. My code in custom class is:

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

class Network{
   checkNetwork() async {
        var connectivityResult = await (Connectivity().checkConnectivity());
        if (connectivityResult == ConnectivityResult.none) {
          return 
          //print("no internet");
          SnackBar(
              content:  Text("Check internet Connectivity"),
              action: SnackBarAction(
                label: "Settings",
                onPressed: (){
                  SystemSetting.goto(SettingTarget.NOTIFICATION);
                },
              ),
            ); 
            //scaffoldKey.currentState.showSnackBar(snackbar);
            }
} 
}

and accessing the method as follows:

 @override
  void initState() {
    super.initState();
    //Network.checkNetwork();

    Network objnetwork = Network();
    objnetwork.checkNetwork();
 }

I have returned a print statement which was executed right, but when return a widget like snackbar or dialog box, it doesnot appear nor show any exception.

Jabir Ishaq
  • 177
  • 1
  • 1
  • 16

1 Answers1

1

The answer was found to be using flutter_after_layout which executes a function after build function finishes so the SnackBar can be displayed. More explanation is found in this relevant answer about how to run method when build completes .

Mazin Ibrahim
  • 7,433
  • 2
  • 33
  • 40
  • https://stackoverflow.com/questions/52164369/show-alert-dialog-on-app-main-screen-load-automatically-in-flutter found this as alternate, but i need to show this on each page of app through calling a separate class, coz it is bad practise to repeat code on each page – Jabir Ishaq Mar 04 '19 at 05:58
  • congratulations ! – Mazin Ibrahim Mar 04 '19 at 07:16