Skip to content

Instantly share code, notes, and snippets.

@SametSahin10
Created September 14, 2023 11:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SametSahin10/7cdaa918a68905b28e96cb8747805631 to your computer and use it in GitHub Desktop.
Save SametSahin10/7cdaa918a68905b28e96cb8747805631 to your computer and use it in GitHub Desktop.
import 'package:flutter/services.dart';
class NoLeadingZerosTextInputFormatter extends TextInputFormatter {
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue,
TextEditingValue newValue,
) {
final newText = newValue.text;
final userTypedWhenThereWasZero =
newText.startsWith("0") && newText.length > 1;
if (!userTypedWhenThereWasZero) return newValue;
final regExp = RegExp(r'^0+(?=.)');
final textWithoutLeadingZeros = newText.replaceAll(regExp, "");
return TextEditingValue(
text: textWithoutLeadingZeros,
selection: newValue.selection.copyWith(
baseOffset: newText.length - 1,
extentOffset: newText.length - 1,
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment