gpt4 book ai didi

dart - flutter 输入中只允许两位小数吗?

转载 作者:IT王子 更新时间:2023-10-29 07:07:23 35 4
gpt4 key购买 nike

我只想要 flutter 输入的小数点后两位数。用户不能在小数点后添加超过两位数。

最佳答案

给你!希望对您有所帮助:)

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

import 'dart:math' as math;

void main() {
runApp(new MaterialApp(home: new MyApp()));
}

class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Flutter"),
),
body: Form(
child: ListView(
children: <Widget>[
TextFormField(
inputFormatters: [DecimalTextInputFormatter(decimalRange: 2)],
keyboardType: TextInputType.numberWithOptions(decimal: true),
)
],
),
),
);
}
}

class DecimalTextInputFormatter extends TextInputFormatter {
DecimalTextInputFormatter({this.decimalRange})
: assert(decimalRange == null || decimalRange > 0);

final int decimalRange;

@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue, // unused.
TextEditingValue newValue,
) {
TextSelection newSelection = newValue.selection;
String truncated = newValue.text;

if (decimalRange != null) {
String value = newValue.text;

if (value.contains(".") &&
value.substring(value.indexOf(".") + 1).length > decimalRange) {
truncated = oldValue.text;
newSelection = oldValue.selection;
} else if (value == ".") {
truncated = "0.";

newSelection = newValue.selection.copyWith(
baseOffset: math.min(truncated.length, truncated.length + 1),
extentOffset: math.min(truncated.length, truncated.length + 1),
);
}

return TextEditingValue(
text: truncated,
selection: newSelection,
composing: TextRange.empty,
);
}
return newValue;
}
}

关于dart - flutter 输入中只允许两位小数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54454983/

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