Search code examples
formsflutterdartflutter-form-builder

How to get form variables in flutter


I have a form in flutter and when you press the button it will call a post function that register a user but i can't acces to the variables in the form.

I want to acces to the username, email and password input values to make a post and register a user

I have divide it in diferents widgets, here the code:

The form

This is the form widget that I have in my register screen

Form(
            key: _formKey,
            child: SingleChildScrollView(
                physics: AlwaysScrollableScrollPhysics(),
                padding: EdgeInsets.symmetric(
                  horizontal: 40.0,
                  vertical: 60.0,
                ),
                child: Column(
                  children: <Widget>[
                    new Container(
                      child: Image.asset(
                        '../../assets/logo-feec.png',
                        width: 200,
                      ),
                      padding: EdgeInsets.symmetric(vertical: 15),
                      alignment: Alignment.topCenter,
                    ),
                    buildUsernameTF(),
                    SizedBox(
                      height: 30.0,
                    ),
                    buildEmailTF(),
                    SizedBox(
                      height: 30.0,
                    ),
                    buildPasswordTF(),
                    SizedBox(
                      height: 30.0,
                    ),
                    buildConfirmPasswordTF(),
                    Container(
                      padding: EdgeInsets.symmetric(vertical: 25.0),
                      width: 200,
                      child: ElevatedButton.icon(
                          onPressed: () async {
                            if (_formKey.currentState.validate()) {
                               futureString = await resource.MyHttpService().registerUser(username, email, password);
                               /* Here we want to access the variables */

                            }
                          },

                          label: Text('Envia'),
                          icon: Icon(Icons.login),
                          style: ElevatedButton.styleFrom(
                            primary: Colors.white,
                            onPrimary: Colors.black,
                            shape: const BeveledRectangleBorder(
                                borderRadius:
                                    BorderRadius.all(Radius.circular(3))),
                          )),
                    ),
                    Container(
                      padding: EdgeInsets.all(5),
                      width: 200,
                      child: TextButton(
                        onPressed: () => RouterConfig.router.navigateTo(
                          context,
                          "login",
                          transition: TransitionType.nativeModal,
                        ),
                        child: Text("Inicia sessió"),
                      ),
                    )
                  ],
                )),
          )

The widgets

These are the widgets called in the form

import 'package:flutter/material.dart';
import 'package:email_validator/email_validator.dart';


final TextEditingController _confirmPass = TextEditingController();
final TextEditingController _pass = TextEditingController();


Widget buildPasswordTF() {
  return Container(
    width: 600,
    child: TextFormField(
      controller: _pass,
      obscureText: true,
      decoration: const InputDecoration(
          icon: Icon(Icons.lock),
          hintText: 'Enter password',
          labelText: 'Password *'),
      validator: (password) {
        if (password == null || password.isEmpty) {
          return 'invalid Password';
        }
        return null;
      },
    ),
  );
}

Widget buildConfirmPasswordTF() {
  return Container(
    width: 600,
    child: TextFormField(
      controller: _confirmPass,
      obscureText: true,
      decoration: const InputDecoration(
          icon: Icon(Icons.lock),
          hintText: 'Enter password',
          labelText: 'Password *'),
      validator: (password) {
        if (password == null || password.isEmpty) {
          return 'Invalid Password';
        }
        if (password != _pass.text) {
          return 'Passwords don\'t match';
        }
        return null;
      },
    ),
  );
}



Widget buildUsernameTF() {
  return Container(
    width: 600,
    child: TextFormField(
      decoration: const InputDecoration(
          icon: Icon(Icons.person),
          hintText: 'Enter Username',
          labelText: 'Username'),
      validator: (username) {
        if (username == null || username.isEmpty) {
          return 'Invalid Username';
        }
        return null;
      },
    ),
  );
}

Widget buildEmailTF() {
  return Container(
    width: 600,
    child: TextFormField(
      decoration: const InputDecoration(
          icon: Icon(Icons.mail),
          hintText: 'Enter email',
          labelText: 'Email *'),
      validator: (email) {
        if (EmailValidator.validate(email) != true) {
          return 'Invalid Email';
        }
        if (email == null || email.isEmpty) {
          return 'Invalid Email';
        }
        return null;
      },
    ),
  );
}

Solution

  • The answer to this will depend on your widget tree but ideally, you would be able to access the TextEditingControllers inside your TextFormFields.

    You will need to create TextEditingControllers for each TextFormField:

    TextEditingController emailController = TextEditingController();
    

    And then when you submit, you need to access the controller and get the text.

    onPressed: () async {
       if (_formKey.currentState.validate()) {
         futureString = await resource.MyHttpService().registerUser(username, email, password);
         /* Here we want to access the variables */
         print('Email text: ' + emailController.text);
         }
      },