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:
-
Add the “intl” package to your pubspec.yaml file:
dependencies: flutter: sdk: flutter intl: ^0.17.0
-
Run
flutter pub get
in your terminal to fetch the package. -
Import the necessary classes in your Dart file:
import 'package:intl/intl.dart';
-
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; }
-
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.
- Flutter firebase delete user
- Flutter fixed bottom container
- Flutter foreach break
- Flutter exception: invalid image data
- Flutter firstwhereornull
- Flutter file exists
- Html table javascript add column dynamically?
- Flutter expansiontile vertical padding
- Flutter firebase messaging onbackgroundmessage not working
- Flutter form reset not working