Flutter自定义引脚屏幕插件custom_pin_screen的使用

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

Flutter自定义引脚屏幕插件custom_pin_screen的使用

🔐 custom pin screen

codecov CI license PRs Welcome GitHub contributors GitHub last commit

这是一个Flutter包,用于在您的移动应用程序中添加带有自定义键盘和PIN码的屏幕。

🎖 Installing 安装

pubspec.yaml文件中添加依赖:

dependencies:
  custom_pin_screen: "^1.0.0"

然后执行flutter pub get以安装新的依赖项。

⚡️ Import 导入

在您的Dart文件中导入此库:

import 'package:custom_pin_screen/custom_pin_screen.dart';

🎮 How To Use 使用方法

Pin Auth PIN验证

通过以下代码可以在应用中打开一个PIN验证页面:

onPressed: (){
    Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => PinAuthentication(
                      onChanged: (v) {
                        if (kDebugMode) {
                          print(v);
                        }
                      },
                      onSpecialKeyTap: () {},
                      specialKey: const SizedBox(),
                      useFingerprint: true,
                      onbuttonClick: () {},
                      submitLabel: const Text(
                        'Submit',
                        style: TextStyle(color: Colors.white, fontSize: 20),
                      ),
                    ),
                  ),
                );
    },

Custom Keyboard 自定义键盘

您还可以创建一个包含自定义键盘的界面,例如用于输入金额:

Column(
        children: [
          const Padding(
            padding: EdgeInsets.symmetric(
              horizontal: 35.0,
              vertical: 35.0,
            ),
            child: Text(
              "How much do you want to fund your wallet with",
              textAlign: TextAlign.center,
              style: TextStyle(
                color: Colors.blue,
                fontWeight: FontWeight.w700,
                fontSize: 18,
              ),
            ),
          ),
          Expanded(
              child: CustomAppKeyBoard(
            onChanged: (v) {
              if (kDebugMode) {
                print(v);
              }
            },
            onbuttonClick: () {
              if (kDebugMode) {
                print('clicked');
              }
            },
            maxLength: 4,
            submitLabel: const Text(
              'Proceed',
              style: TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.w700,
                fontSize: 18,
              ),
            ),
            // ),
          ))
        ],
      )

示例Demo

下面是一个完整的示例项目,它展示了如何使用custom_pin_screen包中的组件。这个例子包含了两个主要功能:PIN验证和自定义键盘。

主程序入口

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:custom_pin_screen/custom_pin_screen.dart';

import 'pin_code_field.dart'; // 假设这是你自己的文件,里面定义了PinCodeField等组件

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Pin Screens Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Pin Screens'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton.icon(
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => const PinAuthScreen(),
                  ),
                );
              },
              icon: const Text('Pin Auth'),
              label: const Icon(Icons.lock),
            ),
            ElevatedButton.icon(
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => const WalletScreen(),
                  ),
                );
              },
              icon: const Text('Custom Keyboard'),
              label: const Icon(Icons.keyboard),
            ),
          ],
        ),
      ),
    );
  }
}

钱包充值页面(WalletScreen)

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

  @override
  State<WalletScreen> createState() => _WalletScreenState();
}

class _WalletScreenState extends State<WalletScreen> {
  final TextEditingController controller = TextEditingController();

  @override
  void initState() {
    super.initState();
    controller.addListener(() {
      setState(() {});
    });
  }

  @override
  void dispose() {
    controller.removeListener(() {
      setState(() {});
    });
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
            icon: const Icon(
              Icons.arrow_back_ios,
              color: Colors.black,
            ),
            onPressed: () {
              Navigator.pop(context);
            }),
        backgroundColor: Colors.white,
        elevation: 0.0,
        title: const Text(
          "Fund wallet",
          style: TextStyle(color: Colors.black),
        ),
      ),
      body: Column(
        children: [
          const Padding(
            padding: EdgeInsets.symmetric(
              horizontal: 35.0,
              vertical: 35.0,
            ),
            child: Text(
              "How much do you want to fund your wallet with",
              textAlign: TextAlign.center,
              style: TextStyle(
                color: Colors.blue,
                fontWeight: FontWeight.w700,
                fontSize: 18,
              ),
            ),
          ),
          Text(
            "₦${controller.text}",
            key: const Key('amtKey'),
            textAlign: TextAlign.center,
            style: const TextStyle(
              color: Colors.blue,
              fontWeight: FontWeight.w700,
              fontSize: 48,
            ),
          ),
          const SizedBox(height: 80),
          CustomKeyBoard(
            controller: controller,
            pinTheme: PinTheme(
              textColor: Colors.red,
              keysColor: Colors.blue,
            ),
            maxLength: 4,
          ),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 30),
            child: GestureDetector(
              onTap: () {},
              child: Container(
                height: 50,
                color: Colors.blue,
                child: const Center(
                  child: Text(
                    "Proceed",
                    style: TextStyle(fontSize: 14),
                  ),
                ),
              ),
            ),
          ),
          SizedBox(
            height: MediaQuery.of(context).padding.bottom,
          )
        ],
      ),
    );
  }
}

PIN验证页面(PinAuthScreen)

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

  @override
  State<PinAuthScreen> createState() => _PinAuthScreenState();
}

class _PinAuthScreenState extends State<PinAuthScreen> {
  TextEditingController controller = TextEditingController();
  PinTheme pinTheme = PinTheme(
    keysColor: Colors.white,
  );

