Flutter密码锁屏插件passcode_screen的使用

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

Flutter密码锁屏插件 passcode_screen 的使用

passcode_screen 是一个用于Flutter的插件,可以在iOS和Android平台上展示类似原生iOS的密码输入界面。本文将介绍如何安装和使用该插件,并提供一个完整的示例代码。

安装

首先,在 pubspec.yaml 文件中添加 passcode_screen 依赖:

dependencies:
  passcode_screen: ^2.0.0

然后在 Dart 文件中导入:

import 'package:passcode_screen/passcode_screen.dart';

功能概述

1. 创建简单的密码锁屏界面

PasscodeScreen(
  title: Text('Enter App Passcode'),
  passwordEnteredCallback: _onPasscodeEntered,
  cancelButton: Text('Cancel'),
  deleteButton: Text('Delete'),
  shouldTriggerVerification: _verificationNotifier.stream,
);

2. 密码输入完成回调

void _onPasscodeEntered(String enteredPasscode) {
  bool isValid = storedPasscode == enteredPasscode;
  _verificationNotifier.add(isValid);
  if (isValid) {
    setState(() {
      isAuthenticated = true;
    });
  }
}

3. 通知密码屏幕是否验证成功

final StreamController<bool> _verificationNotifier = StreamController<bool>.broadcast();

@override
void dispose() {
  _verificationNotifier.close();
  super.dispose();
}

4. 自定义UI

自定义圆圈样式

CircleUIConfig circleUIConfig = CircleUIConfig(
  borderColor: Colors.blue,
  fillColor: Colors.blue,
  borderWidth: 2.0,
  circleSize: 30.0,
);

自定义键盘样式

KeyboardUIConfig keyboardUIConfig = KeyboardUIConfig(
  digitBorderWidth: 2,
  primaryColor: Colors.blue,
);

示例Demo

以下是一个完整的示例代码,展示了如何使用 passcode_screen 插件创建一个带有默认和自定义样式的密码锁屏界面。

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:passcode_screen/circle.dart';
import 'package:passcode_screen/keyboard.dart';
import 'package:passcode_screen/passcode_screen.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Passcode Lock Screen Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: ExampleHomePage(title: 'Passcode Lock Screen Example'),
    );
  }
}

const storedPasscode = '123456';

class ExampleHomePage extends StatefulWidget {
  ExampleHomePage({Key? key, required this.title}) : super(key: key);
  final String title;

  @override
  State<ExampleHomePage> createState() => _ExampleHomePageState();
}

class _ExampleHomePageState extends State<ExampleHomePage> {
  final StreamController<bool> _verificationNotifier =
      StreamController<bool>.broadcast();

  bool isAuthenticated = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('You are ${isAuthenticated ? '' : 'NOT'} authenticated'),
            _defaultLockScreenButton(context),
            _customColorsLockScreenButton(context)
          ],
        ),
      ),
    );
  }

  Widget _defaultLockScreenButton(BuildContext context) => MaterialButton(
        color: Theme.of(context).primaryColor,
        child: Text('Open Default Lock Screen'),
        onPressed: () {
          _showLockScreen(
            context,
            opaque: false,
            cancelButton: Text(
              'Cancel',
              style: const TextStyle(fontSize: 16, color: Colors.white),
              semanticsLabel: 'Cancel',
            ),
          );
        },
      );

  Widget _customColorsLockScreenButton(BuildContext context) {
    return MaterialButton(
      color: Theme.of(context).primaryColor,
      child: Text('Open Custom Lock Screen'),
      onPressed: () {
        _showLockScreen(context,
            opaque: false,
            circleUIConfig: CircleUIConfig(
                borderColor: Colors.blue,
                fillColor: Colors.blue,
                circleSize: 30),
            keyboardUIConfig: KeyboardUIConfig(
                digitBorderWidth: 2, primaryColor: Colors.blue),
            cancelButton: Icon(
              Icons.arrow_back,
              color: Colors.blue,
            ),
            digits: ['一', '二', '三', '四', '五', '六', '七', '八', '九', '零']);
      },
    );
  }

  void _showLockScreen(
    BuildContext context, {
    required bool opaque,
    CircleUIConfig? circleUIConfig,
    KeyboardUIConfig? keyboardUIConfig,
    required Widget cancelButton,
    List<String>? digits,
  }) {
    Navigator.push(
        context,
        PageRouteBuilder(
          opaque: opaque,
          pageBuilder: (context, animation, secondaryAnimation) =>
              PasscodeScreen(
            title: Text(
              'Enter App Passcode',
              textAlign: TextAlign.center,
              style: TextStyle(color: Colors.white, fontSize: 28),
            ),
            circleUIConfig: circleUIConfig,
            keyboardUIConfig: keyboardUIConfig,
            passwordEnteredCallback: _onPasscodeEntered,
            cancelButton: cancelButton,
            deleteButton: Text(
              'Delete',
              style: const TextStyle(fontSize: 16, color: Colors.white),
              semanticsLabel: 'Delete',
            ),
            shouldTriggerVerification: _verificationNotifier.stream,
            backgroundColor: Colors.black.withOpacity(0.8),
            cancelCallback: _onPasscodeCancelled,
            digits: digits,
            passwordDigits: 6,
            bottomWidget: _buildPasscodeRestoreButton(),
          ),
        ));
  }

  void _onPasscodeEntered(String enteredPasscode) {
    bool isValid = storedPasscode == enteredPasscode;
    _verificationNotifier.add(isValid);
    if (isValid) {
      setState(() {
        isAuthenticated = isValid;
      });
    }
  }

  void _onPasscodeCancelled() {
    Navigator.maybePop(context);
  }

  @override
  void dispose() {
    _verificationNotifier.close();
    super.dispose();
  }

  Widget _buildPasscodeRestoreButton() => Align(
        alignment: Alignment.bottomCenter,
        child: Container(
          margin: const EdgeInsets.only(bottom: 10.0, top: 20.0),
          child: TextButton(
            child: Text(
              "Reset passcode",
              textAlign: TextAlign.center,
              style: const TextStyle(
                  fontSize: 16,
                  color: Colors.white,
                  fontWeight: FontWeight.w300),
            ),
            onPressed: _resetAppPassword,
          ),
        ),
      );

  void _resetAppPassword() {
    Navigator.maybePop(context).then((result) {
      if (!result) {
        return;
      }
      _showRestoreDialog(() {
        Navigator.maybePop(context);
        //TODO: Clear your stored passcode here
      });
    });
  }

  void _showRestoreDialog(VoidCallback onAccepted) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text(
            "Reset passcode",
            style: const TextStyle(color: Colors.black87),
          ),
          content: Text(
            "Passcode reset is a non-secure operation!\n\nConsider removing all user data if this action performed.",
            style: const TextStyle(color: Colors.black87),
          ),
          actions: <Widget>[
            TextButton(
              child: Text(
                "Cancel",
                style: const TextStyle(fontSize: 18),
              ),
              onPressed: () {
                Navigator.maybePop(context);
              },
            ),
            TextButton(
              child: Text(
                "I understand",
                style: const TextStyle(fontSize: 18),
              ),
              onPressed: onAccepted,
            ),
          ],
        );
      },
    );
  }
}

