Flutter密码验证插件password_validated_field的使用

发布于 1周前 作者 ionicwang 来自 Flutter

Flutter密码验证插件password_validated_field的使用

password_validated_field 是一个Flutter包,它允许你在应用程序中包含一个外观酷炫且经过验证的 Password TextFormField,以增强用户体验。这个包是完全可修改和易于调整的。

可定制属性

通过导入 package:password_validated_field/src/requirement_widget.dart,你可以修改以下字段:

  • inputDecoration
  • textEditingController
  • textInputAction
  • onEditComplete
  • onFieldSubmitted
  • focusNode
  • cursorColor
  • textStyle
  • activeIcon
  • inActiveIcon
  • activeRequirementColor
  • inActiveRequirementColor

简单用法

下面是简单的使用示例:

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

class Example extends StatefulWidget {
  const Example({Key? key}) : super(key: key);

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

class _ExampleState extends State<Example> {
  // simple check
  bool _validPassword = false;

  // form key for validation
  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Password Validated Field"),
      ),
      body: Form(
        key: _formKey,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            _validPassword
                ? Text(
                    "Password Valid!",
                    style: TextStyle(fontSize: 22.0),
                  )
                : Container(),
            PasswordValidatedFields(), // password validated field from package
            
            // Button to validate the form
            ElevatedButton(
                onPressed: () {
                  if (_formKey.currentState!.validate()) {
                    setState(() {
                      _validPassword = true;
                    });
                  } else {
                    setState(() {
                      _validPassword = false;
                    });
                  }
                },
                child: Text("Check password!")),
          ],
        ),
      ),
    );
  }
}

自定义用法

你也可以自定义输入框的图标、颜色等属性:

class CustomizeFieldExample extends StatefulWidget {
  const CustomizeFieldExample({Key? key}) : super(key: key);

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

class _CustomizeFieldExampleState extends State<CustomizeFieldExample> {
  // simple check
  bool _validPassword = false;

  // form key
  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Customized Field"),
      ),
      body: Form(
        key: _formKey,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            _validPassword
                ? Text(
                    "Password Valid!",
                    style: TextStyle(fontSize: 22.0),
                  )
                : Container(),
            PasswordValidatedFields(
              inActiveIcon: Icons.cancel_outlined,
              activeIcon: Icons.check,
              inActiveRequirementColor: Colors.orange,
              activeRequirementColor: Colors.green,
            ), // password validated field from package
            ElevatedButton(
                onPressed: () {
                  if (_formKey.currentState!.validate()) {
                    setState(() {
                      _validPassword = true;
                    });
                  } else {
                    setState(() {
                      _validPassword = false;
                    });
                  }
                },
                child: Text("Check password!")),
          ],
        ),
      ),
    );
  }
}

更多自定义用法

进一步自定义输入框样式:

class MoreCustomizedField extends StatefulWidget {
  const MoreCustomizedField({Key? key}) : super(key: key);

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

class _MoreCustomizedFieldState extends State<MoreCustomizedField> {
  // simple check
  bool _validPassword = false;

  // form key
  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Customized Field"),
      ),
      body: Form(
        key: _formKey,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            _validPassword
                ? Text(
                    "Password Valid!",
                    style: TextStyle(fontSize: 22.0),
                  )
                : Container(),
            PasswordValidatedFields(
              inActiveIcon: Icons.cancel,
              activeIcon: Icons.done_all,
              inputDecoration: InputDecoration(
                labelText: "Enter password",
                filled: true,
                fillColor: Colors.grey[300],
                prefixIcon: Icon(Icons.lock),
                enabledBorder: OutlineInputBorder(
                  borderSide: BorderSide(color: Colors.transparent),
                  borderRadius: BorderRadius.circular(10.0),
                ),
                focusedBorder: OutlineInputBorder(
                  borderSide: BorderSide(color: Colors.blue),
                  borderRadius: BorderRadius.circular(10.0),
                ),
                errorBorder: OutlineInputBorder(
                  borderSide: BorderSide(color: Colors.red),
                  borderRadius: BorderRadius.circular(10.0),
                ),
                focusedErrorBorder: OutlineInputBorder(
                  borderSide: BorderSide(color: Colors.red),
                  borderRadius: BorderRadius.circular(10.0),
                ),
              ),
            ), // password validated filed from package
            ElevatedButton(
                onPressed: () {
                  if (_formKey.currentState!.validate()) {
                    setState(() {
                      _validPassword = true;
                    });
                  } else {
                    setState(() {
                      _validPassword = false;
                    });
                  }
                },
                child: Text("Check password!")),
          ],
        ),
      ),
    );
  }
}

