【问题标题】:how to format or separate textformfield parts in flutter如何在颤动中格式化或分离文本表单字段部分
【发布时间】:2021-02-19 11:19:32
【问题描述】:

我有一个文本表单字段,我想分隔文本表单字段中的文本
假设用户写1111111,输出将是 1,111,111

Form(
          child: Column(
            children: [
              TextFormField(
                keyboardType: TextInputType.emailAddress,
                decoration: InputDecoration(
                  labelText: 'Email Address',
                  hintText: 'you@example.com',
                ),
              )
            ],
          ),
        ),

【问题讨论】:

  • 这能回答你的问题吗? Dart how to add commas to a string number
  • 如果有,你觉得我为什么要再问一遍?
  • 我知道您正在尝试做什么,并且目前正在尝试制作自定义 TextInputFormatter。 Ashok 的答案是您想要的代码,但在 textformfield 内格式化有点棘手。
  • 我很高兴看到您的帮助,ashok 的回答有效但仅在终端中,这意味着我可以将它们分开但只有在我打印时,我也想在文本表单字段中显示它,如果有可能,请在您的回答中包含此内容
  • 考虑聚焦问题。您是在问如何使字符串分隔,还是在问如何获取“TextField”的更新?

标签: flutter dart


【解决方案1】:
RegExp reg_ex = new RegExp(r'(\d{1,3})(?=(\d{3})+(?!\d))');
Function mathFunc = (Match match) => '${match[1]},';

List<String> sample = [
  '1111111',
];

sample.forEach((String str) {
  String result = str.replaceAllMapped(reg_ex, mathFunc);
  print('$str -> $result');
});

【讨论】:

    【解决方案2】:

    您应该使用TextFormField 类中的controller property

    1. 您需要将小部件设为有状态小部件(我们需要它的 dispose 方法)。
    2. controller 添加到您的状态:
      final _textController = TextEditingController();
    
      @override
      void dispose() {
        super.dispose();
        _textController.dispose();
      }
    
    1. 为您的controller 添加一个侦听器,以便在您键入时格式化您的输入:
      @override
      void initState() {
        super.initState();
        _textController.addListener(() {
          // using Ashok's answer to format the text
          final reg_ex = new RegExp(r'(\d{1,3})(?=(\d{3})+(?!\d))');
          final matchFunc = (Match match) => '${match[1]},';
          final text = _textController.text;
    
          _textController.value = _textController.value.copyWith(
            // we need to remove all the ',' from the values before reformatting
            // if you use other formatting values, remember to remove them here
            text: text.replaceAll(',', '').replaceAllMapped(reg_ex, matchFunc),
            // this will keep the cursor on the right as you type in values
            selection: TextSelection(
              baseOffset: text.length,
              extentOffset: text.length,
            ),
          );
        });
      }
    
    1. 在您的TextFormField 中使用controller
      TextFormField(
        controller: _textController,
        keyboardType: TextInputType.emailAddress,
        decoration: InputDecoration(
          labelText: 'Email Address',
          hintText: 'you@example.com',
        ),
      )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-23
      • 1970-01-01
      • 2016-06-19
      相关资源
      最近更新 更多