Small details that build taste in Flutter.

curated by Kamran BekirovKamran Bekirov

Strip the country code from autofill and paste

This detail uses +994, the Azerbaijani country code. For your country, adapt it yourself or ask your AI agent.

Your phone field shows a fixed +994 prefix on the left, so users type only the national number. Then they paste their number with +994 in front, or autofill inserts it as a full international string, and the country code ends up in the field twice. Catch it with a formatter, so only the national number lands:

You can't control what gets inserted. But every change to the text goes through inputFormatters: keystrokes, paste, and autofill all arrive as an ordinary edit. Strip the dial code there:

import 'package:flutter/services.dart';
  
class StripDialCodeFormatter extends TextInputFormatter {
  static const String _dialCode = '994';
  
  static final RegExp _nonDigits = RegExp(r'[^0-9]');
  
  @override
  TextEditingValue formatEditUpdate(
    TextEditingValue oldValue,
    TextEditingValue newValue,
  ) {
    // A keystroke grows the text by one character.
    // Paste and autofill grow it by many.
    final bool bulk = newValue.text.length - oldValue.text.length > 1;
    if (!bulk) return newValue;
  
    final String digits = newValue.text.replaceAll(_nonDigits, '');
  
    String national = digits;
    if (digits.startsWith('00$_dialCode')) {
      national = digits.substring(2 + _dialCode.length);
    } else if (newValue.text.trimLeft().startsWith('+') &&
        digits.startsWith(_dialCode)) {
      national = digits.substring(_dialCode.length);
    }
  
    return TextEditingValue(
      text: national,
      selection: TextSelection.collapsed(offset: national.length),
    );
  }
}

How it decides:

Typed input passes through. The formatter only acts when the text grows by more than one character, so typing is never touched.

+994... and 00994... are clearly international: strip the dial code.

Wire it up:

TextField(
  keyboardType: TextInputType.phone,
  autofillHints: const [
    AutofillHints.telephoneNumber,
  ],
  inputFormatters: [
    StripDialCodeFormatter(),
  ],
  decoration: const InputDecoration(
    prefixText: '+994 ',
    hintText: '501234567',
  ),
)

autofillHints is what makes the OS offer the number in the first place. Keep it: the formatter makes autofill safe, so users keep the one-tap sign-in.

Kamran Bekirov
Kamran Bekirov

Want this level of care in your Flutter apps?

Work With Me