搜尋套件、儲存庫與 APP 分類

otp_text_field 封面
套件詳情v1.1.5

otp_text_field

一個 Flutter 套件,用於在您的應用程式中建立 OTP 文字欄位小部件。

AndroidiOSWebmacOSWindowsLinux
近 30 天下載
3.4萬
喜歡數
278
Pub 分數
160

安裝套件

flutter pub add otp_text_field

套件介紹

根據套件公開資料產生的選型評估,僅供參考。

一個 Flutter 套件,提供可自訂的 OTP 文字欄位元件,方便輸入一次性密碼。支援輸入欄位間的順暢導航、自動焦點管理,以及簡潔現代的設計。非常適合需要 4 到 8 位數碼的驗證流程。此套件輕量級、文件完整,並相容於所有主要平台,包含 Android、iOS、Web、macOS、Windows 與 Linux。

適用情境

  • 用戶登入使用OTP
  • 雙因素驗證
  • 帳戶驗證
  • 無密碼登入
  • 安全表單輸入
  • 在引導流程中輸入代碼

主要特色

  • 欄位間的自動對焦
  • 可自訂文字欄位大小
  • 支援4到8位密碼
  • 跨平台相容性
  • 簡單 API 結合
  • 螢幕鍵盤處理

適合對象

  • 驗證畫面
  • 行動應用程式入門
  • 安全登入流程
  • 跨平台應用
  • 尋求簡單一次性密碼輸入的開發者

使用建議

  • 超出基本樣式的客製化功能有限
  • 無內建驗證邏輯
  • 需要手動處理提交
  • 不適用於動態程式碼長度
  • 不支援非數位輸入

原始 README

以下為關聯原始碼儲存庫的 README 原文快照,最新內容請造訪原始碼儲存庫。

OTP Text Field

A flutter package to create an OTP (One-Time Password) input widget in your application.


Stay tuned for the latest updates:


Pub Twitter

✨ Features

  • Underline or box style fields, fully customizable colors and borders
  • Smart focus handling — auto-advance on input, backspace jumps to the previous field
  • Paste & SMS autofill support — a pasted or autofilled code is distributed across the fields
  • Programmatic control via OtpFieldController (set, clear, focus)
  • Obscure text support for sensitive PINs
  • Error state styling with a single flag
  • Always renders left-to-right, even in RTL locales
  • Accessibility labels for every digit field

📱 Screenshots

From the gallery of designs in the example app:


⚙️ Installation

Add the package to your pubspec.yaml:

dependencies:
  otp_text_field: ^1.1.5

Or install it from the command line:

flutter pub add otp_text_field

Then import it:

import 'package:otp_text_field/otp_text_field.dart';

The single import above exports everything (OTPTextField, OtpFieldController, OtpFieldStyle, FieldStyle). You can also import otp_field.dart, otp_field_style.dart, and style.dart individually if you prefer.

🚀 Quick Start

OTPTextField(
  length: 5,
  width: MediaQuery.of(context).size.width,
  fieldWidth: 80,
  style: TextStyle(fontSize: 17),
  textFieldAlignment: MainAxisAlignment.spaceAround,
  fieldStyle: FieldStyle.underline,
  onChanged: (pin) {
    print("Changed: " + pin);
  },
  onCompleted: (pin) {
    print("Completed: " + pin);
  },
),
  • onChanged fires on every edit with the current (possibly partial) pin.
  • onCompleted fires once every field is filled, with the full pin.

👨‍💻 Usage

Box style with custom colors
OTPTextField(
  length: 4,
  width: MediaQuery.of(context).size.width,
  fieldWidth: 56,
  fieldStyle: FieldStyle.box,
  outlineBorderRadius: 12,
  otpFieldStyle: OtpFieldStyle(
    backgroundColor: Colors.grey.shade100,
    borderColor: Colors.grey,
    focusBorderColor: Colors.deepPurple,
  ),
  style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
  onCompleted: (pin) => verifyOtp(pin),
),
Controlling the field programmatically

Attach an OtpFieldController to clear, prefill, or focus the fields from your own code — for example after a failed verification or a "resend code" tap:

final OtpFieldController otpController = OtpFieldController();

OTPTextField(
  controller: otpController,
  length: 4,
  onCompleted: (pin) => verifyOtp(pin),
),

// Later:
otpController.clear();                        // clear all fields, focus the first one
otpController.set(['1', '2', '3', '4']);      // prefill the whole pin
otpController.setValue('7', 2);               // set a single field (position 2)
otpController.setFocus(0);                    // move focus to a field

The controller must be attached to a built OTPTextField before calling its methods, otherwise a StateError is thrown. set() expects exactly length entries.

