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

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

phone_form_field_plus 是一个轻量级的 Flutter 电话号码文本字段。

开始使用

安装

pubspec.yaml 文件中添加依赖:

phone_form_field_plus: <latest_version>

示例代码

以下是一个完整的示例代码,展示了如何在 Flutter 应用程序中使用 phone_form_field_plus 插件。

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

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

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

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

class _MyHomePageState extends State<MyHomePage> {
  // 初始化电话号码控制器
  ValueNotifier<PhoneNumber> _phoneCtrl = ValueNotifier(PhoneNumber('', Country.isoCode("US")));

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Phone Form Field Demo"),
      ),
      body: Center(
        child: Container(
          padding: EdgeInsets.all(16),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              SizedBox(
                height: 32,
              ),
              // 使用 PhoneFormField 组件
              PhoneFormField(
                decoration: InputDecoration(
                    labelText: "Phone Number", border: OutlineInputBorder()),
                controller: _phoneCtrl,
              ),
              SizedBox(
                height: 32,
              ),
              // 提交按钮
              ElevatedButton(
                  onPressed: () {
                    setState(() {});
                  },
                  child: Text('Submit')),
              SizedBox(
                height: 32,
              ),
              // 显示当前输入的电话号码
              ValueListenableBuilder(
                  valueListenable: _phoneCtrl,
                  builder: (context, PhoneNumber phoneNumber, _) =>
                      Text("$phoneNumber")),
            ],
          ),
        ),
      ),
    );
  }
}

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

1 回复

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


phone_form_field_plus 是一个用于 Flutter 的插件,专门用于处理电话号码的输入和验证。它提供了一个美观的电话号码输入框,支持国际电话号码的格式化和验证。以下是如何在 Flutter 项目中使用 phone_form_field_plus 插件的详细步骤:

1. 添加依赖

首先,在 pubspec.yaml 文件中添加 phone_form_field_plus 插件的依赖:

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

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

2. 导入插件

在需要使用 phone_form_field_plus 的 Dart 文件中导入插件:

import 'package:phone_form_field_plus/phone_form_field_plus.dart';

3. 使用 PhoneFormField

PhoneFormField 是一个可以在表单中使用的 Widget,它允许用户输入电话号码并自动进行格式化。

class PhoneInputPage extends StatelessWidget {
  final _formKey = GlobalKey<FormState>();
  final _phoneController = PhoneController(null);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Phone Input Example'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: Column(
            children: [
              PhoneFormField(
                controller: _phoneController,
                decoration: InputDecoration(
                  labelText: 'Phone Number',
                  border: OutlineInputBorder(),
                ),
                validator: PhoneValidator.validMobile(), // 验证电话号码
                isCountryButtonPersistent: true,
                defaultCountry: IsoCode.US, // 默认国家
                onChanged: (phone) {
                  print('Phone number changed: $phone');
                },
              ),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: () {
                  if (_formKey.currentState!.validate()) {
                    // 表单验证通过
                    print('Valid phone number: ${_phoneController.value}');
                  } else {
                    // 表单验证失败
                    print('Invalid phone number');
                  }
                },
                child: Text('Submit'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

4. 参数说明

  • controller: 用于控制电话号码输入的 PhoneController
  • decoration: 用于自定义输入框的装饰,如标签、边框等。
  • validator: 用于验证电话号码的 PhoneValidatorPhoneValidator.validMobile() 用于验证手机号码。
  • isCountryButtonPersistent: 是否持久显示国家选择按钮。
  • defaultCountry: 默认的国家代码,如 IsoCode.US 表示美国。
  • onChanged: 当电话号码发生变化时触发的回调函数。

5. 验证电话号码

PhoneValidator 提供了多种验证方法,例如:

  • PhoneValidator.validMobile(): 验证是否为有效的手机号码。
  • PhoneValidator.validFixedLine(): 验证是否为有效的固定电话号码。

6. 获取电话号码

通过 PhoneController 可以获取用户输入的电话号码:

PhoneNumber phoneNumber = _phoneController.value;
print('Phone number: ${phoneNumber.international}');
回到顶部