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

Flutter中实现TextField输入数字时逐位左移替换(初始值0.00)

Flutter 实现数字左移输入效果(固定2位小数,初始值0.00)

初始值为0.00的TextField示例布局:
![初始TextField布局]

在Flutter中,需要实现:当用户输入数字时,数字始终左移一位并替换最后一位,固定保留2位小数,初始值为0.00。

输入输出示例

用户输入输出结果
30.03
50.35
13.51
035.10

实现代码

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('数字左移输入示例')),
        body: const Center(child: NumberInputField()),
      ),
    );
  }
}

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

  @override
  State<NumberInputField> createState() => _NumberInputFieldState();
}

class _NumberInputFieldState extends State<NumberInputField> {
  final TextEditingController _controller = TextEditingController(text: '0.00');

  @override
  void initState() {
    super.initState();
    _controller.addListener(_updateInputValue);
  }

  void _updateInputValue() {
    // 过滤非数字字符,仅保留数字
    String digitStr = _controller.text.replaceAll(RegExp(r'[^0-9]'), '');
    
    if (digitStr.isEmpty) {
      _controller.text = '0.00';
    } else {
      // 将数字转为整数后除以100,自动实现2位小数的左移效果
      double value = int.parse(digitStr) / 100;
      // 格式化输出为固定2位小数
      _controller.text = value.toStringAsFixed(2);
    }

    // 保持光标在文本末尾,避免输入错位
    _controller.selection = TextSelection.fromPosition(
      TextPosition(offset: _controller.text.length),
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return TextField(
      controller: _controller,
      keyboardType: TextInputType.number,
      decoration: const InputDecoration(
        border: OutlineInputBorder(),
        labelText: '金额输入',
      ),
      inputFormatters: const [FilteringTextInputFormatter.digitsOnly],
    );
  }
}

关键说明

  1. 用TextEditingController监听输入变化,实时处理数字逻辑
  2. 通过FilteringTextInputFormatter.digitsOnly限制仅能输入数字
  3. 拼接所有输入数字后转为整数,除以100直接实现左移一位的效果
  4. toStringAsFixed(2)确保输出始终保留2位小数,自动补全末尾的0
  5. 自动定位光标到文本末尾,优化输入体验

内容的提问来源于stack exchange,提问作者gan jinqu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 14:25:19