我正在使用flutter构建一个表单,它有一组动态的输入。因此,我永远不能假设表单将有多少个文本字段,因此我不能手动为每个字段分配一个键,以便以后从其控制器检索数据。
如果我实例化一个包含一些TextFormField的Form,我如何才能简单地提取整个表单的键值数组,例如,当按下按钮时?
Form(
key: _formKey,
child: Column(
children: [
TextFormField(),
TextFormField(),
TextFormField(),
]
)
)发布于 2020-07-22 15:47:51
动态生成TextFields及其控制器
Map<int,TextEditingController> controllers = {}; Form(
key: _formKey,
child: Column(children: [
...List.generate(length, (index) {
var controller = controllers.putIfAbsent(
index, () => TextEditingController());
return TextFormField(
controller: controller,
);
})
]));您可以通过索引访问给定映射中的所有控制器
发布于 2020-07-22 16:17:45
您可以通过向所有TextField添加验证器来实现这一点。
Validator函数接收当前TextField值,因此使用该值验证TextField并将该值添加到列表类型变量。
在按钮onPressed上调用_formKey.currentState.validate():这样在最后,您将获得列表变量中的所有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);
}));
}
}https://stackoverflow.com/questions/63025276
复制相似问题