SMS code autofill

Pass AutofillHints.oneTimeCode to enable one-tap SMS code autofill on iOS and Android. The autofilled code is automatically spread across the fields:

OTPTextField(
  length: 6,
  autofillHints: [AutofillHints.oneTimeCode],
  onCompleted: (pin) => verifyOtp(pin),
),
Showing an error state

Set hasError: true to render every field with the errorBorderColor — for example after the server rejects the code:

OTPTextField(
  length: 4,
  hasError: _otpInvalid,
  otpFieldStyle: OtpFieldStyle(errorBorderColor: Colors.red),
  onChanged: (_) => setState(() => _otpInvalid = false),
  onCompleted: (pin) => verifyOtp(pin),
),
Obscured PIN entry
OTPTextField(
  length: 4,
  obscureText: true,
  onCompleted: (pin) => verifyPin(pin),
),

For more designs, check out the example app.

📋 Parameters

OTPTextField
Parameter Type Default Description
length int 4 Number of OTP fields. Must be greater than 1.
width double 10 Total width of the widget. Usually set to the available screen width.
fieldWidth double 30 Width of each individual field.
spaceBetween double 0 Horizontal space between fields, in addition to textFieldAlignment spacing.
controller OtpFieldController? null Controller to clear, prefill, or focus the fields programmatically.
fieldStyle FieldStyle FieldStyle.underline Field shape: FieldStyle.underline or FieldStyle.box.
outlineBorderRadius double 10 Corner radius of the border when fieldStyle is FieldStyle.box.
otpFieldStyle OtpFieldStyle? OtpFieldStyle() Colors for background and borders — see OtpFieldStyle.
style TextStyle TextStyle() Text style of the digits being entered.
contentPadding EdgeInsets EdgeInsets.symmetric(horizontal: 4, vertical: 8) Content padding inside each field.
isDense bool false Whether the fields use a denser, vertically compact layout.
textFieldAlignment MainAxisAlignment MainAxisAlignment.spaceBetween How the fields are distributed across width.
keyboardType TextInputType TextInputType.number Keyboard shown while typing.
textCapitalization TextCapitalization TextCapitalization.none Capitalization behavior for alphanumeric codes.
inputFormatter List<TextInputFormatter>? null Input formatters applied while typing and to pasted text.
obscureText bool false Hide the entered characters (for sensitive PINs).
showCursor bool false Show the cursor and selection visuals. By default the focused field is indicated only by its focused border.
hasError bool false Render all fields with the error border color.
autofocus bool false Focus the first field automatically when the widget is built.
enabled bool true Whether the fields accept user input.
autofillHints List<String>? null Autofill hints applied to the first field. Use [AutofillHints.oneTimeCode] for SMS autofill.
redirectFocusToFirstEmptyField bool true When a later field gains focus while earlier ones are empty, redirect focus to the first empty field so the code is always entered contiguously. Set to false to let users type into any box.
onChanged ValueChanged<String>? null Called with the current pin whenever it changes.
onCompleted ValueChanged<String>? null Called with the full pin once every field is filled.
OtpFieldStyle
Parameter Type Default Description
backgroundColor Color Colors.transparent Fill color of each field.
borderColor Color Colors.black26 Default border color.
enabledBorderColor Color Colors.black26 Border color when the field is enabled but not focused.
focusBorderColor Color Colors.blue Border color of the focused field.
disabledBorderColor Color Colors.grey Border color when enabled is false.
errorBorderColor Color Colors.red Border color when hasError is true.
OtpFieldController
Method Description
clear() Clears all fields, focuses the first one, and calls onChanged with an empty string.
set(List<String> pin) Sets the whole pin. The list length must equal length; throws ArgumentError otherwise. Calls onChanged, and onCompleted if no entry is empty.
setValue(String value, int position) Sets a single field at position (0-based). Calls onChanged.
setFocus(int position) Moves focus to the field at position (0-based).

📝 Behavior notes

  • Focus flow: typing a digit moves focus to the next field; the keyboard is dismissed after the last one. Deleting a digit moves focus back. Pressing backspace on an already-empty field also jumps back.
  • Typing over a digit: focusing a filled field selects its content, so typing replaces the digit instead of appending to it.
  • Paste & autofill: a multi-character value (paste or SMS autofill) is filtered through your inputFormatters, distributed across the fields from the start, and any leftover fields are cleared.
  • RTL locales: the fields are always laid out left-to-right, since verification codes are read left-to-right.

🙍🏻‍♂️ Author

📄 License

OTP Text Field is released under the MIT license. See LICENSE for details.

所屬分類

原始碼儲存庫

使用此套件的專案

暫無相關資料。