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

前端 未结 5 1717
囚心锁ツ
囚心锁ツ 2021-02-18 23:20

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

5条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-19 00:10

    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');
    

提交回复
热议问题