I have, which is probably a simple error. I’m using a TextField and created a custom widget.
class NoteField extends StatefulWidget {
NoteField({Key? key, required this.n}) : super(key: key);
String n;
@override
State<NoteField> createState() => _NoteFieldState();
}
class _NoteFieldState extends State<NoteField> {
@override
Widget build(BuildContext context) {
return TextField(
maxLength: 40,
onChanged: (String value) {
widget.n = value;
print(widget.n);
},
decoration: InputDecoration(
border: OutlineInputBorder(
borderSide: BorderSide(
color: Theme.of(context).primaryColor,
)),
hintText: 'Enter a label for your visit',
),
);
}
So when I use this widget, I’ve created a String _note and I pass this to the widget.
NoteField(n: _note),
However, I’m getting blank. When I type I can see n
updating from the print statement but when I try and print _note when I press a button, it’s showing as blank.
3
Answers
You can either use a TextEditingController or in your onChanged you need to wrap the assignment in a
You should use a
TextEditingController
to keep the state of your values and retrieve it in parents widget.There is multiple solution to manage the state, one of them using setState and keys is the following:
You assign a GlobalKey to retrieve your child stateful widget. You create a
TextEditingController
that manages the initial value and that will hold your textfield data.Finally you use the key to access the state of your child widget.
EDIT
You can always pass a callback to your widget to update the value you are passing to the TextField widget:
Instead of passing a string pass the TextEditingController to the class.
Use
From the other classs. Here controller is the TextEditingController that you passed to the NoteField class