I am new in flutter and i have some codes to build textfield. i want to make an initial value in textfield but this is from input in another class.
class TextFieldEdit extends StatefulWidget {
TextFieldEdit({
Key? key,
required this.title,
required this.hintTxt,
required this.controller,
required this.defaultTxt,
}) : super(key: key);
final String title, hintTxt;
final controller;
final defaultTxt;
@override
State<TextFieldEdit> createState() => _TextFieldEditState();
}
class _TextFieldEditState extends State<TextFieldEdit> {
TextEditingController _controller = TextEditingController();
@override
void initState() {
super.initState();
_controller.text = defaultTxt;
}
@override
Widget build(BuildContext context) {
return ...
}
in _TextFieldEditState
class at the _controller.text i want to get value from defaultTxt
in TextFieldEdit
class. But how can i send it to _TextFieldEditState
class?
the error message is : Undefined name 'defaultTxt'. Try correcting the name to one that is defined, or defining the name.
CodePudding user response:
Use widget.
to access to the variable in constructor:
@override
void initState() {
super.initState();
_controller.text = widget.defaultTxt;
}
CodePudding user response:
To access the widget variable follow widget.variableName
You can do
late final TextEditingController _controller =
TextEditingController.fromValue(
TextEditingValue(text: widget.defaultTxt));
Or use initState to assign the _controller
.