![](/img/trans.png)
[英]Flutter pass data from one class to another(statefull widget)
[英]Pass data from one widget to another in a Form in Flutter
https://flutter.dev/docs/cookbook/forms/validation
在这里,他们在Form
中使用了两个小部件: TextFormWidget
和ElevatedButton
。 他们说TextFormWidget
的验证器接收用户输入的值。
我想在用户按下ElevatedButton
时打印该值。
如何让ElevatedButton
从TextFormWidget
接收该值?
@override
Widget build(BuildContext context)
{
return Form(
key: _formKey,
child: Column(
children: <Widget>[
TextFormField(
// The validator receives the text that the user has entered.
validator: (value)
{
if (value == null || value.isEmpty)
{
return 'Please enter some text';
}
return null;
},
),
ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
....
}
},
child: Text('Submit'),
),
],
),
);
}
设置TextFormField
的controller
属性并从那里读取数据。
按如下方式使用它:
var controller = TextEditingController();
@override
Widget build(BuildContext context)
{
return Form(
key: GlobalKey(),
child: Column(
children: <Widget>[
TextFormField(
controller: controller,
// The validator receives the text that the user has entered.
validator: (value)
{
if (value == null || value.isEmpty)
{
return 'Please enter some text';
}
return null;
},
),
ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
String currentText = controller.text;
// ...do something with currentText
}
},
child: Text('Submit'),
),
],
),
);
}
您可以使用TextEditingController
并将其传递给TextFormField
的controller
参数。 您可以从controller
获取使用给出的value
或输入。
例子
// Controller
final TextEditingController _controller = TextEditingController();
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Column(
children: <Widget>[
TextFormField(
// Add the controller to the TextFormField
controller: _controller,
// The validator receives the text that the user has entered.
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter some text';
}
return null;
},
),
ElevatedButton(
onPressed: () {
// if (_formKey.currentState!.validate()) {
// ....
// }
// This gives the value
final String value = _controller.text;
print(value);
},
child: Text('Submit'),
),
],
),
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.