I use permission_handler package I need to convert string to permission E.g: "location" is string, need to convert Permission.location
CodePudding user response:
I think there are two solutions:
- 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
}
- 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
}