1. 程式人生 > 實用技巧 >Flutter學習筆記(42)--限定TextField輸入內容,僅允許數字和小數點後兩位

Flutter學習筆記(42)--限定TextField輸入內容,僅允許數字和小數點後兩位

import 'package:flutter/services.dart';
import 'dart:math' as math;
class InputFormat extends TextInputFormatter {

  InputFormat({this.decimalRange = 2})
      : 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('.')) { //如果小數點開頭,我們給他補個0 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 ); } }

使用:

keyboardType: TextInputType.numberWithOptions(decimal: true),
inputFormatters: [InputFormat()],