![](/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.