Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import 'dart:math';
- import 'package:flutter/services.dart';
- class DateTimeTextFormatter extends TextInputFormatter {
- static const _maxChars = 17;
- @override
- TextEditingValue formatEditUpdate(
- TextEditingValue oldValue,
- TextEditingValue newValue,
- ) {
- String separatorDate = '/';
- String spacing = ' ';
- String separatorTime = ':';
- var text = _format(
- newValue.text,
- oldValue.text,
- separatorDate,
- spacing,
- separatorTime,
- );
- return newValue.copyWith(
- text: text,
- selection: updateCursorPosition(
- oldValue,
- text,
- ),
- );
- }
- String _format(
- String value,
- String oldValue,
- String separatorDate,
- String spacing,
- String separatorTime,
- ) {
- var isErasing = value.length < oldValue.length;
- var isComplete = value.length > _maxChars + 2;
- if (!isErasing && isComplete) {
- return oldValue;
- }
- value = value.replaceAll(separatorDate, '');
- value = value.replaceAll(spacing, '');
- value = value.replaceAll(separatorTime, '');
- final result = <String>[];
- for (int i = 0; i < min(value.length, _maxChars); i++) {
- result.add(value[i]);
- if ((i == 1 || i == 3) && i != value.length - 1) {
- result.add(separatorDate);
- }
- if ((i == 7) && i != value.length - 1) {
- result.add(' ');
- }
- if ((i == 9 || i == 11) && i != value.length - 1) {
- result.add(separatorTime);
- }
- }
- // (i == 1 || i == 3 || i == 7 || i == 9 || i == 11)
- return result.join();
- }
- TextSelection updateCursorPosition(
- TextEditingValue oldValue,
- String text,
- ) {
- var endOffset = max(
- oldValue.text.length - oldValue.selection.end,
- 0,
- );
- var selectionEnd = text.length - endOffset;
- return TextSelection.fromPosition(TextPosition(offset: selectionEnd));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement