Skip to content

Instantly share code, notes, and snippets.

@harsh1772
Created November 9, 2022 11:25
Show Gist options
  • Save harsh1772/75f038fc36f11a89760f800ef3a4868e to your computer and use it in GitHub Desktop.
Save harsh1772/75f038fc36f11a89760f800ef3a4868e to your computer and use it in GitHub Desktop.
import 'dart:math';
import 'package:flutter/services.dart';
class DateTextFormatter extends TextInputFormatter {
static const _maxChars = 8;
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue, TextEditingValue newValue) {
var text = _format(newValue.text, '/');
return newValue.copyWith(text: text, selection: updateCursorPosition(text));
}
String _format(String value, String seperator) {
value = value.replaceAll(seperator, '');
var newString = '';
for (int i = 0; i < min(value.length, _maxChars); i++) {
newString += value[i];
if ((i == 1 || i == 3) && i != value.length - 1) {
newString += seperator;
}
}
return newString;
}
TextSelection updateCursorPosition(String text) {
return TextSelection.fromPosition(TextPosition(offset: text.length));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment