What is the difference between dynamic and Object in dart?

Edited to update for null safety (use Object? instead of Object).

Another perspective on dynamic is that it’s not really a type – it’s a way to turn off type checking and tell the static type system “trust me, I know what I’m doing”. Writing dynamic o; declares a variable that isn’t typed – it’s instead marked as “not type-checked”.

When you write Object? o = something; you are telling the system that it can’t assume anything about o except that it’s an Object or null. You can call toString and hashCode because those methods are defined on Object and Null, but if you try to do o.foo() you will get a warning – it can’t see that you can do that, and so it warns you that your code is probably wrong.

If you write dynamic o = something you are telling the system to not assume anything, and to not check anything. If you write o.foo() then it will not warn you. You’ve told it that “anything related to o is OK! Trust me, I know what I’m doing”, and so it thinks o.foo() is OK.

With great power comes great responsibility – if you disable type-checking for a variable, it falls back on you to make sure you don’t do anything wrong.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)