In flutter while dealing with stateful widgets, we can declare variables at 2 places inside the state class shown using variable_1
and variable_2
.
class StatefulWidget_STATE_class extents State<className>{
final int variable_1 = 2;
@override
Widget build(BuildContext context){
final int variable_2 = 2;
}
}
What is the difference between the two declarations and when should one be used over the other?
CodePudding user response:
The variable in your state is saved in your state. The variable in your function is local to your function.
That means the variable in your function will be destroyed when your function is finished and will be recreated and reinitialized every time the function is called.
Therefor, if you want this variable to hold your state between function calls, it need to be outside the function. In this case, in your state class.
This isn't about efficiency. If you want something that is only important to this one run of the build function, make it a local variable. If you want something that keeps it's value even when build is called multiple times (for example with every state change) you need to put it into your state class instead.
Generally speaking, confine your variable to the least amount of visibility that still fullfils it's purpose and then let the compiler worry about efficiency. The lower the visibility of the variable, the easier it is for the compiler to optimize it.