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

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

    A combination of both prior two posts, without the logging.

    Fallback defaults to null when not provided.

    T cast(dynamic x, {T fallback}) => x is T ? x : fallback;
    

提交回复
热议问题