user-interface - Flutter 中的 InputTextType.number 最多允许 3 个小数点值
问题描述
下面是我尝试过的代码,但它完全失败了。如果我删除WhitelistingTextInputFormatter
,我会得到数字键盘,我可以插入数字和句点。但是period
我可以使用的数量不止一个,我需要限制在一个。这个怎么做?
TextField(
controller: _weightCtr,
keyboardType: TextInputType.numberWithOptions(decimal: true),
inputFormatters: [
BlacklistingTextInputFormatter(new RegExp('[\\-|\\ ]')),
WhitelistingTextInputFormatter(new RegExp('^\d+[\.\,]\d+\$')),
],
decoration: InputDecoration(
hintText: "Please enter a valid weight for this trip",
),
style: Theme.of(context).textTheme.title.copyWith(
fontWeight: FontWeight.w300,
fontSize: 14,
),
),
解决方案
您可以在下面复制粘贴运行完整代码
您可以扩展TextInputFormatter
和删除额外的点
在工作演示中,您可以看到额外的点何时不会显示在屏幕上
代码片段
class NumberRemoveExtraDotFormatter extends TextInputFormatter {
NumberRemoveExtraDotFormatter({this.decimalRange = 3})
if (nValue.split('.').length > 2) {
List<String> split = nValue.split('.');
nValue = split[0] + '.' + split[1];
}
...
TextField(
controller: _weightCtr,
keyboardType: TextInputType.numberWithOptions(decimal: true),
inputFormatters: [
NumberRemoveExtraDotFormatter()
//BlacklistingTextInputFormatter(new RegExp('[\\-|\\ ]')),
//WhitelistingTextInputFormatter(new RegExp('^\d+[\.\,]\d+\$')),
],
decoration: InputDecoration(
hintText: "Please enter a valid weight for this trip",
),
style: Theme.of(context).textTheme.title.copyWith(
fontWeight: FontWeight.w300,
fontSize: 14,
),
),
工作演示
完整代码
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:math' as math;
class NumberRemoveExtraDotFormatter extends TextInputFormatter {
NumberRemoveExtraDotFormatter({this.decimalRange = 3})
: assert(decimalRange == null || decimalRange > 0);
final int decimalRange;
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue, TextEditingValue newValue) {
String nValue = newValue.text;
TextSelection nSelection = newValue.selection;
Pattern p = RegExp(r'(\d+\.?)|(\.?\d+)|(\.?)');
nValue = p
.allMatches(nValue)
.map<String>((Match match) => match.group(0))
.join();
if (nValue.startsWith('.')) {
nValue = '0.';
} else if (nValue.contains('.')) {
if (nValue.substring(nValue.indexOf('.') + 1).length > decimalRange) {
nValue = oldValue.text;
} else {
if (nValue.split('.').length > 2) {
List<String> split = nValue.split('.');
nValue = split[0] + '.' + split[1];
}
}
}
nSelection = newValue.selection.copyWith(
baseOffset: math.min(nValue.length, nValue.length + 1),
extentOffset: math.min(nValue.length, nValue.length + 1),
);
return TextEditingValue(
text: nValue, selection: nSelection, composing: TextRange.empty);
}
}
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, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
TextEditingController _weightCtr = TextEditingController();
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextField(
controller: _weightCtr,
keyboardType: TextInputType.numberWithOptions(decimal: true),
inputFormatters: [
NumberRemoveExtraDotFormatter()
//BlacklistingTextInputFormatter(new RegExp('[\\-|\\ ]')),
//WhitelistingTextInputFormatter(new RegExp('^\d+[\.\,]\d+\$')),
],
decoration: InputDecoration(
hintText: "Please enter a valid weight for this trip",
),
style: Theme.of(context).textTheme.title.copyWith(
fontWeight: FontWeight.w300,
fontSize: 14,
),
),
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
推荐阅读
- shell - Linux命令删除特定目录以外的目录在管道的shell脚本中失败
- android - Flutter build apk 无法在 android studio 上运行
- python - NLTK path_similarity 给出 ValueError
- yaml - 如何为 Azure 管道中的不同作业保留环境
- rust - 如何格式化这样的字符串?
- microsoft-teams - 在 Teams Flow 中使用输入更新消息 - 发布自适应卡片操作
- java - 在哪里以及如何免费部署 Java Spring Boot 应用程序?
- html - 如何让我的 gif 显示在此网格的第一行和 2 列中?
- javascript - 如何将焦点转移到extjs中的下一个/上一个选项卡
- javascript - 在 recyclerview 片段中仅显示来自 firebase 的图像文本图像未加载