Search code examples
stringflutterdartcasting

Type cast string to another type


I am not sure just how possible this is but I am trying to receive text 'BoxFit.cover' from my data source, then type cast it and have it assigned to a variable of type BoxFit. This will allow me to customise my application via my datasource which is on a cloud database

BoxFit kLoginScreenBoxFit = 'BoxFit.cover' as BoxFit;

I get an error " type 'String' is not a subtype of type 'BoxFit' in type cast". is there a way of doing this?

I am not sure just how possible this is but I am trying to receive text 'BoxFit.cover' from my data source, then type cast it and have it assigned to a variable of type BoxFit. This will allow me to customise my application via my datasource which is on a cloud database

BoxFit kLoginScreenBoxFit = 'BoxFit.cover' as BoxFit;

I get an error " type 'String' is not a subtype of type 'BoxFit' in type cast". is there a way of doing this?


Solution

  • BoxFit is an enum. Therefore, you can match it by name by searching it's values like so:

    BoxFit boxFit = BoxFit.values.firstWhere((e) => e.toString() == 'BoxFit.cover');