修改包

你可以根据需要轻松修改此包。主要关注以下属性:

RegExp 修改

  • 1个大写字母:RegExp(r'[A-Z]')
  • 1个小写字母:RegExp(r'[a-z]')
  • 1个数字:RegExp(r'[0-9]')
  • 1个特殊字符:RegExp(r'[!@#$%^&*(),.?":{}|<>]')
  • 至少6个字符长度:_pass.length >= 6

结合上述正则表达式,可以得到:

RegExp(r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!@#\$&*~]).{6,}$')

完整简单示例代码可以在 这里 查看。


更多关于Flutter密码验证插件password_validated_field的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter密码验证插件password_validated_field的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用password_validated_field插件来进行密码验证的示例代码。

首先,确保你已经在pubspec.yaml文件中添加了password_validated_field依赖:

dependencies:
  flutter:
    sdk: flutter
  password_validated_field: ^x.y.z  # 请替换为最新版本号

然后运行flutter pub get来安装依赖。

接下来,你可以在你的Flutter项目中使用这个插件来创建一个带有密码验证功能的表单。以下是一个完整的示例代码:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Password Validation Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: PasswordValidationScreen(),
    );
  }
}

class PasswordValidationScreen extends StatefulWidget {
  @override
  _PasswordValidationScreenState createState() => _PasswordValidationScreenState();
}

class _PasswordValidationScreenState extends State<PasswordValidationScreen> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  String? _password;
  String? _passwordError;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Password Validation Example'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              PasswordValidatedField(
                labelText: 'Password',
                validators: [
                  {
                    'pattern': r'^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$',
                    'errorText': 'Password must be at least 8 characters long, and include at least one letter and one number.',
                  },
                ],
                onChanged: (value) {
                  setState(() {
                    _password = value;
                    _passwordError = null; // Clear any previous error
                  });
                },
                onValidate: (value) {
                  setState(() {
                    if (value == null || value.isEmpty) {
                      _passwordError = 'Password is required.';
                    } else {
                      _passwordError = null; // No error if the value is not empty
                    }
                  });
                },
              ),
              if (_passwordError != null)
                Text(
                  _passwordError!,
                  style: TextStyle(color: Colors.red),
                ),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: () {
                  if (_formKey.currentState!.validate()) {
                    // Perform submit action, e.g., navigate to next screen
                    print('Password is valid: $_password');
                  }
                },
                child: Text('Submit'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

代码解释

  1. 依赖导入:首先,我们导入了flutter/material.dartpassword_validated_field包。

  2. 主应用MyApp类是我们的主应用类,它创建了一个Material应用并设置了主题。

  3. 密码验证屏幕PasswordValidationScreen是一个有状态的widget,它包含了密码验证的逻辑。

  4. 表单:我们使用Form widget来包裹我们的密码输入框。_formKey用于验证整个表单。

  5. 密码验证字段PasswordValidatedFieldpassword_validated_field插件提供的widget,它允许我们定义多个验证规则。在这个例子中,我们要求密码至少8个字符长,并且包含至少一个字母和一个数字。

  6. 错误处理:当密码不符合验证规则时,onValidate回调将设置_passwordError,该错误将显示在输入框下方。

  7. 提交按钮:点击提交按钮时,会调用_formKey.currentState!.validate()来验证整个表单。如果验证通过,我们可以执行提交操作(例如,打印密码)。

这个示例展示了如何使用password_validated_field插件来进行基本的密码验证。根据你的需求,你可以添加更多的验证规则或自定义错误消息。

回到顶部