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

发布于 1周前 作者 htzhanglong 来自 Flutter

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

Phone TextField Plus 是一个 Flutter 插件,它允许你解析、验证、格式化国际电话号码,并支持基于 phone_text_field 包的本地化。

Demo 动图

image

安装

  1. 在你的项目 pubspec.yaml 文件中添加以下依赖:

    dependencies:
      phone_text_field_plus: any
    
  2. 使用 IDE 的图形界面或通过命令行获取包:

    $ pub get
    
  3. 导入 phone_text_field_plus.dart 文件到你的应用中:

    import 'package:phone_text_field_plus/phone_text_field_plus.dart';
    

特性

  • 验证电话号码
  • 选择国家代码
  • 支持阿拉伯语、英语和法语
  • 添加文本控制器

使用

默认小部件

PhoneTextField(
    onChanged: (value) {},
),

自定义文本样式

PhoneTextField(
  locale: const Locale('en'),
  decoration: const InputDecoration(
    filled: true,
    contentPadding: EdgeInsets.zero,
    enabledBorder: OutlineInputBorder(
      borderRadius: BorderRadius.all(Radius.circular(10.0)),
      borderSide: BorderSide(),
    ),
    focusedBorder: OutlineInputBorder(
      borderRadius: BorderRadius.all(Radius.circular(10.0)),
      borderSide: BorderSide(),
    ),
    prefixIcon: Icon(Icons.phone),
    labelText: "Phone number",
  ),
  searchFieldInputDecoration: const InputDecoration(
    filled: true,
    enabledBorder: OutlineInputBorder(
      borderRadius: BorderRadius.all(Radius.circular(10.0)),
      borderSide: BorderSide(),
    ),
    focusedBorder: OutlineInputBorder(
      borderRadius: BorderRadius.all(Radius.circular(10.0)),
      borderSide: BorderSide(),
    ),
    suffixIcon: Icon(Icons.search),
    hintText: "Search country",
  ),
  initialCountryCode: "AE",
  onChanged: (phone) {
    debugPrint(phone.completeNumber);
  },
),

阿拉伯语风格

PhoneTextField(
  locale: const Locale('ar'),
  decoration: const InputDecoration(
    filled: true,
    contentPadding: EdgeInsets.zero,
    enabledBorder: OutlineInputBorder(
      borderRadius: BorderRadius.all(Radius.circular(10.0)),
      borderSide: BorderSide(),
    ),
    focusedBorder: OutlineInputBorder(
      borderRadius: BorderRadius.all(Radius.circular(10.0)),
      borderSide: BorderSide(),
    ),
    prefixIcon: Icon(Icons.phone),
    labelText: "رقم الهاتف",
  ),
  searchFieldInputDecoration: const InputDecoration(
    filled: true,
    enabledBorder: OutlineInputBorder(
      borderRadius: BorderRadius.all(Radius.circular(10.0)),
      borderSide: BorderSide(),
    ),
    focusedBorder: OutlineInputBorder(
      borderRadius: BorderRadius.all(Radius.circular(10.0)),
      borderSide: BorderSide(),
    ),
    suffixIcon: Icon(Icons.search),
    hintText: "بحث عن بالاسم او الرمز",
  ),
  dialogTitle: "اختر الدوله",
  initialCountryCode: "AE",
  onChanged: (phone) {
    debugPrint(phone.completeNumber);
  },
),

截图

本地化(英文) 本地化(英文)

本地化(阿拉伯文) 本地化(阿拉伯文)

贡献

主要贡献者

Mohamed Salem Mohamed Abdo Elnashar

示例代码

