【问题标题】:Allow upto 3 decimal points value in flutter InputTextType.number in flutter颤振中最多允许3个小数点值输入文本类型.颤振中的数字
【发布时间】:2020-02-25 08:10:16
【问题描述】:

以下是我尝试过但完全失败的代码。如果我删除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,
                  ),
                ),

【问题讨论】:

  • 将我的作品列入黑名单。现在我应该如何将periods 限制为一个是我的问题。加上您提供的链接是localhost
  • 我尝试搜索TextInputFormatter.withFunction 的示例,但找不到。在颤振文档中给出了它的实现结构。但到目前为止,我并不是创建示例或仅使用结构的专业人士。非常感谢一个简单的例子或一个确切的例子。

标签: user-interface flutter numbers user-input decimalformat


【解决方案1】:

您可以在下面复制粘贴运行完整代码
您可以扩展 TextInputFormatter 并删除多余的点
在工作演示中,您可以看到屏幕上何时不会显示额外的点

代码sn-p

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),
      ),
    );
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-21
    • 2020-07-04
    • 2022-09-24
    • 2019-04-20
    • 1970-01-01
    • 2020-01-07
    • 2020-01-30
    • 1970-01-01
    相关资源
    最近更新 更多