Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

read state from StatefulWidget

I have a reference to a StatefulWidget and I would like to read a a variable in the state class(totally independent of build state) – how would you do that?

One way would be to keep a reference to the state when creating the state, is that the way to go?

Note: It will then complains either about const of late final

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class SomeStateFullWidget extends StatefulWidget {
  _SomeStateFullWidget state;

  const RadialMenu({Key? key});

  @override
  createState(){
    state = _SomeStateFullWidget();
    return state;} // Error: Don't put any logic in createState

  readThisVariableMethod(){
    return state.readThisVariable;
  }

}

class _SomeStateFullWidget extends State<SomeStateFullWidget >{
  bool readThisVariable = false;
}

I then want to read the state variable readThisVariable:

   SomeStateFullWidget someStateFullWidget = SomeStateFullWidget();
   bool bVar = someStateFullWidget.readThisVariableMethod();

>Solution :

You can achieve your goal by using GloabalKey, this sample might help you:

 GlobalKey<SomeStateFullWidgetState > myKey = GlobalKey();

 myKey.currentState!.readThisVariable; //here

where here you should change the state of your widget to public state instead of private (remove the _). SomeStateFullWidgetState in the sample above represent the public state of your widget, so it’s the replacement name of _SomeStateFullWidget

other option would be to use other state management methods like Provider, this link might help you:

https://docs.flutter.dev/development/data-and-backend/state-mgmt/options

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading