gpt4 book ai didi

带有 NumberFormat 的 Flutter TextFormField 显示值

转载 作者:行者123 更新时间:2023-12-05 04:46:43 29 4
gpt4 key购买 nike

我希望能够使用 NumberFormat('###,##0.00', 'en_US') 显示在 TextFormField 中输入的值.

转换没有问题,但我在显示 formattedPrice 的值时遇到问题在 TextFormField 中。我还想将 TextFormField 的默认值设置为 '0.00' .在我下面的示例代码中,TextFormField 将输入限制为只有一个十进制符号/分隔符和两个十进制值。

我对 .00 没问题在输入期间 TextFormField 值中没有小数时不显示小数,但我希望在输入值时放置两位小数格式。

<表类="s-表"><头>键入时显示的 TextFormField 值输入时显示的TextFormField值<正文>123123.00123.5123.50123.54123.5412,34512,345.0012,345.612,345.60

最小复制

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

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}

class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;

@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
final _subscriptionFormKey = GlobalKey<FormState>();
final _subscriptionPriceController = TextEditingController();
NumberFormat numFormat = NumberFormat('###,###.00', 'en_US');
NumberFormat numSanitizedFormat = NumberFormat('en_US');
var currency = 'USD';

void _validate() {
if (_subscriptionFormKey.currentState!.validate()) {}
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Form(
key: _subscriptionFormKey,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
autofocus: true,
inputFormatters: [
FilteringTextInputFormatter.allow(RegExp(r'^\d+\.?\d{0,2}')),
],
keyboardType: TextInputType.numberWithOptions(decimal: true),
validator: (cost) {
if (cost == null || cost.isEmpty) {
return 'Empty';
}
return null;
},
textInputAction: TextInputAction.next,

/// TODO TextFormField default value
/// I'd like to be to set '0.00' value by default
controller: _subscriptionPriceController,
decoration: InputDecoration(
hintText: 'Price',
prefixText:
NumberFormat.simpleCurrency(name: currency).currencySymbol,
),
onChanged: (price) {
/// TODO Display [formattedPrice] in TextFormField
var formattedPrice = numFormat.format(double.parse(price));
debugPrint('Formatted $formattedPrice');
var numSanitized = numSanitizedFormat.parse(price);
debugPrint('Sanitized: $numSanitized');
_subscriptionPriceController.value = TextEditingValue(
text: price,
selection: TextSelection.collapsed(offset: price.length),
);
},
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: _validate,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}

更新:

感谢@Andrej 建议使用 onFieldSubmitted()而不是 onChange() .我已经使用包含的修复程序更新了我的代码。我希望这能帮助其他遇到类似问题的开发者。

修复代码:

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

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}

class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;

@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
final _subscriptionFormKey = GlobalKey<FormState>();
final _subscriptionPriceController = TextEditingController();
final NumberFormat numFormat = NumberFormat('###,##0.00', 'en_US');
final NumberFormat numSanitizedFormat = NumberFormat('en_US');
var currency = 'USD';
var defaultPrice = '0.00';

void _validate() {
if (_subscriptionFormKey.currentState!.validate()) {}
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Form(
key: _subscriptionFormKey,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
autofocus: true,
inputFormatters: [
FilteringTextInputFormatter.allow(RegExp(r'^\d+\.?\d{0,2}')),
],
keyboardType: TextInputType.numberWithOptions(decimal: true),
validator: (cost) {
if (cost == null || cost.isEmpty) {
return 'Empty';
}
return null;
},
textInputAction: TextInputAction.next,

/// Set TextFormField default value
controller: _subscriptionPriceController..text = defaultPrice,
decoration: InputDecoration(
hintText: 'Price',
prefixText:
NumberFormat.simpleCurrency(name: currency).currencySymbol,
),
onTap: () {
var textFieldNum = _subscriptionPriceController.value.text;
var numSanitized = numSanitizedFormat.parse(textFieldNum);
_subscriptionPriceController.value = TextEditingValue(
/// Clear if TextFormField value is 0
text: numSanitized == 0 ? '' : '$numSanitized',
selection:
TextSelection.collapsed(offset: '$numSanitized'.length),
);
},
onFieldSubmitted: (price) {
/// Set value to 0 if TextFormField value is empty
if (price == '') price = '0';
final formattedPrice = numFormat.format(double.parse(price));
debugPrint('Formatted $formattedPrice');
_subscriptionPriceController.value = TextEditingValue(
text: formattedPrice,
selection:
TextSelection.collapsed(offset: formattedPrice.length),
);
},
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: _validate,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}

Demo

最佳答案

如果我没理解错的话,您希望在输入文本字段时对价格进行格式化。

如果是,只需将此代码添加到您的TextFormField:

            onFieldSubmitted: (price) {
final formattedPrice = numFormat.format(double.parse(price));
debugPrint('Formatted $formattedPrice');
_subscriptionPriceController.value = TextEditingValue(
text: formattedPrice,
selection:
TextSelection.collapsed(offset: formattedPrice.length),
);
},

将初始值添加到文本字段:

final _subscriptionPriceController = TextEditingController(text: '0.00');

关于带有 NumberFormat 的 Flutter TextFormField 显示值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68740586/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com