  @override
  void initState() {
    super.initState();
    controller.addListener(() {
      setState(() {});
    });
  }

  @override
  void dispose() {
    controller.removeListener(() {
      setState(() {});
    });
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.green,
      body: SafeArea(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Padding(
              padding: EdgeInsets.symmetric(
                horizontal: 35.0,
                vertical: 35.0,
              ),
              child: Text(
                "Enter PIN",
                style: TextStyle(
                  fontSize: 30,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
            const SizedBox(
              height: 5,
            ),
            const Text(
              "Please enter your pin to continue",
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.normal,
              ),
            ),
            const SizedBox(
              height: 40,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                for (int i = 0; i < 4; i++)
                  PinCodeField(
                    key: Key('pinField$i'),
                    pin: controller.text,
                    pinCodeFieldIndex: i,
                    theme: pinTheme,
                  ),
              ],
            ),
            const SizedBox(height: 80),
            CustomKeyBoard(
              controller: controller,
              pinTheme: pinTheme,
              specialKey: Icon(
                Icons.fingerprint,
                key: const Key('fingerprint'),
                color: pinTheme.keysColor,
                size: 50,
              ),
              specialKeyOnTap: () {
                if (kDebugMode) {
                  print('fingerprint');
                }
              },
              maxLength: 4,
            ),
            TextButton(
              onPressed: () {
                setState(() {
                  controller.clear();
                });
              },
              child: const Text('Clear Pin'),
            ),
            SizedBox(
              height: MediaQuery.of(context).padding.bottom,
            )
          ],
        ),
      ),
    );
  }
}

以上就是关于custom_pin_screen插件的基本介绍以及如何在项目中使用的详细说明。如果您有任何问题或需要进一步的帮助,请随时参考官方文档或者提交issue给开发者团队。希望这些信息对您有所帮助!


更多关于Flutter自定义引脚屏幕插件custom_pin_screen的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter自定义引脚屏幕插件custom_pin_screen的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,我可以为你提供一个关于如何使用 custom_pin_screen 插件的示例代码。custom_pin_screen 是一个用于 Flutter 的强大插件,允许你创建自定义的引脚(PIN)屏幕,常用于身份验证等场景。

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

dependencies:
  flutter:
    sdk: flutter
  custom_pin_screen: ^2.0.0  # 请检查最新版本号

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

以下是一个简单的示例代码,展示了如何使用 custom_pin_screen 创建一个自定义的引脚屏幕:

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

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

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

class PinScreenPage extends StatefulWidget {
  @override
  _PinScreenPageState createState() => _PinScreenPageState();
}

class _PinScreenPageState extends State<PinScreenPage> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final List<Widget> _pinWidgets = List.generate(6, (index) => TextFormField());
  String? _pin;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Custom Pin Screen Example'),
      ),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Form(
            key: _formKey,
            child: CustomPinScreen(
              length: 6,
              pinTheme: PinTheme(
                shape: PinCodeFieldShape.box,
                borderRadius: BorderRadius.circular(10),
                fieldWidth: 50,
                fieldHeight: 60,
                activeColor: Colors.blue,
                inactiveColor: Colors.grey[300]!,
                inactiveFillColor: Colors.white,
                selectedColor: Colors.blueAccent,
                animationType: AnimationType.fade,
                activeFillColor: Colors.white,
              ),
              animationDuration: Duration(milliseconds: 300),
              backgroundColor: Colors.white,
              selectorColor: Colors.blueAccent,
              appContext: context,
              keyboardType: TextInputType.number,
              textStyle: TextStyle(fontSize: 20),
              onCompleted: (pin) {
                setState(() {
                  _pin = pin;
                });
                // Handle the pin completion here, e.g., validate or submit
                print('Completed PIN: $_pin');
              },
              onChanged: (pin) {
                // Handle pin change if needed
                print('Current PIN: $pin');
              },
              beforeTextPaste: (text) {
                // Optional: Handle text paste before it is pasted
                // Return null to cancel paste, otherwise return modified text
                return text.replaceAll(RegExp(r'[^0-9]'), '');
              },
            ),
          ),
        ),
      ),
    );
  }
}

代码说明:

  1. 依赖导入

    • 导入 flutter/material.dartcustom_pin_screen/custom_pin_screen.dart
  2. 主函数

    • MyApp 类是应用的根组件,设置了应用的主题和主页。
  3. PinScreenPage

    • PinScreenPage 是一个有状态的组件,用于管理引脚屏幕的状态。
    • _formKey 是一个全局键,用于表单验证(虽然在这个示例中未使用验证)。
    • _pinWidgets 是一个用于生成 TextFormField 的列表(尽管在这个示例中未使用)。
    • _pin 是一个用于存储用户输入的引脚字符串。
  4. 构建方法

    • 使用 ScaffoldAppBar 创建页面布局。
    • 使用 FormCustomPinScreen 创建引脚输入屏幕。
    • CustomPinScreen 的参数配置包括引脚长度、主题、动画持续时间、背景颜色、选择器颜色、键盘类型、文本样式等。
    • onCompleted 回调在引脚输入完成时触发,用于处理引脚(例如验证或提交)。
    • onChanged 回调在引脚输入变化时触发,可用于实时显示当前输入的引脚。
    • beforeTextPaste 回调在文本粘贴前触发,可用于过滤非数字字符。

希望这个示例能帮助你理解如何使用 custom_pin_screen 插件创建自定义的引脚屏幕。如果有任何进一步的问题,请随时提问!

回到顶部