In Dart, syntactically nice way to cast dynamic to given type or return null?

Just use the as keyword

final tweet = tweets[index] as Tweet;

I use the following utility function, which allows for an optional fallback value and error logging.

T tryCast<T>(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');

I'm using those with Dart null safety (Dart SDK >= 2.12):

T? castOrNull<T>(dynamic x) => x is T ? x : null;

T castOrFallback<T>(dynamic x, T fallback) => x is T ? x : fallback;

Dart 2 has generic functions which allows

T? cast<T>(x) => x is T ? x : null;
dynamic x = something();
String s = cast<String>(x);

you can also use

var /* or final */ s = cast<String>(x);

and get String inferred for s

Tags:

Dart