Reputation: 105
I make a statefullwidget with final variable, like password. But When I need to get data from extend statefullwidget to setstate it show error
class Inputtextfield extends StatefulWidget {
const Inputtextfield({
Key key, this.label, this.onChange, this.password = false,
}) : super(key: key);
final String label;
final Function onChange;
final bool password;
@override
_InputtextfieldState createState() => _InputtextfieldState();
}
class _InputtextfieldState extends State<Inputtextfield> {
void _togglevisibility(){
setState(() {
widget.password = !widget.password;
});
}
i need to change it for Toggle, in setState Error say password can't be setter,cause it final
, I try to fix error with Ctrl + . -> Make 'password' Not Final
and error move to extend statefullWidget
Upvotes: 1
Views: 61
Reputation: 11988
final
keyword prevents you to re-assign its value. It's better to keep the widget constructor variables immutable, and create a mutable variable into the State
itself.
Therefore, to change your variable, you need to do as follows:
class _InputtextfieldState extends State<Inputtextfield> {
bool _password;
@override
void initState() {
super.initState();
_password = widget.password;
}
void _togglevisibility(){
setState(() {
// now, you can modify it
_password = !_password;
});
}
}
You can read more on this discussion: https://groups.google.com/g/flutter-dev/c/zRnFQU3iZZs/m/JX9ei27CBwAJ?pli=1
Upvotes: 1
Reputation: 96
Upvotes: 0
Reputation: 1232
It's simple. Final
variables can only be set ONCE
. Once you set them they cannot be changed.
final bool password = true; // this value cannot be changed again
In your case, if you want to update the value of password
, you have to make it to be Not Final
by removing the final
keyword ie:
bool password = false; // this can now be changed later using `setState()`
Upvotes: 0