flutter 如何去掉TextField中的前导0(零)

xwmevbvl  于 2023-01-27  发布在  Flutter
关注(0)|答案(2)|浏览(278)

bounty将在7天后过期。回答此问题可获得+100的声誉奖励。Linar正在寻找来自声誉良好的来源的答案

如何删除0个数字而不丢失光标位置。

hmae6n7t

hmae6n7t1#

inputFormatters: [
        FilteringTextInputFormatter.digitsOnly,
        FilteringTextInputFormatter.deny(RegExp('^0+'))
      ]
2g32fytz

2g32fytz2#

TextField(
    controller: controller,
    onChanged: (value) {
      var selection = controller.selection;
      final RegExp regexp = new RegExp(r'^0+(?=.)');
      var match = regexp.firstMatch(value);

      var matchLengh = match?.group(0)?.length ?? 0;
      if (matchLengh != 0) {
        controller.text = value.replaceAll(regexp, '');
        controller.selection = TextSelection.fromPosition(
          TextPosition(
            offset: math.min(matchLengh, selection.extent.offset),
          ),
        );
      }
    },
    // keyboardType and inputFormatters not realy needed in this case but maybe usefull
    keyboardType: TextInputType.number,
    inputFormatters: <TextInputFormatter>[
      FilteringTextInputFormatter.digitsOnly
    ],
    ...
  )

相关问题