Looking up a deactivated widget's ancestor is unsafe
Declare a global variable
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
then register the key on your widget build's scaffold eg
@override Widget build(BuildContext context) { return Scaffold( key: _scaffoldKey, ...
then on the dialog
show(BuildContext context){var dialog = Dialog( child: Container( margin: EdgeInsets.all(8.0), child: Form( child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ TextFormField( decoration: InputDecoration( labelText: "Insira o número de telefone", border: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(2.0)))), ), Row( mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[ FlatButton( onPressed: () { Navigator.of(context).pop(); }, child: Text("Cancelar")), FlatButton( onPressed: () { Navigator.of(context).pop(); }, child: Text("Aceitar")) ], ) ], ), ), ),);
Pass that scaffold context to the showDialog method
showDialog(context: _scaffoldKey.currentContext ,builder: (context){ return dialog; });}
Try This
Give different context name for dialog
showDialog(context: context,builder: (dialogContex){ return Dialog( child: Container( margin: EdgeInsets.all(8.0), child: Form( child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ TextFormField( decoration: InputDecoration( labelText: "Insira o número de telefone", border: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(2.0)))), ), Row( mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[ FlatButton( onPressed: () { Navigator.of(dialogContex).pop(); }, child: Text("Cancelar")), FlatButton( onPressed: () { Navigator.of(context).pop(); }, child: Text("Aceitar")) ], ) ], ), ), ), ); });
I got the same error when attempting to open a dialog and I found a solution here: github flutter issues. Specifically, I followed the poster's recommendation, which was to create a GlobalKey
and associate it with the Scaffold
widget, and use the context from that key when creating the dialog. In my case, I have a globally accessible object which holds the GlobalKey
:
MyGlobals myGlobals = MyGlobals();class MyGlobals { GlobalKey _scaffoldKey; MyGlobals() { _scaffoldKey = GlobalKey(); } GlobalKey get scaffoldKey => _scaffoldKey;}
In the Scaffold
widget constructor call:
Scaffold( appBar: ..., body: ..., drawer: ..., key: myGlobals.scaffoldKey,)
And in the showDialog
call:
showDialog<String>( barrierDismissible: ..., builder: ..., context: myGlobals.scaffoldKey.currentContext,);