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

标签 dart flutter flutter-layout

我只想要 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/

相关文章:

dart - Flutter:使用按钮更改标签栏 View 中的当前标签

在 Google Dart 中解析 YAML?

list - Dart 流/列表

flutter - PlatformException(400,HTTP状态码错误。,null)

flutter - 如何使 Sliver 标题在其他 Sliver 中具有粘性

ruby - Ruby Sass弃用-如何查看我的版本是否被弃用

android - 我在android studio中遇到了这个问题。我已经下载了链接中提到的文件,并将其粘贴到哪里

ios - 不受支持的架构,.app/Frameworks/...的可执行文件包含 Flutter ios 上不受支持的架构 [x86_64]

flutter - 如何在 Flutter 中设置 Row() 的背景颜色?

flutter - 如何在 flutter 中仅使一行2个元素中的一个元素居中