flutterdartphone-numbercountry-codes

Replace 0 in a phone number with country code


I use a library to get phone numbers from a mobile device but most of the numbers start with 0 for example:03004444444.But I noticed whatsapp converted it to country code(+92).I want to know how how to replace 0 with a country code in flutter.


Solution

  • To replace '0' with country code '+92' you can easily do that with replaceFirst method. But unfortunately it's not as simple as that. We need to check it whether the phone is a valid phone first, whether it's already '+92' in there, or whether it's started with leading '3'

    void main() {
      //   final String phone = '03004444444';
      final String phone = '0312345678901';
    
    
      print('original: $phone');
    
      // this regex assume after digit '3' there should be 9-11 characters after it
      final phoneRegex = RegExp(r'(0|\+?92)3\d{9,11}$');
    
      if (phoneRegex.hasMatch(phone)) {
        // if start with '0' then replace it with '+92'
        final String replaced = phone.startsWith('0') ? 
                                phone.replaceFirst('0', '+92') : phone;
    
        print('replaced: $replaced');
      } else {
        print('invalid phone');
      }
    } 
    

    You can check the code in this dartpad.

    As for dial code:

    WidgetsBinding.instance.window.locale.countryCode
    

    will only give you country code like 'US' not dial code.

    For dial code, there are many ways of getting it,

    I would recommend using this package called country_codes

    But in order to be used in widget you need make it StatefulWidget and then put code initialization in initState

    import 'package:country_codes/country_codes.dart';
    
    ...
    
    String? dialCode;
    
    @override
    void initState() {
      super.initState();
    
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
        // Optionally, you may provide a `Locale` to get countrie's localizadName
        await CountryCodes.init();
        final CountryDetails details = CountryCodes.detailsForLocale();
        setState(() {
          dialCode = details.dialCode;
        });
      });
    }