I hope this approach helps.
dynamic doSomething(dynamic str) { return str is String ? 'did something with $str' : null; }