首页 > 解决方案 > NumerFormat 不允许我添加“,”

问题描述

我想要货币格式匹配意大利语(欧洲大部分地区)语义。为此,我编写了一种数字格式功能,但它不允许我添加“,”作为值的小数部分。

class CurrencyInputFormatter extends TextInputFormatter{
  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    // TODO: implement formatEditUpdate
    if (newValue.selection.baseOffset == 0) {
      print(true);
      return newValue;
    }
    double value = double.parse(newValue.text);
    final formatter = new NumberFormat("#,###.##", "it_IT");
    String newText = formatter.format(value);
    return newValue.copyWith(
        text: newText,
        selection: new TextSelection.collapsed(offset: newText.length));
  }
}

标签: flutter

解决方案


添加依赖 pubspec.yaml 文件。

intl: ^0.15.8

以下是示例

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

void main() => runApp(MyApp());

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

class _MyAppState extends State<MyApp> {
  NumberFormat currencyFormat = new NumberFormat("#,###.##", "it_IT");

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Number Format'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(
                '${currencyFormat.format(200011.56)}',
              )
            ],
          ),
        ), 
      ),
    );
  }
}

推荐阅读