Amani
Amani

Reputation: 18123

How can I use Listview builder inside a Flutter Form widget?

I have a Form widget that has about 30 TextFormField widgets. This is intended to be used as a web app. I'm trying to do the best to have the maximum possible speed. The TextFormField widgets have different text input formatters, controllers and some are required and some are optional. How can I use the ListView.builder inside the Form so the the TextFormField widgets are loaded as needed?

Upvotes: 1

Views: 3163

Answers (1)

Marco Domingos
Marco Domingos

Reputation: 715

If I could understand, you need to make Form with ListView.builder that will build 30 TextFormField, if that right, you only need to put the ListView.builder inside The Form like this:

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final _formKey = GlobalKey<FormState>();
  List validators = [
    (value) {
      if (value == null || value.isEmpty) {
        return 'Please enter the number';
      }
      return null;
    },
    (value) {
      if (value == null || value.isEmpty) {
        return 'Please enter the email';
      }
      return null;
    },
    (value) {
      if (value == null || value.isEmpty) {
        return 'Please enter the password';
      }
      return null;
    },
  ];
  List formatters = [
    FilteringTextInputFormatter.digitsOnly,
    FilteringTextInputFormatter.allow(RegExp('[a-zA-Z]')),
    FilteringTextInputFormatter.deny(RegExp(r'[/\\]'))
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Form(
        key: _formKey,
        child: ListView.builder(
          itemCount: 3,
          itemBuilder: (context, index) {
            return TextFormField(
              validator: validators[index],
              inputFormatters: [formatters[index]],
            );
          },
        ),
      ),
      floatingActionButton: FloatingActionButton(
        child: Text('Click'),
        onPressed: () {
          if (_formKey.currentState.validate()) {
            // If the form is valid, display a snackbar. In the real world,
            // you'd often call a server or save the information in a database.
            ScaffoldMessenger.of(context)
                .showSnackBar(SnackBar(content: Text('Processing Data')));
          }
        },
      ),
    );
  }
}

This will check if all the 30 TextFormField are not empty.

Upvotes: 4

Related Questions