Search code examples
flutterdartdart-null-safety

Calling static method on type parameter renders method not defined error


Suppose this method:

  T? reviveObject<T>( dynamic value ) {

    if (  ( value is Map )
       && value.containsKey( '_type_' )
       && ( T.toString() == value[ '_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.

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 ) {