How to store the value received through a method in another variable instance?

Issue

How to store the value received through a method in another variable instance?

I want to store the value passed to the Statefulwidget in an instance which I am not able to do. This is how I pass the value to the Statefulwidget’s method.

_MyHomePageState().getprints(state1);

But not able to store the data in an instance in the StatefulWidget, Please check the comments to see what is working what is not working

var state11;
getprints(var state1){
 
   print("hello");
   print(state1); //this works
   state11 = state1; // this does not works
}

How should I save it in an instance in flutter?

Solution

This is more of a ‘dart’ question than a ‘flutter’ one. So I just tested out the code in dartpad.dev

The thing is, it does get stored in state1. But the thing is, you can’t refer to it with another instance cause then that instance will be a newly created instance and will have a different value for state1. The solution?
You can make state11 a static variable and instead of calling the instance, you call it with the class directly. Like this:

void main() {
  print(MyHomePageState.state11);     //Line 1
  MyHomePageState().getprints('Some state');
  print(MyHomePageState.state11);     //Line 4
}

class MyHomePageState {
  static var state11;
  getprints(var state1) {
    print("hello");                   //Line 2
    print(state1);                    //Line 3
    state11 = state1; 
  }
}

with output as:

null
hello
Some state
Some state

This ensures that change in value to state1 is reflected across all instances of the class.

Or…
You can store the instance in a variable and then call the variable of that instance.

void main() {
  var homePage = MyHomePageState();
  homePage.getprints('Some state');
  print(homePage.state11);            //Line 3
}

class MyHomePageState {
  var state11;
  getprints(var state1) {
    print("hello");                   //Line 1
    print(state1);                    //Line 2
    state11 = state1; 
  }
}

with output as:

hello
Some state
Some state

But since you’re using this for a HomePage widget, I’d recommend using the first method.

Answered By – rkdupr0n

Answer Checked By – Dawn Plyler (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *