Flutter密码验证插件password_validated_field的使用
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
在 validated_fieldonChange
回调函数在 validated_fieldrequirement_widget
在 requirement_widget- 添加到 validated_field 的
requirement_widget
检查
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
更多关于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'),
),
],
),
),
),
);
}
}
代码解释
-
依赖导入:首先,我们导入了
flutter/material.dart
和password_validated_field
包。 -
主应用:
MyApp
类是我们的主应用类,它创建了一个Material应用并设置了主题。 -
密码验证屏幕:
PasswordValidationScreen
是一个有状态的widget,它包含了密码验证的逻辑。 -
表单:我们使用
Form
widget来包裹我们的密码输入框。_formKey
用于验证整个表单。 -
密码验证字段:
PasswordValidatedField
是password_validated_field
插件提供的widget,它允许我们定义多个验证规则。在这个例子中,我们要求密码至少8个字符长,并且包含至少一个字母和一个数字。 -
错误处理:当密码不符合验证规则时,
onValidate
回调将设置_passwordError
,该错误将显示在输入框下方。 -
提交按钮:点击提交按钮时,会调用
_formKey.currentState!.validate()
来验证整个表单。如果验证通过,我们可以执行提交操作(例如,打印密码)。
这个示例展示了如何使用password_validated_field
插件来进行基本的密码验证。根据你的需求,你可以添加更多的验证规则或自定义错误消息。