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

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

该插件简化了具有自定义设计的一次性密码(OTP)字段的实现,并提供了高级验证功能。

安装

  1. 在你的 pubspec.yaml 文件中添加该包的最新版本(并运行 dart pub get):
dependencies:
  otp_form_field: ^0.0.3
  1. 导入该包并在你的 Flutter 应用中使用它。
import 'package:otp_form_field/otp_form_field.dart';

示例

有许多属性可以帮助你修改 OTP 字段:

  • length
  • assignOtp
  • onChange
  • onComplete
  • isEditable
  • otpDecoration -> OtpDecoration( . . 它包含其他属性,可以用来自定义 OtpDecoration 数据 )
  • style
  • width
  • height
  • alignContentByPadding
  • enableAutoValidation
  • spaceBetweenFields
  • onTimeOut
  • resendOtpAllFeatures -> ResendOtpAllFeatures( . . 它包含其他属性,可以用来自定义 ResendOtpAllFeatures 数据 )
  • margin
  • errorMessageMargin
  • timerCountMargin

示例代码

class OtpScreen extends StatelessWidget {  
  const OtpScreen({Key? key}) : super(key: key);  
  
  [@override](/user/override)  
  Widget build(BuildContext context) {  
    return Scaffold(  
      body: Center(  
        child: OtpFormField(
          width: 40,
          height: 40,
          spaceBetweenFields: 10,
          resendOtpAllFeatures: ResendOtpAllFeatures(
            timeOutDuration: 10,
          ),
          otpDecoration: OtpDecoration(
            fieldFocusErrorBorderColor: Colors.blue.shade300,
            fieldFocusBorderColor: Colors.green.shade200,
            fieldErrorBorderColor: Colors.transparent,
            fieldsColor: [Colors.red.shade50, Colors.green.shade50, Colors.brown.shade50, Colors.blue.shade50],
          ),
          length: 5,
          onChange: (value) {
            debugPrint("onChangeOTP>>$value");
          },
          onComplete: (onChangeOTP) {
            debugPrint("on complete>>$onChangeOTP");
          },
          onTimeOut: (isTimeOut) {
            debugPrint("on isTimeOut>>$isTimeOut");
          },
        ),
      ),  
    );  
  }  
}

另一个示例代码

class OtpScreen extends StatelessWidget {  
  const OtpScreen({Key? key}) : super(key: key);  
  
  [@override](/user/override)  
  Widget build(BuildContext context) {  
    return Scaffold(  
      body: Center(  
        child: OtpFormField(
          width: 40,
          height: 40,
          spaceBetweenFields: 10,
          resendOtpAllFeatures: ResendOtpAllFeatures(
            timeOutDuration: 10,
          ),
          otpDecoration: OtpDecoration(
            fieldFocusErrorBorderColor: Colors.blue.shade300,
            fieldFocusBorderColor: Colors.green.shade200,
            fieldErrorBorderColor: Colors.transparent,
            fieldsColor: [Colors.red.shade500, Colors.green.shade500, Colors.brown.shade500, Colors.blue.shade500],
            isFieldColorSelected: true,
          ),
          length: 5,
          onChange: (value) {
            debugPrint("onChangeOTP>>$value");
          },
          onComplete: (onChangeOTP) {
            debugPrint("on complete>>$onChangeOTP");
          },
          onTimeOut: (isTimeOut) {
            debugPrint("on isTimeOut>>$isTimeOut");
          },
        ),
      ),  
    );  
  }  
}

更多示例代码

class OtpScreen extends StatelessWidget {  
  const OtpScreen({Key? key}) : super(key: key);  
  
  [@override](/user/override)  
  Widget build(BuildContext context) {  
    return Scaffold(  
      body: Center(  
        child: OtpFormField(
          width: 40,
          height: 40,
          spaceBetweenFields: 10,
          resendOtpAllFeatures: ResendOtpAllFeatures(
            timeOutDuration: 10,
          ),
          otpDecoration: OtpDecoration(
            errorValidationMsg: "Invalid Otp!",
            fieldFocusErrorBorderColor: Colors.blue.shade300,
            fieldFocusBorderColor: Colors.blue.shade200,
            fieldErrorBorderColor: Colors.transparent,
            fieldsColor: [
              Colors.blue.shade50,
            ],
            // isFieldColorSelected: true,
          ),
          length: 5,
          onChange: (value) {
            debugPrint("onChangeOTP>>$value");
          },
          onComplete: (onChangeOTP) {
            debugPrint("on complete>>$onChangeOTP");
          },
          onTimeOut: (isTimeOut) {
            debugPrint("on isTimeOut>>$isTimeOut");
          },
        ),
      ),  
    );  
  }  
}

