Flutter一次性密码输入插件custom_otp_textfield的使用

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

Flutter一次性密码输入插件custom_otp_textfield的使用

特性

  • 支持任何尺寸设备的自定义一次性密码输入文本框
  • 支持自定义UI
  • 可以调整一次性密码的长度

开始使用

你需要提供文本框允许的最大宽度和文本编辑控制器。

使用方法

以下是custom_otp_textfield插件的使用示例:

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

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

  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final TextEditingController textEditingController = TextEditingController();

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("自定义一次性密码输入框演示", style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
        centerTitle: true,
      ),
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            CustomOTPTextField(
              deviceWidth: MediaQuery.of(context).size.width,
              textEditingController: textEditingController,
              boxSize: 70,
              inputBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(12),
                borderSide: BorderSide(color: Colors.lightBlueAccent, width: 5),
              ),
              cursorColor: Colors.blue,
              otpLength: 5,
              textStyle: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),
              spaceBetweenTextFields: 10,
              cursorHeight: 40,
            ),
            SizedBox(height: 60,),
            TextButton(
              style: TextButton.styleFrom(
                backgroundColor: Colors.lightBlueAccent,
                padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16)
              ),
              onPressed: () => ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("文本为: ${textEditingController.text}", style: TextStyle(fontSize: 15, fontWeight: FontWeight.bold)))),
              child: const Text("提交", style: TextStyle(fontSize: 20, fontWeight: FontWeight.w600, color: Colors.white)),
            )
          ],
        ),
      ),
    );
  }
}

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

1 回复

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


当然,以下是如何在Flutter项目中使用custom_otp_textfield插件来实现一次性密码(OTP)输入功能的示例代码。这个插件允许你创建一个美观且用户友好的OTP输入界面。

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

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

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

接下来,你可以在你的Dart文件中使用CustomOTPTextField组件。以下是一个完整的示例,展示如何在Flutter应用中实现OTP输入:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: OTPScreen(),
    );
  }
}

class OTPScreen extends StatefulWidget {
  @override
  _OTPScreenState createState() => _OTPScreenState();
}

class _OTPScreenState extends State<OTPScreen> {
  final List<FocusNode> _focusNodes = List.generate(6, (index) => FocusNode());
  final TextEditingController _controller = TextEditingController();
  String? otpResult;

  @override
  void dispose() {
    _focusNodes.forEach((node) => node.dispose());
    _controller.dispose();
    super.dispose();
  }

  void _onCompleted(String otp) {
    setState(() {
      otpResult = otp;
    });
    // 在这里处理OTP输入完成后的逻辑,比如发送OTP到服务器验证
    print("OTP entered: $otp");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('OTP Input Example'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            CustomOTPTextField(
              length: 6,
              width: 50,
              height: 60,
              fieldStyle: TextStyle(fontSize: 24),
              focusNodes: _focusNodes,
              controller: _controller,
              onCompleted: _onCompleted,
              decoration: BoxDecoration(
                border: Border.all(color: Colors.grey, width: 1),
                borderRadius: BorderRadius.circular(8),
              ),
              boxDecoration: [
                BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(8),
                ),
                BoxDecoration(
                  border: Border.all(
                    color: Colors.grey.withOpacity(0.5),
                    width: 1,
                  ),
                ),
              ],
              textFieldAlignment: MainAxisAlignment.spaceBetween,
            ),
            SizedBox(height: 20),
            otpResult != null
                ? Text(
                    'OTP Result: $otpResult',
                    style: TextStyle(fontSize: 20, color: Colors.green),
                  )
                : Container(),
          ],
        ),
      ),
    );
  }
}

代码解释

  1. 依赖导入

    import 'package:flutter/material.dart';
    import 'package:custom_otp_textfield/custom_otp_textfield.dart';
    
  2. OTP输入屏幕

    • OTPScreen是一个StatefulWidget,用于管理OTP输入的状态。
    • _OTPScreenState是其状态类,包含OTP输入逻辑。
  3. FocusNode和TextEditingController

    • 使用FocusNode列表来管理每个OTP输入框的焦点。
    • 使用TextEditingController来管理整个OTP输入过程。
  4. CustomOTPTextField

    • 配置CustomOTPTextField的参数,如长度、宽度、高度、样式等。
    • 设置onCompleted回调,当OTP输入完成时触发。
  5. UI布局

    • 使用Column布局来垂直排列OTP输入框和结果文本。
    • 使用SizedBox来添加间距。
  6. 处理OTP输入完成

    • _onCompleted回调中处理OTP输入完成后的逻辑,例如打印OTP结果或发送至服务器验证。

这个示例展示了如何使用custom_otp_textfield插件创建一个基本的OTP输入界面。你可以根据需要进一步自定义和扩展这个示例。

回到顶部