Flutter extract all key-values from Form

Viewed 9771

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(),
    ]
  )
)
2 Answers

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

You can achieve this by adding validator to All TextField.

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);
        }));
  }
}
Related