Flutter GlobalKey current state is null

If anyone having the same issue. I haven't found a solution to this or at least an explanation to why this happens. However, I switched from using my own approach to using an Inherited Widget to transport my form data while keeping the validation inside each separate form (I was validation inside the wrapper class Forms, now I validate each form in its own class).


You need to pass the key into the scaffold widget, then the context and state will be set.

class _MyHomePageState extends State<MyHomePage> {
  GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey(); //so we can call snackbar from anywhere

...

Widget build(BuildContext context) {
    return Scaffold(
        key: _scaffoldKey, //set state and context

...

//define method to call
void showInSnackBar(String value) {
    _scaffoldKey.currentState.showSnackBar(new SnackBar(
        content: new Text(value)
    ));
  }

...

//Then you can call it
showInSnackBar("Proximity Alert, please distance yourself from the person or dangerous object close to you! This incident has been logged.");

Tags:

State

Flutter