Reviewing a question recently but could not post response due to lacking any reputation.
In this question regarding a compiletime error coming from using List<Map<String,Object>> there was a compile time error when trying to pull the value of the Object which was known to be either a String or a Widget.
My resolution was to use as when calling using the values 'as String' or 'as Widget' in the appropriate spots.
Another more elegant solution was to replace 'Object' with 'dynamic'.
I remember reading 'as' was discouraged where possible. I don't know why, and I feel it resolve the issue. Is this simply because it should be cast as a specific type when created? When trying to recreate in Dartpad I had no issues, potentially just a flutter issue?
Why does dynamic work, but Object doesn't in this scenario? I mean everything will be a subtype of object right?
Thanks,
Can copy and paste code across if required, felt context of attached question was valuable.
CodePudding user response:
- I remember reading 'as' was discouraged where possible. I don't know why, and I feel it resolve the issue. Is this simply because it should be cast as a specific type when created? When trying to recreate in Dartpad I had no issues, potentially just a flutter issue?
Explicit type casts are a code smell. They're not necessarily wrong or bad, but they're frequently indicative of APIs that are unnecessarily awkward and perhaps could be designed better to use the correct types in the first place.
Explicit casts are also brittle. They introduce potential runtime failure points. That is, if the actual (runtime) type of the object changed, the cast could fail, and that failure wouldn't be noticed at compilation time.
- Why does dynamic work, but Object doesn't in this scenario? I mean everything will be a subtype of object right?
dynamic
is a special type that disables static (compile-time) type-checking. Object
(like every other non-dynamic
type) is statically type-checked, so any methods that you call on it must be statically known to exist on that type.
Note that using dynamic
is brittle too since failures involving dynamic
types are inherently runtime failures. Using dynamic
also can be less readable in general; except when there's some obvious context, readers won't know what type you expect the object to be and therefore won't know what behavior you expect the called method to have.
Also see the Effective Dart recommendation: AVOID using dynamic unless you want to disable static checking.