再一个示例代码

class OtpScreen extends StatelessWidget {  
  const OtpScreen({Key? key}) : super(key: key);  
  
  [@override](/user/override)  
  Widget build(BuildContext context) {  
    return Scaffold(  
      body: Center(  
        child: OTPFormField(
          width: 40,
          height: 40,
          spaceBetweenFields: 10,
          resendOtpAllFeatures: ResendOtpAllFeatures(
            timeOutDuration: 60,
          ),
          otpDecoration: OtpDecoration(
            errorValidationMsg: "Invalid Otp!",
            fieldFocusErrorBorderColor: Colors.blue.shade300,
            fieldFocusBorderColor: Colors.blue.shade200,
            fieldErrorBorderColor: Colors.transparent,
            fieldsColor: [
              Colors.blue.shade500,
            ],
            isFieldColorSelected: true,
          ),
          length: 5,
          onChange: (value) {
            debugPrint("onChangeOTP>>$value");
          },
          onComplete: (onChangeOTP) {
            debugPrint("on complete>>$onChangeOTP");
          },
          onTimeOut: (isTimeOut) {
            debugPrint("on isTimeOut>>$isTimeOut");
          },
        ),
      ),  
    );  
  }  
}

最后一个示例代码

class OtpScreen extends StatelessWidget {  
  const OtpScreen({Key? key}) : super(key: key);  
  
  [@override](/user/override)  
  Widget build(BuildContext context) {  
    return Scaffold(  
      body: Center(  
        child:OTPFormField(
          width: 40,
          height: 40,
          spaceBetweenFields: 10,
          resendOtpAllFeatures: ResendOtpAllFeatures(
            timeOutDuration: 60,
          ),
          otpDecoration: OtpDecoration(
            errorValidationMsg: "Invalid Otp!",
            fieldFocusErrorBorderColor: Colors.blue.shade300,
            fieldFocusBorderColor: Colors.blue.shade200,
            fieldErrorBorderColor: Colors.transparent,
            isFieldColorSelected: true,
          ),
          length: 5,
          onChange: (value) {
            debugPrint("onChangeOTP>>$value");
          },
          onComplete: (onChangeOTP) {
            debugPrint("on complete>>$onChangeOTP");
          },
          onTimeOut: (isTimeOut) {
            debugPrint("on isTimeOut>>$isTimeOut");
          },
        ),
      ),  
    );  
  }  
}

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

1 回复

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


当然,以下是如何在Flutter应用中使用otp_form_field插件来实现一次性密码(OTP)输入的一个示例代码案例。otp_form_field是一个方便的插件,用于创建OTP输入字段,通常用于验证码输入界面。

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

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

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

接下来,在你的Dart文件中使用OTPFormField来创建OTP输入字段。以下是一个完整的示例:

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

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

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

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

class _OTPScreenState extends State<OTPScreen> {
  final _controller = TextEditingController();
  final _focusNode = FocusNode();
  String? _otpResult;

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

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

  @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>[
            OTPFormField(
              controller: _controller,
              focusNode: _focusNode,
              length: 6,  // OTP长度
              width: 50.0,
              height: 50.0,
              decoration: InputDecoration(
                border: OutlineInputBorder(),
              ),
              onCompleted: _onCompleted,
              style: TextStyle(fontSize: 24),
              fieldStyle: TextStyle(fontSize: 24, color: Colors.black),
              autoFocus: true,
            ),
            SizedBox(height: 20),
            if (_otpResult != null)
              Text(
                'OTP Entered: $_otpResult',
                style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
              ),
          ],
        ),
      ),
    );
  }
}

代码说明:

  1. 依赖导入:首先导入flutter/material.dartotp_form_field/otp_form_field.dart
  2. 主应用:创建一个MyApp类,它包含一个OTPScreen作为首页。
  3. OTP屏幕OTPScreen是一个有状态的组件,包含一个文本编辑控制器和一个焦点节点。
  4. OTP输入字段:使用OTPFormField来创建OTP输入字段。配置字段的长度、宽度、高度、装饰、样式等。
  5. 完成回调:当用户完成OTP输入时,触发_onCompleted回调,并在这里处理OTP。
  6. 显示结果:如果OTP已经输入,显示输入的OTP。

运行这个代码,你会看到一个简单的OTP输入界面。用户可以逐个输入数字,当所有数字输入完毕后,_onCompleted回调会被触发,你可以在回调中处理OTP的验证逻辑。

回到顶部