Skip to content

Commit

Permalink
Merge pull request #111 from rcasula/bugfix/fix-keyboard-decimal-input
Browse files Browse the repository at this point in the history
Allow decimal input in AddTransaction page.
  • Loading branch information
mikev-cw authored Sep 12, 2023
2 parents 30c71eb + e47474a commit 5e3f2dd
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 2 deletions.
5 changes: 3 additions & 2 deletions lib/pages/add_page/add_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../utils/decimal_text_input_formatter.dart';
import '../../model/transaction.dart';
import 'widgets/details_tile.dart';
import 'widgets/type_tab.dart';
Expand Down Expand Up @@ -337,9 +338,9 @@ class _AddPageState extends ConsumerState<AddPage> with Functions {
color: typeToColor(selectedType),
),
),
keyboardType: TextInputType.number,
keyboardType: const TextInputType.numberWithOptions(decimal: true),
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.allow(RegExp(r'[0,0-9,9]')),
DecimalTextInputFormatter(decimalDigits: 2)
],
autofocus: true,
textAlign: TextAlign.center,
Expand Down
55 changes: 55 additions & 0 deletions lib/utils/decimal_text_input_formatter.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import 'dart:math' as math;
import 'package:flutter/services.dart';

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

final int? decimalDigits;
final String decimalSeparator = ".";
final String thousandsSeparator = ",";

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

RegExp regex = RegExp(r'[\d\,\.]');

if (value.isNotEmpty && !regex.hasMatch(value[value.length -1])) {
return oldValue;
}

if (value.contains(thousandsSeparator)) {
value = value.replaceAll(thousandsSeparator, decimalSeparator);
}

if (decimalSeparator.allMatches(value).length > 1 || value.contains(thousandsSeparator)) {
return oldValue;
}

if (value == decimalSeparator) {
// Allow for .x decimal notation
value = "0$decimalSeparator";
}

if (decimalDigits != null &&
value.contains(decimalSeparator) && value.substring(value.indexOf(decimalSeparator) + 1).length > decimalDigits!) {
value = oldValue.text;
}

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

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

0 comments on commit 5e3f2dd

Please sign in to comment.