Flutter密码输入插件password_input的使用

Flutter密码输入插件password_input的使用

一个帮助开发者在最佳UI下获取密码输入的新Flutter包。

该源代码为100% Dart,并且所有文件都位于/lib文件夹中。

支持项目

展示一些爱心并为项目点赞以支持该项目:

GitHub stars GitHub forks GitHub watchers GitHub followers

Twitter Follow

Open Source Love License

使用Password Input快速创建UI

无输入

有输入

安装

在你的 pubspec.yaml 文件的 dependencies: 部分添加以下行:

  password_input: <latest_version>

使用

首先,导入 password_input 包:

import 'package:password_input/password_input.dart';

然后,在你的 StatelessWidgetStatefulWidget 中使用 PasswordInputTextField

class MyWidget extends StatelessWidget {
  Widget build(BuildContext context) {
    return Center(
      // 使用此组件作为密码输入框
      child: PasswordInputTextField(
        passwordLength: 6, // 设置密码长度
        keyboardType: TextInputType.text, // 设置键盘类型
        autoFocus: true, // 自动聚焦
        inputFormatter: [
          FilteringTextInputFormatter.allow(RegExp(r'[a-zA-Z0-9_@.]')), // 允许输入的字符
        ],
        textInputAction: TextInputAction.done, // 设置提交动作
        onSubmit: (password) {
          if (password == null || password.isEmpty || password.length > 6) {
            setState(() {
              _errorMessage = "Enter Password";
            });
          }
        },
      ),
    );
  }
}

完整示例代码

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:password_input/password_input.dart';

class PasswordScreen extends StatefulWidget {
  [@override](/user/override)
  _PasswordScreenState createState() => _PasswordScreenState();
}

class _PasswordScreenState extends State<PasswordScreen> {
  /// 控制输入文本框。
  TextEditingController _passwordEditingController = TextEditingController();

  String _errorMessage = "";

  /// 装饰Pin的外部。
  late PasswordDecoration _pinDecoration;

  late PasswordDecoration _looseDecoration;

  late PasswordDecoration _tightDecoration;

  [@override](/user/override)
  void initState() {
    super.initState();

    /// 对于UnderLine装饰
    _pinDecoration = UnderlineDecoration(
      enteredColor: Colors.black,
      color: Colors.black,
      errorText: _errorMessage,
      textStyle: TextStyle(color: Colors.red),
    );

    /// 对于BoxLoose装饰
    _looseDecoration = BoxLooseDecoration(
      enteredColor: Colors.black,
      errorText: _errorMessage,
      textStyle: TextStyle(color: Colors.red),
    );

    /// 对于BoxTight装饰
    _tightDecoration = BoxTightDecoration(
      strokeColor: Colors.black,
      errorText: _errorMessage,
      textStyle: TextStyle(color: Colors.red),
    );
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: SafeArea(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Expanded(
                flex: 3,
                child: Align(
                  alignment: Alignment.bottomCenter,
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      FittedBox(
                        child: Text("ENTER PASSWORD",
                            style: TextStyle(
                                fontSize: 40, fontWeight: FontWeight.w900)),
                      ),
                      Text(
                        "Please Enter Password.",
                        style: TextStyle(
                            fontWeight: FontWeight.w500, fontSize: 15),
                      ),
                    ],
                  ),
                )),
            Expanded(
              flex: 4,
              child: Align(
                alignment: Alignment.topCenter,
                child: Column(
                  children: [
                    Padding(
                      padding: const EdgeInsets.all(16.0),
                      child: PasswordInputTextField(
                        passwordLength: 6,
                        decoration: _pinDecoration,
                        controller: _passwordEditingController,
                        keyboardType: TextInputType.text,
                        autoFocus: true,
                        inputFormatter: [
                          FilteringTextInputFormatter.allow(
                              RegExp(r'[a-zA-Z0-9_@.]')),
                        ],
                        textInputAction: TextInputAction.done,
                        onSubmit: (password) {
                          if (password.isEmpty || password.length > 6) {
                            setState(() {
                              _errorMessage = "Enter Password";
                            });
                          }
                        },
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.all(16.0),
                      child: PasswordInputTextField(
                        passwordLength: 6,
                        decoration: _looseDecoration,
                        controller: _passwordEditingController,
                        keyboardType: TextInputType.text,
                        autoFocus: true,
                        inputFormatter: [
                          FilteringTextInputFormatter.allow(
                              RegExp(r'[a-zA-Z0-9_@.]')),
                        ],
                        textInputAction: TextInputAction.done,
                        onSubmit: (password) {
                          if (password.isEmpty || password.length > 6) {
                            setState(() {
                              _errorMessage = "Enter Password";
                            });
                          }
                        },
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.all(16.0),
                      child: PasswordInputTextField(
                        passwordLength: 6,
                        decoration: _tightDecoration,
                        controller: _passwordEditingController,
                        keyboardType: TextInputType.text,
                        autoFocus: true,
                        inputFormatter: [
                          FilteringTextInputFormatter.allow(
                              RegExp(r'[a-zA-Z0-9_@.]')),
                        ],
                        textInputAction: TextInputAction.done,
                        onSubmit: (password) {
                          if (password.isEmpty || password.length > 6) {
                            setState(() {
                              _errorMessage = "Enter Password";
                            });
                          }
                        },
                      ),
                    ),
                  ],
                ),
              ),
            ),
            Expanded(
                flex: 3,
                child: Container(
                  alignment: Alignment.topCenter,
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                        primary: Colors.black,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(5.0),
                        )),
                    onPressed: () {
                      if (_passwordEditingController.value.text.isEmpty ||
                          _passwordEditingController.value.text.length > 6) {
                        setState(() {
                          _errorMessage = "Enter Password";
                        });
                      } else {
                        Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (_) => PasswordScreen()));
                      }
                    },
                    child: Padding(
                      padding: const EdgeInsets.symmetric(
                          vertical: 5.0, horizontal: 15.0),
                      child: Text(
                        "VERIFY",
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: 18,
                            fontWeight: FontWeight.w700),
                      ),
                    ),
                  ),
                ))
          ],
        ),
      ),
    );
  }
}

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

