0

I want to create a helper class that will extend only a class that is derived from an abstract class. I face the following problems.

  1. i need derived class to provide value to static member of an abstract class and access that value to the helper class.

  2. I need to create a fromMap static or factory constructor, the signature will be in the abstact but the implementation is from derived.

      abstract class DatabaseModel {
       static String tableName;
    
       Map<String, dynamic> toMap();
    
       factory DatabaseModel.fromMap(Map<String, dynamic> map) {
         throw UnimplementedError();
       }
     }
    
     class DatabaseHelper<T extends DatabaseModel> {
       Future<List<T>> getAllItems() async {
         Database db = await openDatabase('database.db');
         final List<Map<String, dynamic>> maps = await db.query(T.tableName);
    
         return List.generate(maps.length, (i) {
           return T.fromMap(maps[i]);
         });
       }
     }
    

Here i got the following error:

  1. The method 'fromMap' isn't defined for the type 'Type'. Try correcting the name to the name of an existing method, or defining a method named 'fromMap'
  2. he getter 'tableName' isn't defined for the type 'Type'. Try importing the library that defines 'tableName', correcting the name to the name of an existing getter, or defining a getter or field named 'tableName'. Thanks in advance
tluanga
  • 27
  • 4
  • [There are many questions just like this one](https://stackoverflow.com/search?q=%5Bdart%5D+t.fromjson). `static` methods and constructors in Dart are not part of a type's interface. I strongly recommend using [`package:json_serializable`](https://pub.dev/packages/json_serializable) or [`package:built_value`](https://pub.dev/packages/built_value) and avoid implementing your own serialization/deserialization code. Alternatively pass around a `fromMap` callback appropriate for that type. – jamesdlin Mar 15 '23 at 02:17

0 Answers0