【发布时间】:2021-10-03 08:30:55
【问题描述】:
我正在使用pattern formatter 包以便使用ThousandsFormatter。所以当我有值10000000 时,它会自动显示为10.000.000。最初的代码是这样的,它按预期工作
TextFormField(
autofocus: false,
autocorrect: false,
maxLines: 1,
textAlign: TextAlign.end,
keyboardType: TextInputType.number,
onChanged: (newNominal) {
final newValue = newNominal.replaceAll(".", "");
controller.selectedNominal = int.tryParse(newValue) ?? 0;
},
inputFormatters: [
ThousandsFormatter(formatter: NumberFormat("#,###.##", "in_ID")),
],
),
然后我做一些这样的按钮
如您所见,当我选择 $4000 时,文本字段将显示 4000,我希望它会显示 4.000
从按钮中选择值后,我使用TextEditingController 填充文本字段中的值,所以我的 TeextField 将是这样的
final _textEditingController = TextEditingController();
TextFormField(
controller: _textEditingController, // I add this line
autofocus: false,
autocorrect: false,
maxLines: 1,
textAlign: TextAlign.end,
keyboardType: TextInputType.number,
onChanged: (newNominal) {
final newValue = newNominal.replaceAll(".", "");
controller.selectedNominal = int.tryParse(newValue) ?? 0;
},
inputFormatters: [
ThousandsFormatter(formatter: NumberFormat("#,###.##", "in_ID")),
],
),
当我点击其中一个按钮时,build 将再次调用,所以我在文本字段中设置了这样的文本
@override
Widget build(context) {
final selectedNominal = pageController.selectedNominal.toString();
final editingValue = TextEditingValue(
text: selectedNominal,
selection: TextSelection.fromPosition(
TextPosition(offset: selectedNominal.length),
),
);
_textEditingController.value = editingValue;
return Scaffold(
appBar: AppBar(
title: Text("Title here"),
),
body: _buildWidgets(),
);
}
}
我不明白为什么ThousandsFormatter 在_textEditingController.value 之后不再起作用,即使我使用键盘输入数值,ThousandsFormatter 也不起作用
名义上的控制器是这样的
class NominalController with ChangeNotifier {
int _selectedNominal = 0;
int get selectedNominal => _selectedNominal;
set selectedNominal(int newValue) {
_selectedNominal = newValue;
notifyListeners();
}
}
【问题讨论】: