I have a dynamic x
and I would like to assign x
to T s
if x is T
, and otherwise assign null
to s
. S
I use the following utility function, which allows for an optional fallback value and error logging.
T tryCast(dynamic x, {T fallback}){
try{
return (x as T);
}
on CastError catch(e){
print('CastError when trying to cast $x to $T!');
return fallback;
}
}
var x = something();
String s = tryCast(x, fallback: 'nothing');