Flutter国际电话号码输入插件intl_phone_number_field的使用
Flutter国际电话号码输入插件intl_phone_number_field的使用
intl_phone_number_field
是一个自定义的Flutter TextFormField
,用于输入国际电话号码以及国家代码。本文将详细介绍如何使用这个插件,并提供完整的示例代码。
使用方法
可用参数
以下是 InternationalPhoneNumberInput
的一些常用参数及其数据类型和初始值:
参数 | 数据类型 | 初始值 |
---|---|---|
controller | TextEditingController | TextEditingController() |
height | double | 60 |
inputFormatters | List | [] |
formatter | MaskedInputFormatter | MaskedInputFormatter(’### ### ## ##’) |
initCountry | CountryCodeModel | CountryCodeModel(name: “United States”, dial_code: “+1”, code: “US”) |
betweenPadding | double | 23 |
onInputChanged | Function(IntPhoneNumber number) | null |
loadFromJson | Future<String?> Function() | null |
dialogConfig | DialogConfig | DialogConfig() |
countryConfig | CountryConfig | CountryConfig() |
phoneConfig | PhoneConfig | PhoneConfig() |
validator | String? Function(IntPhoneNumber number)? | null |
示例代码
以下是一个完整的示例代码,展示了如何使用 intl_phone_number_field
插件:
// ignore_for_file: avoid_print
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:intl_phone_number_field/intl_phone_number_field.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
TextEditingController controller = TextEditingController();
String? data;
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 15),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
InternationalPhoneNumberInput(
height: 60,
controller: controller,
inputFormatters: const [],
formatter: MaskedInputFormatter('### ### ## ##'),
initCountry: CountryCodeModel(
name: "United States", dial_code: "+1", code: "US"),
betweenPadding: 23,
onInputChanged: (phone) {
print(phone.code);
print(phone.dial_code);
print(phone.number);
print(phone.rawFullNumber);
print(phone.rawNumber);
print(phone.rawDialCode);
},
dialogConfig: DialogConfig(
backgroundColor: const Color(0xFF444448),
searchBoxBackgroundColor: const Color(0xFF56565a),
searchBoxIconColor: const Color(0xFFFAFAFA),
countryItemHeight: 55,
topBarColor: const Color(0xFF1B1C24),
selectedItemColor: const Color(0xFF56565a),
selectedIcon: Padding(
padding: const EdgeInsets.only(left: 10),
child: Image.asset(
"assets/check.png",
width: 20,
fit: BoxFit.fitWidth,
),
),
textStyle: TextStyle(
color: const Color(0xFFFAFAFA).withOpacity(0.7),
fontSize: 14,
fontWeight: FontWeight.w600),
searchBoxTextStyle: TextStyle(
color: const Color(0xFFFAFAFA).withOpacity(0.7),
fontSize: 14,
fontWeight: FontWeight.w600),
titleStyle: const TextStyle(
color: Color(0xFFFAFAFA),
fontSize: 18,
fontWeight: FontWeight.w700),
searchBoxHintStyle: TextStyle(
color: const Color(0xFFFAFAFA).withOpacity(0.7),
fontSize: 14,
fontWeight: FontWeight.w600),
),
countryConfig: CountryConfig(
decoration: BoxDecoration(
border: Border.all(
width: 2, color: const Color(0xFF3f4046)),
borderRadius: BorderRadius.circular(8),
),
noFlag: false,
textStyle: const TextStyle(
color: Colors.black,
fontSize: 16,
fontWeight: FontWeight.w600)),
validator: (number) {
if (number.number.isEmpty) {
return "The phone number cannot be left empty";
}
return null;
},
phoneConfig: PhoneConfig(
focusedColor: const Color(0xFF6D59BD),
enabledColor: const Color(0xFF6D59BD),
errorColor: const Color(0xFFFF5494),
labelStyle: null,
labelText: null,
floatingLabelStyle: null,
focusNode: null,
radius: 8,
hintText: "Phone Number",
borderWidth: 2,
backgroundColor: Colors.transparent,
decoration: null,
popUpErrorText: true,
autoFocus: false,
showCursor: false,
textInputAction: TextInputAction.done,
autovalidateMode: AutovalidateMode.onUserInteraction,
errorTextMaxLength: 2,
errorPadding: const EdgeInsets.only(top: 14),
errorStyle: const TextStyle(
color: Color(0xFFFF5494), fontSize: 12, height: 1),
textStyle: const TextStyle(
color: Colors.black,
fontSize: 16,
fontWeight: FontWeight.w400),
hintStyle: TextStyle(
color: Colors.black.withOpacity(0.5),
fontSize: 16,
fontWeight: FontWeight.w400),
),
),
],
),
),
),
);
}
}
错误配置
你可以通过设置 popUpErrorText
来控制错误消息的显示方式。如果设置为 true
,则错误消息不会占用额外的空间;如果设置为 false
,则会预留空间给错误消息。
PhoneConfig(
errorColor: const Color(0xFFFF5494),
popUpErrorText: true,
autovalidateMode: AutovalidateMode.onUserInteraction,
errorTextMaxLength: 2,
errorPadding: const EdgeInsets.only(top: 14),
errorStyle: const TextStyle(
color: Color(0xFFFF5494), fontSize: 12, height: 1)
)
加载JSON数据
你可以从自己的JSON文件中加载国家代码并上传到插件中。确保你的JSON文件格式如下:
[
{
"name": "Aland Islands",
"dial_code": "+358",
"code": "AX"
},
{
"name": "Albania",
"dial_code": "+355",
"code": "AL"
},
{
"name": "Algeria",
"dial_code": "+213",
"code": "DZ"
}
]
然后在代码中加载该JSON文件:
Future<String> loadFromJson() async {
return await rootBundle.loadString('assets/countries/country_list.json');
}
IntPhoneNumber
onInputChanged
函数会返回一个 IntPhoneNumber
类型的对象,包含以下信息:
print(phone.code); // US
print(phone.dial_code); // +1
print(phone.number); // 553 142 88 74
print(phone.rawFullNumber); // 15531428874
print(phone.rawNumber); // 5531428874
print(phone.rawDialCode); // 1
通过以上内容,你应该能够轻松地在Flutter应用中集成国际电话号码输入功能。希望这些信息对你有所帮助!
更多关于Flutter国际电话号码输入插件intl_phone_number_field的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter国际电话号码输入插件intl_phone_number_field的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,下面是一个关于如何使用 intl_phone_number_field
插件在 Flutter 中实现国际电话号码输入的详细代码案例。
首先,确保你已经在 pubspec.yaml
文件中添加了 intl_phone_number_input
依赖项(注意:intl_phone_number_field
并不是官方或广泛使用的包名,这里我们假设你是指 intl_phone_number_input
,它是实现类似功能的流行包):
dependencies:
flutter:
sdk: flutter
intl_phone_number_input: ^0.7.0+2 # 请检查最新版本号
然后运行 flutter pub get
来获取依赖项。
接下来,在你的 Dart 文件中使用 IntlPhoneNumberInput
小部件。以下是一个完整的示例,展示了如何集成和使用该插件:
import 'package:flutter/material.dart';
import 'package:intl_phone_number_input/intl_phone_number_input.dart';
import 'package:intl_phone_number_input/utils/utils.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Intl Phone Number Input Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: Text('Intl Phone Number Input Demo'),
),
body: Center(
child: PhoneNumberInputDemo(),
),
),
);
}
}
class PhoneNumberInputDemo extends StatefulWidget {
@override
_PhoneNumberInputDemoState createState() => _PhoneNumberInputDemoState();
}
class _PhoneNumberInputDemoState extends State<PhoneNumberInputDemo> {
final phoneController = TextEditingController();
final focusNode = FocusNode();
PhoneNumber number = PhoneNumber();
@override
void dispose() {
phoneController.dispose();
focusNode.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(16.0),
child: IntlPhoneNumberInput(
controller: phoneController,
focusNode: focusNode,
initialSelectionCountry: 'us', // 初始选择国家代码
favorite: ['+1', '91'], // 常用国家代码
decoration: InputDecoration(
labelText: 'Phone Number',
border: OutlineInputBorder(),
),
onSelectCountry: (PhoneNumber country) {
setState(() {
number = country;
});
},
onChanged: (PhoneNumber value) {
print("phone number: ${value.number}");
print("dialCode: ${value.dialCode}");
print("isoCode: ${value.isoCode}");
},
validator: (PhoneNumber value) {
if (value == null || value.isEmpty) {
return 'Please enter a valid phone number';
}
return null;
},
onSaved: (PhoneNumber value) {
print("Saved phone number: ${value.number}");
},
keyboardType: TextInputType.phone,
),
);
}
}
在这个示例中:
- 我们首先导入了必要的包。
- 创建了一个
MyApp
小部件作为应用的根。 - 在
PhoneNumberInputDemo
小部件中,我们定义了一个TextEditingController
和一个FocusNode
来管理电话号码输入框的状态和焦点。 - 使用
IntlPhoneNumberInput
小部件来显示电话号码输入字段。 - 配置了初始选择国家代码、常用国家代码、装饰样式、国家选择回调、值变化回调、验证器和保存回调。
这样,你就可以在 Flutter 应用中使用 intl_phone_number_input
插件来输入和验证国际电话号码了。记得在实际项目中根据需要调整依赖项的版本号和其他配置。