Reputation: 8666
I have a screen with a list of textfields and a dropdown option. I declared a variable in the StatefulWidget class and use it in the class through widget.variableName, however after entering some values on the textfields, I noticed the widgets get updated and my variable loses its value and I am left with a null variable. I have tried initializing it in initState() but it still loses it's value.
Example:
class Screen extends StatefulWidget{
var variable;
@override
_ScreenState createState(){
variable = "dummyText";
return _ScreenState();
}
}
class _ScreenState extends State<Screen>{
@override
Widget build(BuildContext context) {
return Scaffold(
body: _layout(),
);
}
_layout(){
print(" value of variable: ${widget.variable}");
//imagine lots of textfields here in a listview
}
}
After entering text on some textfields, the variable
loses it's value and it resets to null. How can i maintain it's value or where should I even declare it to make it not lose it's value.
Upvotes: 3
Views: 4143
Reputation: 40433
Any state (i.e. variables) should be held in the class that inherits State
. The class that inherits StatefulWidget should actually only have final
variables - if you look at the Dart Analysis it should actually show an error as it inherits an @immutable
class.
It's hard to tell without a bit more context about what you're doing, but generally if a value is passed in to the object you want to store it as a final variable in the class that inherits StatefulWidget
, and store the actual value in a State wherever the change is actually affected.
Flutter is optimized for building objects, so don't worry about the performance implications of instantiating objects many times.
Note that if your class is the right place for the variable to be held, but you also want an initial value, you could pass in the initial value to the StatefulWidget then retrieve the value into the State in the initState
call.
I'd recommend reading the part of the flutter tutorial about stateless and stateful widgets to get a deeper understanding of how they work.
Upvotes: 5
Reputation: 277037
You can't set mutable variable inside the StatefulWidget
subclass. All fields of StatefulWidget
must be final or const.
Instead, move that variable inside the State
subclass.
class Screen extends StatefulWidget {
_ScreenState createState() => _ScreenState();
}
class _ScreenState extends State<Screen> {
String variable;
@override
void initState() {
variable = "dummyText";
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: _layout(),
);
}
_layout() {
print(" value of variable: $variable");
//imagine lots of textfields here in a listview
}
}
Upvotes: 9