I have problems following step by step what happens when onChanged
is triggered on my TextField
. Especially, I have a problem understanding where and why the variable value gets its actual value in the following example.
Example:
class felder extends StatefulWidget {
felder({super.key});
String textFieldName = "";
@override
State<felder> createState() => _felderState();
}
class _felderState extends State<felder> {
@override
Widget build(BuildContext context) {
return Column(
children: [
TextField(
obscureText: false,
decoration: const InputDecoration(
border: OutlineInputBorder(), labelText: 'Name'),
onChanged: (value) => widget.textFieldName = value,
)
],
);
}
}
How I always imagined it: I think flutter passes a function
in the background, which has a parameter value, that has the content of the TextField
.
3
Answers
TextField
is a widget that has its own state.TextField
changes.
TextField
.callback.
onChanged: (value){ print(value); }
, we canget the value from that callback and use it as per our needs.
From
TextField
source code,The text field calls the [onChanged] callback whenever the user changes the text in the field. If the user indicates that they are done typing in the field (e.g., by pressing a button on the soft keyboard), the text field calls the [onSubmitted] callback.
To get the value from a
TextField
, you can also useTexteditingController
.First declare
TextEditingController controller = TextEditingController();
.Then inside your
TextField
, add the controller like thisThen to get the value from controller, you can use
controller.value.text
.What is a callback?
From GeeksForGeeks:
Creating a callback
To create your own callback, you can use
ValueChanged
.Code example:
Let’s create our own button, that when the
onChanged
is called, it will give us a newvalue
:Usage:
Complete example
You can run/paste this example in your editor, and take a look:
See also
How to pass callback in Flutter
What’s in onChanged Docs ?
This callback doesn’t run when the
TextField's text
is changed programmatically, via theTextField's controller
. Typically it isn’t necessary to be notified of such changes, since they’re initiated by the app itself.What is Callback ?
If we go by definition, the
Callback
is afunction
or amethod
which we pass as anargument
into anotherfunction
ormethod
and can perform an action when we require it.For Example, if you are working in any app and if you want any change in any value then what would you do?
Here you are in a dilemma that what you want to change either
state()
or a simplevalue/values
. If you need to change states then you have various state-changing techniques but if you want to change simple values then you will useCallback
.Refer this article to understand the callback on event of textChange this will surely make you understand the core behind the mechanism