Flutter:如何使用“通用”类构造函数?

时间:2019-11-07 14:22:18

标签: flutter

是否可以创建一个“通用”类构造函数,以代替(不能与其他类重复使用):

uploader.dart:

class Uploader extends StatefulWidget {
  const Uploader({
    Key key,
      @required this.event
    }) : super(key: key);
      final Event event;

    ...

    uploadEvent() async {
        await database.setEvent(widget.event)

database.dart:

Future<void> setEvent(Event event) async => await _service.setData(
    data: event.toMap(),
    docId: event.id,
  );

它变成了这样的东西:

uploader.dart:

class Uploader extends StatefulWidget {
  const Uploader({
    Key key,
      @required this.event
    }) : super(key: key);
      final T class;

    ...

    uploadEvent() async {
        await database.setGeneric(widget.generic)

database.dart:

Future<void> setGeneric(T generic) async => await _service.setData(
    data: generic.toMap(),
    docId: generic.id,
  );

是否可以做类似的事情?正确的术语是什么(以便我可以相应地更新问题)?

另一个选择是将event.toMap()传递给uploader.dart中的“最终地图通用”,但是我觉得有更好的解决方案?

1 个答案:

答案 0 :(得分:0)

T不是具有方法toMap()的对象的子类型。

u使用方法extends将其class设为onMap()

abstract class Base{
  toMap();
}

Future<void> setGeneric<T extends Base>(T generic) async => await _service.setData(
    data: generic.toMap(),
    docId: generic.id,
  );