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

前端 未结 5 1731
囚心锁ツ
囚心锁ツ 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:09

    Dart 2 has generic functions which allows

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

    you can also use

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

    and get String inferred for s

提交回复
热议问题