How to convert String to Permission in flutter

Issue

I use permission_handler package
I need to convert string to permission
E.g: "location" is string, need to convert Permission.location

Solution

I think there are two solutions:

  1. With the ability to manage names
    Make enum with all Permission’s values and static extension method that get as field String and returns Permission
extension NamedPermission on Permission {
  static Permission fromName(String permissionName) {
    switch (permissionName) {
      case 'location':
        return Permission.location;
      case 'contacts':
        return Permission.contacts;
      // other... 
      default:
        return Permission.unknown;
    }
  }
}

main() {
  print(NamedPermission.fromName('location'));
  //Result: Permission.location
}
  1. Concise and simple but without the ability to manage names
extension NamedPermission on Permission {
  static Permission fromName(String permissionName) {
    final matchedPermissions =
        Permission.values.where((e) => e.toString() == permissionName);
    if (matchedPermissions.isNotEmpty) return matchedPermissions.first;
    return Permission.unknown;
  }
}

main() {
  print(NamedPermission.fromName('location'));
  //Result: Permission.location
}

Answered By – Stanisalv ilin

Answer Checked By – Mary Flores (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *