| layout | page |
|---|---|
| title | Handling Text Input |
| sidebar | home_sidebar |
| permalink | /text-input/ |
- TOC Placeholder {:toc}
This page describes how to set up basic text input for Flutter applications.
The
Input
widget under
Material
satisfies most text input use cases, and implements material design's style. If
you want an input widget that does not use material design, see
EditableText
Assuming that the input is already in focus, the basic data flow for retrieving user input is:
- User taps a character in the keyboard.
- The
onChangedcallback is called with the currentvalueof the widget. - Perform any necessary logic/validation on the current input value.
- Update the state of the
Inputwidget accordingly throughsetState().
For most cases, we recommend that you use the
Input
class within a
StatefulWidget
so you can save and operate on the current value of the input.
To learn more about
StatefulWidget
and managing state in Flutter, you can look at this helpful example of
managing widget state.
This example is a
StatefulWidget
that mirrors the text inside an
Input.
/// [StatefulWidget] that displays what is being entered in the input
class MyInput extends StatefulWidget {
MyInput({Key key}) : super(key: key);
@override
_MyInputState createState() => new _MyInputState();
}
/// State that corresponds to [MyInput]
class _MyInputState extends State<MyInput> {
/// Track the current input state
InputValue _currentInput;
@override
void initState() {
super.initState();
// The empty constructor for InputValue
// will initial an InputValue with an empty string
_currentInput = const InputValue();
}
/// Handle callbacks from Input, when the text is changed
void _handleInputChange(InputValue input) {
setState(() {
_currentInput = input;
});
}
@override
Widget build(BuildContext context) {
return new Column(
children: <Widget>[
new Text(_currentInput.text), // Display the text of the current input
new Input(
onChanged: _handleInputChange,
value: _currentInput,
),
],
);
}
}