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

Flutter中fluttercontactpicker选联系人后,TextFormField不显示内容的解决方法

问题原因及解决方案

你的问题核心在于自定义的EditTextField没有和_phn变量实现双向绑定:虽然你在onChanged里更新了_phn,也在选中联系人后通过setState更新了_phn,但输入框本身没有监听_phn的变化,所以无法同步显示更新后的号码。

下面提供两种可行的解决方式:


方式1:使用TextEditingController(推荐)

通过控制器直接控制输入框的内容,这是Flutter中处理输入框内容更新的标准方式。

步骤1:初始化控制器

在你的State类中添加并初始化控制器:

late TextEditingController _phoneController;

@override
void initState() {
  super.initState();
  _phoneController = TextEditingController();
}

@override
void dispose() {
  _phoneController.dispose(); // 记得销毁控制器
  super.dispose();
}

步骤2:绑定控制器到EditTextField

修改你的EditTextField代码,传入控制器并在选中联系人时更新控制器内容:

EditTextField(
  controller: _phoneController, // 绑定控制器
  onChanged: (text) {
    setState(() => _phn = text);
  },
  input: [FilteringTextInputFormatter.digitsOnly],
  isPassword: false,
  inputType: TextInputType.number,
  decoration: country_code,
  isSuffix: InkWell(
    onTap: () async {
      final PhoneContact contact = await FlutterContactPicker.pickPhoneContact();
      if (contact != null) {
        final String processedNumber = contact.phoneNumber!.number
            .removeAllWhiteSpace()
            .replaceFirst('+91', '');
        setState(() {
          _phn = processedNumber;
          _phoneController.text = processedNumber; // 直接更新控制器内容
          print("this is $_phn");
        });
      }
    },
    child: const Icon(
      Icons.contacts,
      color: t5DarkNavy,
    ),
  ),
),

方式2:通过value属性绑定(如果自定义组件支持)

如果你的EditTextField封装时支持接收value参数并传递给内部TextFormField的initialValue,可以直接绑定_phn:

EditTextField(
  value: _phn, // 绑定_phn变量
  onChanged: (text) {
    setState(() => _phn = text);
  },
  input: [FilteringTextInputFormatter.digitsOnly],
  isPassword: false,
  inputType: TextInputType.number,
  decoration: country_code,
  isSuffix: InkWell(
    onTap: () async {
      final PhoneContact contact = await FlutterContactPicker.pickPhoneContact();
      if (contact != null) {
        setState(() {
          _phn = contact.phoneNumber!.number
              .removeAllWhiteSpace()
              .replaceFirst('+91', '')
              .toString();
          print("this is $_phn");
        });
      }
    },
    child: const Icon(
      Icons.contacts,
      color: t5DarkNavy,
    ),
  ),
),

注意事项

如果是你自己封装的EditTextField,需要确保组件内部把value参数传递给TextFormField的initialValue,同时注意:controller和initialValue不能同时使用,二选一即可。

内容的提问来源于stack exchange,提问作者Sandeep Sharma

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 14:20:48