flutterlocationdeviceregion

How can I add initialCountryCode to device current region country code in flutter IntlPhoneField


I need to get device region country code not based on device language setting but based on region. How can I get device country code.

await CountryCodes.init();

final Locale? deviceLocale = CountryCodes.getDeviceLocale();
profileEmployee.countryCode = (deviceLocale?.countryCode)!;

I used this code and this code refers to en_US when my phone language setting is English but I lived in Myanmar. I just want my_MM. How can I get not based on Language setting. enter image description here


Solution

  • From the device you can only get the language, if you want to get the region code, you will need to get the user location using geolocator https://pub.dev/packages/geolocator then you can use geocoding https://pub.dev/packages/geocoding to get code from coordinates.

    Get Location

    Future<Position> getCurrentLocation(BuildContext context) async {
      bool serviceEnabled;
      LocationPermission permission;
    
      serviceEnabled = await Geolocator.isLocationServiceEnabled();
      if (!serviceEnabled) {
        return Future.error('Location services are disabled.');
      }
    
      permission = await Geolocator.checkPermission();
      if (permission == LocationPermission.deniedForever) {
        return Future.error(
            'Location permissions are permanently denied, we cannot request permissions.');
      }
    
      if (permission == LocationPermission.denied) {
    
        permission = await Geolocator.requestPermission();
        if (permission != LocationPermission.whileInUse &&
            permission != LocationPermission.always) {
          return Future.error(
              'Location permissions are denied (actual value: $permission).');
        }
      }
    
      return await Geolocator.getCurrentPosition();
    }
    

    Decode location using Geocoding

    position = await getCurrentLocation(context);
    placeMarks = await placemarkFromCoordinates(position.latitude, position.longitude);
    if (placeMarks.isNotEmpty) {
        debugPrint('=======> ${placeMarks.first.isoCountryCode}');
    }
    

    It will show MM for Myanmar.