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

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

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

国际电话字段包

开发者:Kalybos Prosper Kokou Ahianyo

特性

这个自定义的Flutter TextFormField可以用来输入国际电话号码以及国家代码。你可以通过下拉菜单选择国家代码,并且在构建Flutter Web应用时可以修改国家标志的大小。

以下是插件的一些截图: 示例图片1 示例图片2 示例图片3 示例图片4

开始使用

要使用这个包,请运行以下命令:

flutter pub add flutter_phone_number_field

或者,将以下内容添加到你的pubspec.yaml文件中:

dependencies:
    flutter_phone_number_field: ^1.0.1

使用方法

只需创建一个FlutterPhoneNumberField小部件,并传递所需的参数:

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_phone_number_field/flutter_phone_number_field.dart';

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

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

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  GlobalKey<FormState> formKey = GlobalKey();

  FocusNode focusNode = FocusNode();
  // 这个小部件是应用程序的根。
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Phone Number Field Example'),
        ),
        body: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16.0),
          child: Form(
            key: formKey,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                FlutterPhoneNumberField(
                  focusNode: focusNode, // 焦点节点
                  initialCountryCode: "TG", // 初始国家代码
                  pickerDialogStyle: PickerDialogStyle(
                    countryFlagStyle: const TextStyle(fontSize: 17), // 国旗样式
                  ),
                  decoration: const InputDecoration(
                    hintText: 'Phone Number', // 提示文本
                    border: OutlineInputBorder( // 边框样式
                      borderSide: BorderSide(),
                    ),
                  ),
                  languageCode: "en", // 语言代码
                  onChanged: (phone) { // 当号码改变时
                    if (kDebugMode) {
                      print(phone.completeNumber); // 打印完整号码
                    }
                  },
                  onCountryChanged: (country) { // 当国家改变时
                    if (kDebugMode) {
                      print('Country changed to: ${country.name}'); // 打印国家名称
                    }
                  },
                ),
                const SizedBox(
                  height: 10,
                ),
                MaterialButton(
                  color: Theme.of(context).primaryColor, // 按钮颜色
                  textColor: Colors.white, // 文本颜色
                  onPressed: () {
                    formKey.currentState?.validate(); // 验证表单
                  },
                  child: const Text('Submit'), // 按钮文本
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

使用initialCountryCode设置初始国家代码。如果正在构建Flutter Web应用,则使用webCountryIconWidth设置国家标志宽度。

更新电话号码

要在更新页面上更新电话号码,需要显示之前获取的电话号码并传递给控制器。为此,请调用函数PhoneNumber.getNumber(String completeNumber)

更新页面示例(update_page.dart)

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_phone_number_field/flutter_phone_number_field.dart';

class UpdatePage extends StatefulWidget {
  final String name, email, phone;
  const UpdatePage({
    super.key,
    required this.name,
    required this.email,
    required this.phone,
  });

  [@override](/user/override)
  State<UpdatePage> createState() => _UpdatePageState();
}

class _UpdatePageState extends State<UpdatePage> {
  GlobalKey<FormState> formKey = GlobalKey();

  final TextEditingController phoneNumberController = TextEditingController();
  final TextEditingController nameController = TextEditingController();
  final TextEditingController emailController = TextEditingController();
  String? phoneNumber;

  [@override](/user/override)
  void initState() {
    setState(() {
      phoneNumberController.text = PhoneNumber.getNumber(widget.phone);
      nameController.text = widget.name;
      emailController.text = widget.email;
    });
    super.initState();
  }

  FocusNode focusNode = FocusNode();
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Update Phone Number Page'),
      ),
      body: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16.0),
        child: Form(
          key: formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              const SizedBox(height: 30),
               TextField(
                controller: nameController,
                decoration: const InputDecoration(
                  labelText: 'Name',
                  border: OutlineInputBorder(
                    borderSide: BorderSide(),
                  ),
                ),
              ),
              const SizedBox(
                height: 10,
              ),
               TextField(
                controller: emailController,
                decoration: const InputDecoration(
                  labelText: 'Email',
                  border: OutlineInputBorder(
                    borderSide: BorderSide(),
                  ),
                ),
              ),
              const SizedBox(
                height: 10,
              ),
              FlutterPhoneNumberField(
                controller: phoneNumberController,
                focusNode: focusNode,
                initialCountryCode: "TG",
                pickerDialogStyle: PickerDialogStyle(
                  countryFlagStyle: const TextStyle(fontSize: 17),
                ),
                decoration: const InputDecoration(
                  hintText: 'Phone Number',
                  border: OutlineInputBorder(
                    borderSide: BorderSide(),
                  ),
                ),
                languageCode: "en",
                onChanged: (phone) {
                  setState(() {
                    phoneNumber = phone.completeNumber;
                  });
                  if (kDebugMode) {
                    print(phone.completeNumber);
                  }
                },
                onCountryChanged: (country) {
                  if (kDebugMode) {
                    print('Country changed to: ${country.name}');
                  }
                },
              ),
              const SizedBox(
                height: 10,
              ),
              MaterialButton(
                color: Theme.of(context).primaryColor,
                textColor: Colors.white,
                onPressed: () {
                  if (formKey.currentState!.validate()) {
                    if (kDebugMode) {
                      print("Phone number is: $phoneNumber");
                    }
                  }
                },
                child: const Text('Submit'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

示例代码

下面是一个完整的示例代码,展示如何使用flutter_phone_number_field插件:

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_phone_number_field/flutter_phone_number_field.dart';

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

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

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  GlobalKey<FormState> formKey = GlobalKey();

  final TextEditingController phoneNumberController = TextEditingController();
  String? phoneNumber;

  [@override](/user/override)
  void initState() {
    setState(() {
      phoneNumberController.text = PhoneNumber.getNumber("+22893333401");
    });
    super.initState();
  }

  FocusNode focusNode = FocusNode();
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Phone Number Field Example'),
        ),
        body: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16.0),
          child: Form(
            key: formKey,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                const SizedBox(height: 30),
                const TextField(
                  decoration: InputDecoration(
                    labelText: 'Name',
                    border: OutlineInputBorder(
                      borderSide: BorderSide(),
                    ),
                  ),
                ),
                const SizedBox(
                  height: 10,
                ),
                const TextField(
                  decoration: InputDecoration(
                    labelText: 'Email',
                    border: OutlineInputBorder(
                      borderSide: BorderSide(),
                    ),
                  ),
                ),
                const SizedBox(
                  height: 10,
                ),
                FlutterPhoneNumberField(
                  controller: phoneNumberController,
                  focusNode: focusNode,
                  initialCountryCode: "TG",
                  pickerDialogStyle: PickerDialogStyle(
                    countryFlagStyle: const TextStyle(fontSize: 17),
                  ),
                  decoration: const InputDecoration(
                    hintText: 'Phone Number',
                    border: OutlineInputBorder(
                      borderSide: BorderSide(),
                    ),
                  ),
                  languageCode: "en",
                  onChanged: (phone) {
                    setState(() {
                      phoneNumber = phone.completeNumber;
                    });
                    if (kDebugMode) {
                      print(phone.completeNumber);
                    }
                  },
                  onCountryChanged: (country) {
                    if (kDebugMode) {
                      print('Country changed to: ${country.name}');
                    }
                  },
                ),
                const SizedBox(
                  height: 10,
                ),
                MaterialButton(
                  color: Theme.of(context).primaryColor,
                  textColor: Colors.white,
                  onPressed: () {
                    if (formKey.currentState!.validate()) {
                      if (kDebugMode) {
                        print("Phone number is: $phoneNumber");
                      }
                    }
                  },
                  child: const Text('Submit'),
                ),
              ],
            ),
          ),
        ),
      ),
    
    );
  }
}

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

