Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calling static method on type parameter renders method not defined error

Suppose this method:

  T? reviveObject<T>( dynamic value ) {

    if (  ( value is Map )
       && ( value as Map ).containsKey( '_type_' )
       && ( T.toString() == ( value as Map )[ '_type_' ] )
    ) {
      print( '!! ' + T.toString()  );
      return T.fromJson( value as Map<String, dynamic> );
    }

    return null;

  }

reviveObject decodes some JSON to revive an object of T.

When called using e.g. reviveObject<EItem>(value ), EItem actually does have a EItem.fromJson() method.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Unfortunately, the type checker complains, that fromJson() is not defined in the above generic method.

How do I make the type checker not complain?

>Solution :

its not possible, check this answer know more details

TL;DR

Dart static method invocations are resolved at compile-time, so it’s not possible to call them on type variables which only have a value at run-time.

I got over this by passing the from json function of the Type that i want

i.e

T? reviveObject<T>( dynamic value, T Function(Object? json) fromJsonT ) {
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading