Flutter中实现TextField输入数字时逐位左移替换(初始值0.00)
Flutter 实现数字左移输入效果(固定2位小数,初始值0.00)
初始值为0.00的TextField示例布局:
![初始TextField布局]
在Flutter中,需要实现:当用户输入数字时,数字始终左移一位并替换最后一位,固定保留2位小数,初始值为0.00。
输入输出示例
| 用户输入 | 输出结果 |
|---|---|
| 3 | 0.03 |
| 5 | 0.35 |
| 1 | 3.51 |
| 0 | 35.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], ); } }
关键说明
- 用
TextEditingController监听输入变化,实时处理数字逻辑 - 通过
FilteringTextInputFormatter.digitsOnly限制仅能输入数字 - 拼接所有输入数字后转为整数,除以100直接实现左移一位的效果
toStringAsFixed(2)确保输出始终保留2位小数,自动补全末尾的0- 自动定位光标到文本末尾,优化输入体验
内容的提问来源于stack exchange,提问作者gan jinqu
相关产品推荐
相关产品推荐

