如何在颤振中获取表单变量

How to get form variables in flutter

我有一个 flutter 表单,当你按下按钮时,它会调用一个 post 函数来注册用户,但我无法访问表单中的变量。

我想访问用户名、电子邮件和密码输入值以创建 post 并注册用户

我把它分成不同的小部件,这里是代码:

形式

这是我的注册屏幕中的表单小部件

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ó"),
                      ),
                    )
                  ],
                )),
          )

小部件

这些是在表单中调用的小部件

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

这个问题的答案将取决于您的小部件树,但理想情况下,您将能够访问 TextFormFields 中的 TextEditingControllers。

您需要为每个 TextFormField 创建 TextEditingControllers:

TextEditingController emailController = TextEditingController();

然后当你提交的时候,你需要访问控制器并获取文本。

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