1 回复

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


当然,以下是一个关于如何使用 flutter_phone_number_field 插件在 Flutter 应用中实现电话号码输入的示例代码。这个插件提供了一个方便的方式来格式化、验证和输入国际电话号码。

首先,确保你已经在 pubspec.yaml 文件中添加了 flutter_phone_number_field 依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_phone_number_field: ^2.0.0  # 请根据需要替换为最新版本

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

接下来,在你的 Dart 文件中,你可以这样使用 flutter_phone_number_field

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Phone Number Input Example'),
        ),
        body: Center(
          child: PhoneNumberField(
            decoration: InputDecoration(
              labelText: 'Enter your phone number',
              border: OutlineInputBorder(),
            ),
            initialCountryCode: 'US',  // 初始国家代码
            enabledCountries: ['US', 'CN', 'IN'],  // 允许的国家代码列表
            onChanged: (phoneNumber) {
              print("Phone number: ${phoneNumber.number}");
              print("Country code: ${phoneNumber.countryCode}");
              print("International formatted number: ${phoneNumber.internationalNumber}");
              print("National formatted number: ${phoneNumber.nationalNumber}");
            },
          ),
        ),
      ),
    );
  }
}

在这个示例中,我们创建了一个简单的 Flutter 应用,其中包含一个 PhoneNumberField 组件。这个组件允许用户输入和格式化他们的电话号码。

  • decoration 参数用于自定义输入框的外观,例如标签文本和边框。
  • initialCountryCode 参数设置初始的国家代码,这里是 ‘US’。
  • enabledCountries 参数限制了用户可以选择的国家代码列表。
  • onChanged 回调函数在用户输入电话号码时触发,可以获取到格式化后的电话号码信息,包括:
    • phoneNumber.number:仅包含数字的电话号码。
    • phoneNumber.countryCode:国家代码。
    • phoneNumber.internationalNumber:国际格式化的电话号码。
    • phoneNumber.nationalNumber:国家格式化的电话号码。

这个插件还提供了许多其他自定义选项和验证功能,你可以根据需要查阅其文档进行进一步的配置。

回到顶部