Flutter: how to create a non-final property for a StatefulWidget?
You can have variables in the State
object of the StatefulWidget
, not in the StatefulWidget
itself.
If you need to pass the value from another widget, you can pass it and reassign it to a State
variable in the initState
function.
Example:
class TestButton extends StatefulWidget { TestButton({this.passedcolor}); final Color passedColor; @override _TestButtonState createState() => _TestButtonState();}class _TestButtonState extends State<TestButton> { Color color; @override initState(){ color = widget.passedColor; super.initState() } @override Widget build(BuildContext context) { return RaisedButton( onPressed: () { setState(() { color = color == Colors.red ? Colors.blue : Colors.red; }); }, child: Icon( Icons.add, size: 80, ), color: color, ); }}
and then you can update it using setState
to any color you wish.
As to why the value passed in the constructor has to be final
or why you can't change it is because the StatefulWidget
itself is immutable and holds immutable data, but it also holds a mutable State
object which is a store for all the state aka mutable data
the widget requires.
Quoting from Flutter docs:
StatefulWidget instances themselves are immutable and store their mutable state either in separate State objects that are created by the createState method, or in objects to which that State subscribes, for example Stream or ChangeNotifier objects, to which references are stored in final fields on the StatefulWidget itself.
You can read more on it here: StatefulWidget class documentation on Flutter website