Created
November 9, 2022 11:25
-
-
Save harsh1772/75f038fc36f11a89760f800ef3a4868e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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