import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:phone_text_field_plus/phone_text_field_plus.dart';

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

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      locale: const Locale('en'),
      localizationsDelegates: const [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: const [
        Locale('ar'),
        Locale('en'),
        Locale('fr'),
      ],
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

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

class _MyHomePageState extends State<MyHomePage> {
  TextEditingController textController = TextEditingController();

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Phone Text Field"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(15),
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  const Text(
                    "Basic Widget",
                    textScaler: TextScaler.linear(1.5),
                  ),
                  PhoneTextField(
                    initialValue: '+2001090718223',
                    initialCountryCode: '+971',
                    countryViewOptions: CountryViewOptions.countryCodeOnly,
                    showCountryCodeAsIcon: true,
                    onChanged: (value) {},
                  ),
                ],
              ),
              Column(
                children: [
                  const Text(
                    "Decoration Widget",
                    textScaler: TextScaler.linear(1.5),
                  ),
                  const SizedBox(
                    height: 20,
                  ),
                  PhoneTextField(
                    controller: textController,
                    locale: const Locale('en'),
                    decoration: const InputDecoration(
                      filled: true,
                      contentPadding: EdgeInsets.zero,
                      enabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(10.0)),
                        borderSide: BorderSide(),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(10.0)),
                        borderSide: BorderSide(),
                      ),
                      prefixIcon: Icon(Icons.phone),
                      labelText: "Phone number",
                    ),
                    searchFieldInputDecoration: const InputDecoration(
                      filled: true,
                      enabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(10.0)),
                        borderSide: BorderSide(),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(10.0)),
                        borderSide: BorderSide(),
                      ),
                      suffixIcon: Icon(Icons.search),
                      hintText: "Search country",
                    ),
                    initialCountryCode: "AE",
                    onChanged: (phone) {
                      debugPrint(phone.completeNumber);
                    },
                  ),
                  const SizedBox(
                    height: 20,
                  ),
                  ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.deepPurpleAccent,
                      foregroundColor: Colors.white,
                      padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 9),
                    ),
                    onPressed: () {
                      textController.clear();
                    },
                    child: const Text(
                      "Submit",
                      style: TextStyle(fontSize: 15),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

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

1 回复

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


当然,以下是关于如何在Flutter项目中使用phone_text_field_plus插件的一个示例代码案例。这个插件为电话号码输入提供了增强功能,如格式化、验证等。

首先,确保你的Flutter项目已经添加了phone_text_field_plus依赖。在pubspec.yaml文件中添加以下依赖:

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

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

接下来,在你的Dart文件中使用这个插件。以下是一个完整的示例,展示如何使用PhoneTextField

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'PhoneTextFieldPlus Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('PhoneTextFieldPlus Demo'),
        ),
        body: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Center(
            child: MyPhoneNumberForm(),
          ),
        ),
      ),
    );
  }
}

class MyPhoneNumberForm extends StatefulWidget {
  @override
  _MyPhoneNumberFormState createState() => _MyPhoneNumberFormState();
}

class _MyPhoneNumberFormState extends State<MyPhoneNumberForm> {
  final _formKey = GlobalKey<FormState>();
  String _phoneNumber = '';

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          PhoneTextFieldPlus(
            decoration: InputDecoration(
              labelText: 'Phone Number',
              border: OutlineInputBorder(),
            ),
            keyboardType: TextInputType.phone,
            initialSelection: TextSelection.collapsed(offset: -1),
            autoFormat: true,
            autoValidateMode: AutovalidateMode.onUserInteraction,
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'Phone number is required';
              }
              return null;
            },
            onChanged: (value) {
              setState(() {
                _phoneNumber = value;
              });
            },
          ),
          SizedBox(height: 20),
          ElevatedButton(
            onPressed: () {
              if (_formKey.currentState!.validate()) {
                // 处理验证通过的逻辑
                print('Validated phone number: $_phoneNumber');
              }
            },
            child: Text('Submit'),
          ),
        ],
      ),
    );
  }
}

在这个示例中:

  1. 我们创建了一个简单的Flutter应用,包含一个表单,表单中有一个PhoneTextFieldPlus字段。
  2. PhoneTextFieldPlus字段具有一些基本配置,如标签文本、边框、键盘类型等。
  3. 启用了自动格式化(autoFormat: true),这意味着当用户输入电话号码时,插件会自动将其格式化为适当的格式。
  4. 使用了一个简单的验证器来检查电话号码是否为空。
  5. 当表单验证通过时,打印出验证通过的电话号码。

这个示例展示了如何使用phone_text_field_plus插件进行电话号码输入、格式化和验证。你可以根据需要进一步自定义和扩展这个示例。

回到顶部