I asked similar question on this comment, but the team didn't really respond quite well. I am thus creating a new issue.
You can either use as
or type annotation to upcast or downcast things, let's take this example, where I have a SizedBox
and I want to upcast to a Widget
, so that I don't want to allow users to use width
property on it, in this example I am using as
to upcast, but this gives me a warning:
(Whenever I am writing bad
in comment, that means it is undesired behavior, and good
for desired one)
const widget = SizedBox() as Widget; // warning
final width = widget.width; // error (good)
Now if I take warning into consideration and modify my code to silence pedantic, I can do:
const widget = SizedBox(); // no warning (good)
final width = widget.width; // no error (bad)
But this allows me to access width
which I don't want.
Second solution is to use type annotation like:
const Widget widget = SizedBox(); // no warning (good)
final width = widget.width; // error (good)
So you can clearly see if I use as
, I get myself in trouble and can only do limited things but if I use type annotation, I can do things the way I want. Let's take one more example into consideration (thanks to @eernstg )
final foo = 1 as String; // no error (bad)
final String bar = 1; // error (good)
As you can see if I am again comparing as
with type annotation, the latter has advantages almost everywhere.