Ad

Display ShowDialog When A Variable Value Is Changed

- 1 answer

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);
    }
Ad

Answer

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);
    });
  }
}
Ad
source: stackoverflow.com
Ad