You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何根据国家代码格式化手机号码?

根据国家代码动态格式化手机号的解决方案

嘿,看你现在用的是固定掩码来处理手机号,要实现根据国家代码自动切换格式的话,咱们可以通过动态切换掩码的方式来搞定,下面是具体的实现思路和代码示例:

1. 先准备国家代码与对应掩码的映射

首先定义常用国家的代码和对应的手机号格式掩码,你可以根据业务需求随时扩展这个列表:

final Map<String, String> countryMaskMap = {
  'US': '(000) 000-0000', // 美国格式
  'CN': '000-0000-0000', // 中国格式
  'IN': '+91 00000 00000', // 印度格式
  'GB': '+44 (0)0000 000000', // 英国格式
};

2. 动态管理掩码与输入控制器

我们需要维护当前选中的国家代码,并且在切换时同步更新输入框的掩码,用setState触发UI更新即可:

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

  @override
  State<PhoneNumberFormatter> createState() => _PhoneNumberFormatterState();
}

class _PhoneNumberFormatterState extends State<PhoneNumberFormatter> {
  String? selectedCountryCode = 'US'; // 默认选中美国
  late MaskedTextController _controller;

  @override
  void initState() {
    super.initState();
    // 初始化控制器,使用默认国家的掩码
    _controller = MaskedTextController(mask: countryMaskMap[selectedCountryCode]!);
  }

  // 切换国家时更新控制器的掩码
  void _onCountryChanged(String? newCode) {
    if (newCode == null) return;
    setState(() {
      selectedCountryCode = newCode;
      // 更新掩码,同时保留已输入的内容并自动适配新格式
      _controller.updateMask(countryMaskMap[newCode]!);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("动态手机号格式化"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Row(
          children: <Widget>[
            // 国家代码选择下拉框
            DropdownButton<String>(
              value: selectedCountryCode,
              items: countryMaskMap.keys.map((code) {
                return DropdownMenuItem(
                  value: code,
                  child: Text('+$code'),
                );
              }).toList(),
              onChanged: _onCountryChanged,
            ),
            const SizedBox(width: 16),
            // 手机号输入框
            Expanded(
              child: TextField(
                controller: _controller,
                keyboardType: TextInputType.number,
                decoration: const InputDecoration(
                  hintText: "输入手机号",
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

关键细节说明

  • _onCountryChanged方法里调用的updateMask()是MaskedTextController自带的方法,能自动保留已输入内容并按照新掩码重新格式化,不用手动处理内容迁移。
  • 如果需要更严格的校验(比如不同国家的号码长度限制),可以额外结合TextInputFormatter来做补充校验。
  • 你可以随时扩展countryMaskMap,添加更多国家的代码和对应的格式规则。

内容的提问来源于stack exchange,提问作者Rutvik Gumasana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:13:36