Home > front end >  Display showDialog when a variable value is changed
Display showDialog when a variable value is changed

Time:02-20

I have a boolean variable hasConnection that keeps checking if a user is connected to the internet, I'd like to display showDialog , once the variable is false!

I'm getting this error :

FlutterError (setState() or markNeedsBuild() called during build.

i created this function to display the dialog :

  Future connectivity(BuildContext context) async {
    return showDialog<bool>(
        context: context,
        builder: (context) => AlertDialog(
                backgroundColor: Colors.black,
                title: new Text("Whoa!!",
                    textAlign: TextAlign.center,
                    style: TextStyle(color: Colors.white.withOpacity(0.6))),
                content: new Text("Please Connect To Internet",
                    textAlign: TextAlign.center,
                    style: TextStyle(fontSize: 15, color: Colors.white)),
                actions: [
                  TextButton(
                    child: Text("Ok"),
                    onPressed: () {
                      Navigator.pop(context);
                    },
                  ),
                ]));
  }
 

then inside my main widget I call that , but I'm getting an error !

  @override
  Widget build(BuildContext context) {
    if(hasConnection == false){
    connectivity(context);
    }

CodePudding user response:

You can do so by wrapping you function in a post frame callback

@override
Widget build(BuildContext context) {
  if(hasConnection == false){
    WidgetsBinding.instance?.addPostFrameCallback((_){
      connectivity(context);
    });
  }
}
  • Related