Home > other >  Flutter access variables in state
Flutter access variables in state

Time:09-11

I want to get variables of a StatefulWidget from within the state. Is there a easy way to just get the Stateobject like username.state.value.

EDIT: To clarify I want to access a variable that's defined in the state from the parent of the widget(not the state). The variable is gonna change, but I don't want to update it constantly in the parent. I want to get the variable when I press a button. I have an example below how I can access variables normally, but I want to know if there is a way to access the state and its variables.

class MyTextField extends StatefulWidget {
  final String? validator;

  const MyTextField(
      {super.key,
      this.validator});

  @override
  State<MyTextField> createState() => _MyTextFieldState();
}

class _MyTextFieldState extends State<MyTextField> {
  String value = "";
MyTextField username = MyTextField(validator: null)
String? validator = username.validator;
String value = ?

CodePudding user response:

One you can do this is you set a function and when ever these value change, call that function:

class MyTextField extends StatefulWidget {
  final String? validator;
  final Function(String) onValueChange;

  const MyTextField(
      {super.key,
      this.validator, this.onValueChange});

  @override
  State<MyTextField> createState() => _MyTextFieldState();
}

Then where ever you define MyTextField pass this function and listen to that value:

return MyTextField(
   validator: null,
   onValueChange:(value){
     setState((){
       print('value =$value');
     });
   }
);

or in your case use it like this:

    String _value = '';
    MyTextField username = MyTextField(validator: null, onValueChange:(value){
             setState((){
               _value = value;
             });
           })

CodePudding user response:

Edit-:

You can update states with two ways

  1. call-backs
  2. state management

Call Backs

They are very useful but it will get messy when your app grows. You can start by looking into VoidCallBack you can create similar function signature with different parameters using typedef keyword.

State Management

Obviously very useful but more importantly it will keep your business logic out of your UI logic. In real world apps, you will use this and callback use case based.

So I assume you are going to use state management then start by looking into ChangeNotifier and InheritedWidget, these are flutter inbuilt state management systems. But they can be little hard to understand at first for new commers so start by using provider package from pub.dev. Its very easy to use and for 90% of the time you won't need anything else for the state management.

  • Related