I am building a form using flutter, that has a dynamic set of input. Therefore, I can never assume how many text fields the form will have, and so I cannot manually assign a key to each field to later retrieve data from its controller.
If I instanciate a Form, that holds some TextFormField how can I simply extract an array of key values for the whole form, when pressing a button for example?
Form(
key: _formKey,
child: Column(
children: [
TextFormField(),
TextFormField(),
TextFormField(),
]
)
)
to generate TextFields and their controller on the fly
Map<int,TextEditingController> controllers = {};
Form(
key: _formKey,
child: Column(children: [
...List.generate(length, (index) {
var controller = controllers.putIfAbsent(
index, () => TextEditingController());
return TextFormField(
controller: controller,
);
})
]));
you can access all the controllers in the given map with their index
The Validator function receives the current TextField's value, so use this value for validate the TextField and add this value to the List type variable.
Call _formKey.currentState.validate() on Button onPressed: So at the end you will get all the TextField's value in List variable.
See the below code or play with this DartPad AllTextFieldValues for interactive example.
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);
}));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With