Flutter电话号码输入插件my_phone_form_field的使用

Flutter电话号码输入插件my_phone_form_field的使用

特性

  • 完全跨平台,这是一个纯 Dart 包/依赖项
  • 国际化支持
  • 按地区格式化电话号码
  • 电话号码验证(内置验证器适用于主要用例)
  • 支持自动填充和复制粘贴
  • 扩展了 Flutter 的 FormField
  • 使用 dart phone_numbers_parser 进行解析

示例

演示页面可在 这里 查看。

使用

// 无需任何参数即可使用
MyPhoneFormField();

// 使用所有参数
MyPhoneFormField(
  key: Key('phone-field'),
  controller: null,     // 控制器与初始值不能同时设置
  initialValue: null,   // 可以不设置
  shouldFormat: true,   // 默认为 true
  defaultCountry: IsoCode.US, // 默认国家为美国
  decoration: InputDecoration(
    labelText: 'Phone',          // 默认为空
    border: OutlineInputBorder(), // 默认为 UnderlineInputBorder()
    // 其他装饰参数...
  ),
  validator: PhoneValidator.validMobile(),   // 验证器默认为 PhoneValidator.valid()
  isCountryChipPersistent: false, // 默认为 false
  isCountrySelectionEnabled: true, // 默认为 true
  countrySelectorNavigator: CountrySelectorNavigator.bottomSheet(),
  showFlagInInput: true,  // 默认为 true
  flagSize: 16,           // 默认为 16
  autofillHints: [AutofillHints.telephoneNumber], // 默认为 null
  enabled: true,          // 默认为 true
  autofocus: false,       // 默认为 false
  onSaved: (PhoneNumber p) => print('saved $p'),   // 默认为 null
  onChanged: (PhoneNumber p) => print('saved $p'), // 默认为 null
  // 其他文本框参数...
)

验证

内置验证器

  • 必填:PhoneValidator.required
  • 有效:PhoneValidator.valid(当未提供验证器时,默认值)
  • 有效的移动电话号码:PhoneValidator.validMobile
  • 有效的固定电话号码:PhoneValidator.validFixedLine
  • 有效的类型:PhoneValidator.validType
  • 有效的国家:PhoneValidator.validCountry
  • 无:PhoneValidator.none(可以用来禁用默认的有效验证)

验证器详情

  • 每个验证器都有一个可选的 errorText 属性,用于覆盖内置的本地化文本。
  • 大多数验证器都有一个可选的 allowEmpty(默认为 true)属性,防止将空字段标记为有效。如果需要不同的空字段文本,可以考虑使用组合验证器,其中第一个为 PhoneValidator.required

组合验证器

验证器可以是内置或自定义验证器的组合,使用 PhoneValidator.compose 方法。例如:

MyPhoneFormField(
  // ...
  validator: PhoneValidator.compose([
    // 验证器列表
    PhoneValidator.required(errorText: "You must enter a value"),
    PhoneValidator.validMobile(),
    // 其他验证器...
  ]),
)

注意:在组合验证器时,排序很重要,因为显示的第一个失败的验证器的错误信息。

国家选择器

以下是可以用于所有内置国家选择器的参数列表:

参数名称 默认值 描述
countries null 列表视图中可用的国家(省略时列出所有国家)
favorites null 要显示在列表顶部的国家代码列表,如 ['FR','UK']
addSeparator true 是否在收藏国家和其他国家之间添加分隔符。如果 favorites 参数为 null,则无效
showCountryCode true 是否显示国家拨号码作为列表项的副标题
sortCountries false 国家是否按字母顺序排列,如果为 false,则按 countries 属性的顺序显示(注意,收藏国家按提供的顺序列出,无论此参数的值如何)
noResultMessage null 当搜索结果为空时显示的消息(省略时使用默认本地化消息)

内置国家选择器

CountrySelectorNavigator.searchDelegate

打开对话框以选择国家。 无额外参数。

CountrySelectorNavigator.dialog

打开对话框以选择国家。 无额外参数。

CountrySelectorNavigator.bottomSheet

打开展开到两个轴上所有可用空间的底部栏。 无额外参数。

CountrySelectorNavigator.modalBottomSheet

水平扩展的模态底部栏。 额外参数:

  • height (double, 默认为 null),允许确定底部栏的高度,省略时将扩展到所有可用高度。

CountrySelectorNavigator.draggableBottomSheet

可从最小到当前可用最大高度拖动的水平扩展模态底部栏。 内部使用 DraggableScrollableSheet Flutter 小部件。 额外参数:

  • initialChildSize (double, 默认为 0.5),打开时使用的当前可用高度的比例因子
  • minChildSize (double, 默认为 0.25),当前可用高度的最大比例因子
  • maxChildSize (double, 默认为 0.75),当前可用高度的最小比例因子
  • borderRadius (BorderRadiusGeometry, 默认为 16px 圆角半径在左上角和右上角)

自定义国家选择器导航器

可以通过创建实现 CountrySelectorNavigator 接口的类来自定义国家选择器。 它有一个必需的方法 navigate,预期返回所选国家:

class CustomCountrySelectorNavigator implements CountrySelectorNavigator {
  Future<Country?> navigate(BuildContext context) {
    // 向用户请求国家并返回相关的 `Country` 类
  }
}

// 使用
MyPhoneFormField(
  // ...
  selectorNavigator: CustomCountrySelectorNavigator(),
  // ...
)

国际化

包含委托:

return MaterialApp(
  localizationsDelegates: [
    GlobalMaterialLocalizations.delegate,
    PhoneFieldLocalization.delegate
  ],
  supportedLocales: [
    const Locale('en', ''),
    const Locale('es', ''),
    const Locale('fr', ''),
    const Locale('ru', ''),
    const Locale('uz', ''),
    const Locale('uk', ''),
    // ...
  ],
);

更多关于Flutter电话号码输入插件my_phone_form_field的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

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


my_phone_form_field 是一个用于 Flutter 的电话号码输入插件,它提供了更便捷的方式来处理电话号码的输入和格式化。使用这个插件,你可以轻松地在应用中集成电话号码输入功能,并支持国际电话号码格式。

安装

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

dependencies:
  flutter:
    sdk: flutter
  my_phone_form_field: ^latest_version

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

基本用法

以下是一个简单的使用示例:

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

class PhoneInputScreen extends StatefulWidget {
  [@override](/user/override)
  _PhoneInputScreenState createState() => _PhoneInputScreenState();
}

class _PhoneInputScreenState extends State<PhoneInputScreen> {
  final _formKey = GlobalKey<FormState>();
  PhoneNumber _phoneNumber = PhoneNumber(isoCode: 'US');

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Phone Number Input'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: Column(
            children: [
              MyPhoneFormField(
                initialValue: _phoneNumber,
                onChanged: (PhoneNumber? phoneNumber) {
                  setState(() {
                    _phoneNumber = phoneNumber!;
                  });
                },
                validator: (PhoneNumber? phoneNumber) {
                  if (phoneNumber == null || phoneNumber.number.isEmpty) {
                    return 'Please enter a valid phone number';
                  }
                  return null;
                },
              ),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: () {
                  if (_formKey.currentState!.validate()) {
                    // 处理电话号码
                    print('Phone Number: ${_phoneNumber.completeNumber}');
                  }
                },
                child: Text('Submit'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
回到顶部