小编Mik*_*ike的帖子

Flutter 使用 T 扩展接口创建通用函数

语境

在我的代码中,我有一个名为的接口AbstactDataModel,用作所有数据模型类的起点。实现这一点是为了让我知道无论xyzModel我需要什么类,它都会有一个fromJson(Map<String, dynamic> json)函数,该函数将返回使用给定的 json 和type.

// In abstract_model.dart
abstract class AbstractDataModel {
  ///
  /// returns a String containing the class name
  /// For example, the class ColumnModel will return 'column'
  ///
  String get type;

  ///
  /// Will call the [.fromJson] constructor and return a new instance of the
  /// object
  ///
  dynamic fromJson(Map<String, dynamic> json);
}
Run Code Online (Sandbox Code Playgroud)

下面是一个扩展了 DataModel 类的示例AbstractDataModel

// in group_model.dart
class GroupModel extends AbstractDataModel {
  int _id; …
Run Code Online (Sandbox Code Playgroud)

generic-programming function-templates dart flutter

7
推荐指数
1
解决办法
4012
查看次数