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

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

Flutter OTP Input

OTPInput小部件是一个可定制的Flutter小部件,允许用户通过一系列单独的文本字段输入一次性密码(OTP)。它提供了用于验证代码的交互式UI,包括可自定义的标题、副标题和错误消息等功能。该小部件还支持OTP长度配置、“重新发送”按钮以请求新代码,以及一个验证按钮。

创建者

@badiniibrahim

喜欢我的工作?请买杯咖啡支持我。感谢您的支持 ❤️

Buy Me A Coffee

截图

  • iOS Flexi Toast IOS

  • Android Flexi Toast Android

特性

  • 可定制的OTP长度:轻松调整OTP输入的字段数量。
  • 重新发送功能:当用户请求重新发送OTP时触发回调函数。
  • 错误处理:如果OTP不完整或无效,则显示错误消息。
  • 样式:可定制的文本样式、边框颜色和按钮样式。

开始使用

在你的 pubspec.yaml 文件中添加依赖项:

dependencies:
  ...
  flutter_otp_input: latest_version

完整示例

以下是一个完整的示例,展示了如何使用 OTPInput 小部件:

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'Flutter Demo',
      home: MyHomePage(title: ''),
    );
  }
}

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: OTPInput(
        length: 6, // 设置OTP长度为6
        onCompleted: (value) => print('OTP Completed: $value'), // 当OTP完成时调用
        onChanged: (value) => print('OTP Changed: $value'), // 当OTP改变时调用
        textStyle: const TextStyle(fontSize: 18, color: Colors.black), // 设置文本样式
        borderFieldColor: Colors.blue, // 设置边框颜色
        phoneNumber: "+33767567658", // 设置电话号码
        resendStyle: const TextStyle(
          fontSize: 14,
          color: Colors.black,
          fontWeight: FontWeight.bold,
        ), // 设置重新发送样式的文本
        onResend: () {
          print("Renvoi du code..."); // 当点击重新发送时调用
        },
        verifyButtonColor: Colors.blue, // 设置验证按钮背景色
        errorMessage: "Code OTP invalide", // 设置错误消息
        resendTextStyle: const TextStyle(
          color: Colors.blue,
          fontSize: 16,
          fontWeight: FontWeight.bold,
          decoration: TextDecoration.underline,
        ), // 设置重新发送文本的样式
      ),
    );
  }
}

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

1 回复

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


当然,以下是如何在Flutter项目中使用flutter_otp_input插件的一个示例代码案例。这个插件主要用于实现一次性密码(OTP)输入界面,通常用于短信验证码等场景。

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

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

然后运行flutter pub get来获取依赖。

接下来,你可以在你的Dart文件中使用这个插件。以下是一个完整的示例,展示如何使用flutter_otp_input来创建一个6位数的OTP输入界面:

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

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

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

class OTPInputScreen extends StatefulWidget {
  @override
  _OTPInputScreenState createState() => _OTPInputScreenState();
}

class _OTPInputScreenState extends State<OTPInputScreen> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final List<OtpWidget> otpWidgets = List.generate(6, (index) {
    return OtpWidget(
      width: (MediaQuery.of(context).size.width - 32) / 6,
      height: 50,
      decoration: BoxDecoration(
        border: Border.all(color: Colors.grey[300]!),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Center(
        child: Text(
          '',
          style: TextStyle(fontSize: 20),
        ),
      ),
    );
  });

  String? otpResult;

  void _submit() {
    if (_formKey.currentState!.validate()) {
      // 在这里处理OTP输入结果
      // 例如,可以获取到otpResult然后发送验证请求
      print('OTP: $otpResult');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('OTP Input Demo'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Form(
              key: _formKey,
              child: OTPInputField(
                length: 6,
                width: (MediaQuery.of(context).size.width - 32) / 6,
                height: 50,
                fieldStyle: TextStyle(fontSize: 20),
                onCompleted: (otp) {
                  setState(() {
                    otpResult = otp;
                  });
                },
                otpWidgets: otpWidgets,
              ),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _submit,
              child: Text('Submit OTP'),
            ),
          ],
        ),
      ),
    );
  }
}

代码解释:

  1. 依赖添加:在pubspec.yaml中添加flutter_otp_input依赖。
  2. OTP输入界面
    • 使用OTPInputField来创建一个6位的OTP输入字段。
    • otpWidgets列表定义了每个OTP输入框的样式。
    • onCompleted回调在OTP输入完成后被调用,并将OTP结果保存到otpResult变量中。
  3. 表单提交
    • 使用Form_formKey来管理表单状态。
    • 点击“Submit OTP”按钮时,调用_submit方法来处理OTP输入结果。

这个示例展示了如何使用flutter_otp_input插件来创建一个简单的OTP输入界面,并处理用户输入的OTP。你可以根据需要进一步自定义样式和功能。

回到顶部