首页 > 解决方案 > Flutter - 验证用户输入

问题描述

所以我正在尝试为我的应用程序创建一个注册页面。到目前为止,我已经有了一些欢迎文本和一个输入表单,用户可以在其中输入他们的电子邮件。我还有一个按钮,它最终会更改输入字段下方显示“下一步”的页面。我们的想法是禁用按钮,这很简单(只需添加 OnPressed: null),但是当用户输入至少一个字符时,后跟一个“@”,然后是一个字符串列表“.com,.co”。 uk 等)下一个按钮将启用。我试图在表单中添加一个 validate if else 语句,但并不高兴,因此将其从下面的代码中删除。我想我要问的是我该怎么做:

非常感谢对上述任何内容的所有回复/贡献!

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

void main() {
  runApp(MyApp());
}

class MyCustomForm extends StatefulWidget {
  @override
  MyCustomFormState createState() {
    return MyCustomFormState();
  }
}

class MyCustomFormState extends State<MyCustomForm> {
  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: Column(children: <Widget>[
        TextFormField(
          decoration: InputDecoration(labelText: 'Enter your email'),
        ),
      ]),
    );
  }
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Test Bench',
      home: Stack(
        children: [
          Scaffold(
            body: Container(
              width: double.infinity,
              decoration: BoxDecoration(color: Colors.pinkAccent),
              child: Padding(
                padding: const EdgeInsets.all(30.0),
                child: Column(
                  children: [
                    Text(
                      "Hello, Let's Get Started...\n",
                      style: TextStyle(
                        fontSize: 60.0,
                        fontWeight: FontWeight.bold,
                        fontFamily: 'Oswald',
                        color: Colors.black,
                      ),
                    ),
                    MyCustomForm(),
                    ButtonTheme(
                      minWidth: 250.0,
                      child: RaisedButton(
                        onPressed: null,
                        child: Text("Next"),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

标签: fluttervalidationauthenticationdartuser-input

解决方案


这是一个可能的解决方案。我使用正则表达式来验证输入的电子邮件。您可以从此处了解有关验证的更多信息: https ://flutter.dev/docs/cookbook/forms/validation

class MyApp extends StatefulWidget {
  // This widget is the root of your application.
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final _formKey = GlobalKey<FormState>();

  bool isValidated = false;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Test Bench',
        home: Stack(children: [
          Scaffold(
              body: Container(
                  width: double.infinity,
                  decoration: BoxDecoration(color: Colors.pinkAccent),
                  child: Padding(
                      padding: const EdgeInsets.all(30.0),
                      child: Column(children: [
                        Text("Hello, Let's Get Started...\n",
                            style: TextStyle(
                              fontSize: 60.0,
                              fontWeight: FontWeight.bold,
                              fontFamily: 'Oswald',
                              color: Colors.black,
                            )),
                        Form(
                            key: _formKey,
                            child: Column(children: <Widget>[
                              TextFormField(
                                onChanged: (input) {
                                  _formKey.currentState.validate();
                                },
                                validator: (input) {     
                                  var regex = RegExp(
                                      r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+");
                                  if (!regex.hasMatch(input) && isValidated) {
                                    setState(() {
                                      isValidated = false;
                                    });
                                    return null;
                                  } else {
                                    setState(() {
                                      isValidated = true;
                                    });
                                    return input;
                                  }
                                },
                                decoration: InputDecoration(
                                    labelText: 'Enter your email'),
                              ),
                            ])),
                        ButtonTheme(
                          minWidth: 250.0,
                          child: RaisedButton(
                            onPressed:
                                isValidated ? () => print('Signed In') : null,
                            child: Text("Next"),
                          ),
                        ),
                      ]))))
        ]));
  }
}


推荐阅读