Flutter-如何实现一个电子邮件TextFormField小部件以在多个屏幕中使用?

时间:2020-03-31 16:38:40

标签: email flutter dart firebase-authentication

我正在开发带有注册,登录和重置密码屏幕的应用程序。在所有这些屏幕中,用户必须输入他的电子邮件地址。现在,我不会为每个屏幕都实现电子邮件地址文本字段。因此,我将为每个屏幕(如以下代码)实现一个电子邮件文本字段小部件。

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

class EMailTextFormField extends StatefulWidget {

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

class _EMailTextFormFieldState extends State<EMailTextFormField> {
  final _email = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 3.0),
      child: TextFormField(
        decoration: InputDecoration(
          icon: Icon(Icons.email, size: IconTheme.of(context).size, color: IconTheme.of(context).color),
          labelText: 'E-Mail...',
          counterText: '',
        ),
        keyboardType: TextInputType.emailAddress,
        controller: _email,
        validator: _validateEmail,
        maxLength: 70,
      ),
    );
  }

  String _validateEmail(String email) {
    // validate E-Mail function...
  }
}

我的问题是,现在我无法在不同屏幕(注册,登录和重置密码)中的此小部件外部使用TextEditingController(_email),例如:

final FirebaseUser user = (await _auth.createUserWithEmailAndPassword(
                  email: _email.text.toString(), password: _password.text.toString())).user;

错误是“未定义名称_email”,因为_email TextEditingController在EMailTextFormField小部件中,但是如何将EMailTextFormField小部件中的_email字段的值提供给其他屏幕(注册,登录和重置密码)?

到目前为止,没有人能帮助我吗?

1 个答案:

答案 0 :(得分:1)

您可以使用$env:myvar = "Fname = John ``n Lname= Smith ``n DOB = 01/01/1980" 回调来做到这一点。

EMailTextFormField:

onSaved

您将在其中使用EMailTextFormField的页面:

class EMailTextFormField extends StatefulWidget {

  final void Function(String email) onSaved;

  const EMailTextFormField({Key key, this.onSaved}) : super(key: key);

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

class EMailTextFormFieldState extends State<EMailTextFormField> {
  final _email = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 3.0),
      child: TextFormField(
        decoration: InputDecoration(
          icon: Icon(Icons.email, size: IconTheme.of(context).size, color: IconTheme.of(context).color),
          labelText: 'E-Mail...',
          counterText: '',
        ),
        keyboardType: TextInputType.emailAddress,
        controller: _email,
        validator: _validateEmail,
        maxLength: 70,
        onSaved: widget.onSaved, //callback
      ),
    );
  }

  String _validateEmail(String email) {
    // validate E-Mail function...
  }
}