Home > Net >  read state from StatefulWidget
read state from StatefulWidget

Time:04-14

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

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();

CodePudding user response:

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

  • Related