首页 > 解决方案 > 在同一字段中使用 ObscureText 和 Validator 时无法在 TextFormField 中键入任何内容

问题描述

海我是颤振/飞镖的新手,希望你们能在这方面帮助我。我在使用TextFormField 时遇到了这个问题,我无法在该字段中输入任何内容obscureText: truevalidator:有人能告诉我这是为什么吗?

class _LoginPageState extends State<LoginPage>{

  final formKey = new GlobalKey<FormState>();
  String _email;
  String _password;

  void validateAndSave(){

    final form = formKey.currentState;

    if (form.validate()){
      print('Form is valid');
    }else{
      print('Form is invalid');
    }

  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Login'),
      ),
      body: new Container(
        padding: const EdgeInsets.all(20.0),
        child: new Form(
          key: formKey,
            child: new Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: <Widget>[
                new TextFormField(
                  decoration: new InputDecoration(labelText: 'Email'),
                  validator: (value) => value.isEmpty ? 'Email can\'t be empty' : null,
                  onSaved: (value) => _email = value,
                ),
                new TextFormField(
                  decoration: new InputDecoration(labelText: 'Password'),
                  obscureText: true,
                  validator: (value) => value.isEmpty ? 'Password can\'t be empty' : null,
                  onSaved: (value) => _password = value,
                ),
                new RaisedButton(
                  child: new Text('Login', style: new TextStyle(fontSize: 20.0)),
                  onPressed: validateAndSave,
                )
              ],
            ),
          )
        )
      );
    }
}

标签: dartflutter

解决方案


上面的代码没有任何问题。无论如何,当我测试上面的代码时,添加/替换了一些东西,比如验证器类FieldValidator,而不是列使用 ListView 等。

演示

查看代码:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'My App',
      home: LoginPage(),
    );
  }
}

class FieldValidator {
  static String validateEmail(String value) {
    if (value.isEmpty) return 'Email can\'t be empty!';

    Pattern pattern =
        r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';

    RegExp regex = RegExp(pattern);

    if (!regex.hasMatch(value)) {
      return 'Enter Valid Email!';
    }

    return null;
  }

  static String validatePassword(String value) {
    if (value.isEmpty) return 'Password can\'t be empty!';

    if (value.length < 7) {
      return 'Password must be more than 6 charater';
    }

    return null;
  }
}

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  String _email;
  String _password;
  final _formKey = GlobalKey<FormState>();

  void validateAndSave() {
    final form = _formKey.currentState;

    if (form.validate()) {
      form.save();
      print('Form is valid $_email $_password');
    } else {
      print('Form is invalid');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Login'),
      ),
      body: Container(
        padding: const EdgeInsets.all(20.0),
        child: Form(
          key: _formKey,
          child: ListView(
            children: <Widget>[
              TextFormField(
                decoration: InputDecoration(labelText: 'Email'),
                validator: FieldValidator.validateEmail,
                onSaved: (value) => _email = value.trim(),
              ),
              TextFormField(
                decoration: InputDecoration(labelText: 'Password'),
                obscureText: true,
                validator: FieldValidator.validatePassword,
                onSaved: (value) => _password = value.trim(),
              ),
              RaisedButton(
                child: Text('Login', style: TextStyle(fontSize: 20.0)),
                onPressed: validateAndSave,
              )
            ],
          ),
        ),
      ),
    );
  }
}

希望能帮助到你 !


推荐阅读