读取输入框的内容
获取文本框的输入值
实用教程chevron_right表单交互 (Forms)chevron_right获取文本框的输入值
这个章节讲解的是如何获取文本框的输入值。
- 创建一个
TextEditingController - 把
TextEditingController应用到TextField上 - 展示文本框当前值
1. 创建 TextEditingController
为了获取文本框输入值,需要创建一个 TextEditingController。在后续步骤中,这个 TextEditingController 将会被应用到 TextField 上。
TextEditingController 被应用于 TextField 或者 TextFormField 后,就可以使用它来获取文本框输入值。
error重点提醒
当不再使用 TextEditingController 时,请调用 dispose 销毁它以确保相关的资源得到释放。
dart
// Define a custom Form widget.
class MyCustomForm extends StatefulWidget {
const MyCustomForm({super.key});
@override
State<MyCustomForm> createState() => _MyCustomFormState();
}
// Define a corresponding State class.
// This class holds the data related to the Form.
class _MyCustomFormState extends State<MyCustomForm> {
// Create a text controller and use it to retrieve the current value
// of the TextField.
final myController = TextEditingController();
@override
void dispose() {
// Clean up the controller when the widget is disposed.
myController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
// Fill this out in the next step.
}
}
content_copy
2. 把 TextEditingController 应用到 TextField 上
创建完 TextEditingController,就可以使用 controller 属性完成 text field 绑定。
dart
return TextField(
controller: myController,
);
content_copy
3. 展示文本框当前值
在 TextEditingController 作用于文本框后,就可以开始取值了。通过 TextEditingController 提供的 text() 方法,就能够获取到文本框输入值了。
在下面的示例中,用户点击浮层按钮,将会触发弹出一个对话框,对话框获取并显示文本框的当前值。
dart
FloatingActionButton(
// When the user presses the button, show an alert dialog containing
// the text that the user has entered into the text field.
onPressed: () {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
// Retrieve the text that the user has entered by using the
// TextEditingController.
content: Text(myController.text),
);
},
);
},
tooltip: 'Show me the value!',
child: const Icon(Icons.text_fields),
),
content_copy
浙公网安备 33010602011771号