我正在使用 flutter 构建一个表单,它具有一组动态输入。因此,我永远无法假设表单将有多少个文本字段,因此我无法手动为每个字段分配一个键以便稍后从其控制器检索数据。
如果我实例化一个Form,它保存了一些内容,例如TextFormField,当按下按钮时,如何简单地提取整个表单的键值数组?
Form(
key: _formKey,
child: Column(
children: [
TextFormField(),
TextFormField(),
TextFormField(),
]
)
)
Run Code Online (Sandbox Code Playgroud)
动态生成 TextFields 及其控制器
Map<int,TextEditingController> controllers = {};
Run Code Online (Sandbox Code Playgroud)
Form(
key: _formKey,
child: Column(children: [
...List.generate(length, (index) {
var controller = controllers.putIfAbsent(
index, () => TextEditingController());
return TextFormField(
controller: controller,
);
})
]));
Run Code Online (Sandbox Code Playgroud)
您可以通过索引访问给定地图中的所有控制器
Validator 函数接收当前 TextField 的值,因此使用该值来验证 TextField 并将该值添加到 List 类型变量中。
在 Button onPressed 上调用 _formKey.currentState.validate():所以最后您将获得 List 变量中所有 TextField 的值。
请参阅下面的代码或使用此 DartPad AllTextFieldValues作为交互式示例。
import 'package:flutter/material.dart';
final Color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
debugShowCheckedModeBanner: false,
home: MyWidget());
}
}
class MyWidget extends StatelessWidget {
final List<String> textFieldsValue = [];
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Form(
key: _formKey,
child: Column(children: [
TextFormField(
validator: (value) {
textFieldsValue.add(value);
return ;
},
),
TextFormField(
validator: (value) {
textFieldsValue.add(value);
return ;
},
),
TextFormField(
validator: (value) {
textFieldsValue.add(value);
///it will be more complex because you want dynamic textfields
},
),
])),
),
floatingActionButton: FloatingActionButton(onPressed: () {
_formKey.currentState.validate();
print(textFieldsValue);
}));
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13678 次 |
| 最近记录: |