1 回复

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


password_input 是一个用于 Flutter 的密码输入插件,它提供了一个美观且安全的密码输入界面。使用这个插件,你可以轻松地在你的 Flutter 应用中集成密码输入功能。

安装插件

首先,你需要在 pubspec.yaml 文件中添加 password_input 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  password_input: ^1.0.0  # 请检查最新版本

然后运行 flutter pub get 来安装插件。

基本用法

接下来,你可以在你的 Flutter 应用中使用 PasswordInput 组件。以下是一个简单的示例:

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

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Password Input Example'),
        ),
        body: Center(
          child: PasswordInput(
            onChanged: (value) {
              print('Password: $value');
            },
            hintText: 'Enter your password',
          ),
        ),
      ),
    );
  }
}

参数说明

PasswordInput 组件提供了多个可配置的参数,以下是一些常用的参数:

  • onChanged: 当密码输入内容发生变化时触发的回调函数。
  • hintText: 输入框的提示文本。
  • obscureText: 是否隐藏输入的密码(默认值为 true)。
  • maxLength: 密码的最大长度。
  • keyboardType: 键盘类型(默认值为 TextInputType.text)。
  • style: 输入文本的样式。
  • decoration: 输入框的装饰(如边框、背景等)。

自定义样式

你可以通过 decoration 参数来自定义输入框的样式。例如:

PasswordInput(
  onChanged: (value) {
    print('Password: $value');
  },
  hintText: 'Enter your password',
  decoration: InputDecoration(
    border: OutlineInputBorder(),
    labelText: 'Password',
    prefixIcon: Icon(Icons.lock),
  ),
)

处理密码输入

你可以在 onChanged 回调中处理用户输入的密码。例如,你可以验证密码的强度或在用户输入完密码后执行某些操作。

PasswordInput(
  onChanged: (value) {
    if (value.length >= 8) {
      print('Password is strong enough');
    } else {
      print('Password is too short');
    }
  },
  hintText: 'Enter your password',
)

完整示例

以下是一个完整的示例,展示了如何使用 PasswordInput 组件:

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

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Password Input Example'),
        ),
        body: Center(
          child: PasswordInput(
            onChanged: (value) {
              if (value.length >= 8) {
                print('Password is strong enough');
              } else {
                print('Password is too short');
              }
            },
            hintText: 'Enter your password',
            decoration: InputDecoration(
              border: OutlineInputBorder(),
              labelText: 'Password',
              prefixIcon: Icon(Icons.lock),
            ),
          ),
        ),
      ),
    );
  }
}
回到顶部