skip to Main Content

Given the following page with 3 tabs that all contain multiple textfields, is using the riverpod library the best/easiest way to both set and collect values from each tab’s textformfield widgets?

enter image description here

The "Save" button should collect all the values. likewise, when creating the form, a data model is passed in containing all the info, and should be distributed among the tabs. I’ve been reading that there seem to be multiple ways to do this, such as providers, textcontrollers, etc, but i just found the riverpod library and it seems the easiest option.

Thanks!

2

Answers


  1. You can simplify handling multiple TextFormFields by using the flutter_form_builder package. It makes form handling easier by providing built-in widgets for validation and input collection, without needing to manually manage each field.

    import 'package:flutter/material.dart';
    import 'package:flutter_form_builder/flutter_form_builder.dart';
    
    class MyFormPage extends StatelessWidget {
    final _formKey = GlobalKey<FormBuilderState>();
    
    @override
    Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Form Example')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: FormBuilder(
          key: _formKey,
          child: Column(
            children: [
              FormBuilderTextField(
                name: 'email',
                decoration: InputDecoration(labelText: 'Email'),
              ),
              FormBuilderTextField(
                name: 'password',
                decoration: InputDecoration(labelText: 'Password'),
              ),
              ElevatedButton(
                onPressed: () {
                  if (_formKey.currentState?.saveAndValidate() ?? false) {
                    print(_formKey.currentState?.value);
                  } else {
                    print('Validation failed');
                  }
                },
                child: Text('Submit'),
              ),
            ],
          ),
        ),
      ),
    );
    

    }
    }

    Login or Signup to reply.
  2. I’m not a fan of one-fits-all. But, indeed Riverpod can be a good solution for this.

    I think StateNotifier works pretty fine for your case. I don’t think you’re looking for a code solution by the question, but just to outline the process here are some code snippets that might help.

    You’ll have to create a state class containing all the different properties you’re going to collect.

    Something like:

    class FormData {
      String fullName;
      String realName;
      String ethnicity;
      // ....
    
      FormData({
        this.fullName = "",
        this.realName = "",
        this.ethnicity = "",
        // ...
      });
    }
    

    Get your StateNotifierProvider ready:

    // Define a Provider that holds the form data
    final formDataProvider = StateNotifierProvider<FormDataNotifier, FormData>((ref) {
      return FormDataNotifier();
    });
    

    Create your State Notifier:

    class FormDataNotifier extends StateNotifier<FormData> {
      FormDataNotifier() : super(FormData());
      
      // ...
      // Write some methods to update the field values
    
    }
    

    And there you go, just use it in your actual widgets.

    At the end of everything, in your save button widget, just access the state:

    class SaveButton extends ConsumerWidget {
      @override
      Widget build(BuildContext context, WidgetRef ref) {
        return ElevatedButton(
          onPressed: () {
            final formData = ref.read(formDataProvider);
    
            // Access all form data here
            print('Full Name: ${formData.fullName}');
            print('Real Name: ${formData.realName}');
            print('Ethnicity: ${formData.ethnicity}');
            // ... handle save logic
            // Clear the state if no longer needed
          },
          child: Text('Save'),
        );
      }
    }
    

    You’re good to go! You can do the same in pretty much a million different ways, but the important thing is to consider is the time and resource you might want to spend to a single problem. If you find Riverpod easy and as it can do it efficiently that’s a way-to-go.

    Hope this helps!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search