Flutter format phone number

Formatting Phone Number in Flutter

To format a phone number in Flutter, you can use the “intl” package which provides localization and internationalization support. Here’s how you can do it:

  1. Add the “intl” package to your pubspec.yaml file:

            dependencies:
              flutter:
                sdk: flutter
              intl: ^0.17.0
          
  2. Run flutter pub get in your terminal to fetch the package.
  3. Import the necessary classes in your Dart file:

            import 'package:intl/intl.dart';
          
  4. Create a function to format the phone number:

            String formatPhoneNumber(String phoneNumber) {
              final pattern = r'(\d{3})(\d{3})(\d{4})';
              final formatted =
                  RegExp(pattern).stringMatch(phoneNumber)?.replaceAll(pattern, '(\$1) \$2-\$3');
    
              return formatted ?? phoneNumber;
            }
          
  5. Call the formatPhoneNumber function with a phone number as input:

            final phoneNumber = '1234567890';
            final formattedPhoneNumber = formatPhoneNumber(phoneNumber);
            print(formattedPhoneNumber);
          

    This will output “(123) 456-7890”.

The formatPhoneNumber function uses regular expressions to find matches of the phone number pattern (3 digits, 3 digits, and 4 digits) and replace it with the desired format. If the input phone number does not match the pattern, it simply returns the original phone number.

Leave a comment