以上代码展示了如何使用 passcode_screen 插件创建一个密码锁屏界面,并提供了默认和自定义样式的实现方法。希望这些信息能帮助你快速上手并应用到你的项目中。


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

1 回复

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


当然,以下是一个关于如何在Flutter项目中使用passcode_screen插件来实现密码锁屏功能的代码示例。passcode_screen是一个流行的Flutter插件,用于创建自定义的PIN码或密码锁屏界面。

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

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

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

接下来,下面是一个完整的示例代码,展示了如何使用passcode_screen插件来创建一个简单的密码锁屏界面:

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

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

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

class PasscodeScreenWrapper extends StatefulWidget {
  @override
  _PasscodeScreenWrapperState createState() => _PasscodeScreenWrapperState();
}

class _PasscodeScreenWrapperState extends State<PasscodeScreenWrapper> {
  final _controller = PasscodeController();

  @override
  void initState() {
    super.initState();
    // 设置初始密码(例如:1234)
    _controller.setPasscode(List.filled(4, '1'));
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Passcode Screen Example'),
      ),
      body: Center(
        child: Builder(
          builder: (context) {
            return PasscodeScreen(
              controller: _controller,
              length: 4,
              onCompleted: (passed) async {
                if (passed) {
                  // 密码正确,跳转到主页面或执行其他操作
                  Navigator.pushReplacement(
                    context,
                    MaterialPageRoute(builder: (context) => HomePage()),
                  );
                } else {
                  // 密码错误,显示错误消息或执行其他操作
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('密码错误,请重试')),
                  );
                }
              },
              onChanged: (value) {
                // 密码输入变化时的回调(可选)
                print('当前输入: $value');
              },
              title: '请输入密码',
              subtitle: '这是一个简单的密码锁屏示例',
              animationType: AnimationType.slide,
              hideKeyboardAutomatically: true,
              autoFocus: true,
              obscureText: false,
              showCursor: false,
              enableActiveFill: true,
              activeFillColor: Colors.blue,
              inactiveFillColor: Colors.grey[300]!,
              activeColor: Colors.blue,
              inactiveColor: Colors.grey,
              buttonBackgroundColor: Colors.blue,
              buttonTextColor: Colors.white,
              appBarBackgroundColor: Colors.blueGrey,
              keyboardType: TextInputType.number,
            );
          },
        ),
      ),
    );
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('主页'),
      ),
      body: Center(
        child: Text('欢迎来到主页!'),
      ),
    );
  }
}

在这个示例中,我们创建了一个简单的Flutter应用,其中包含一个密码锁屏界面。当用户输入正确的密码(在这个例子中是1234)时,他们将被导航到HomePage。如果密码错误,将显示一个SnackBar提示用户密码错误。

你可以根据需要自定义PasscodeScreen的参数,例如动画类型、颜色、是否隐藏键盘等。这个示例应该能帮助你快速上手passcode_screen插件的使用。

回到顶部