首页 > 解决方案 > 颤振广义参数?

问题描述

我有一个使用 Moor 生成的数据库的颤振应用程序。

通常我需要 3 页,但由于所有 3 页看起来都一样,所以代码是一样的。唯一不同的是他们使用的 DAO。

所以我有FirstDao, SecondDao, ThirdDao. 它们都有list()方法并且它们都返回不同类型的对象(FirstType, SecondType, ThirdType)目前这是我使它工作的方式,但我不确定这是不是一个好方法:

class RollingListChoice<T> extends StatefulWidget {
  T dao;

  RollingListChoice(this.dao);

  @override
  _RollingListChoiceState createState() =>
      _RollingListChoiceState(dao);
 }

class _RollingListChoiceState<T> extends State<RollingListChoice> {
  T dao;

  _RollingListChoiceState(this.dao);


  @override
  Widget build(BuildContext context) {
    return Text(getDao().list());
  }


  getDao() {
    if (dao.runtimeType == FirstDao) {
      FirstDao mydao = dao as FirstDao;
      return mydao;
    } else if (dao.runtimeType == SecondDao) {
      SecondDaomydao = dao as SecondDao;
      return mydao;
    } else if (dao.runtimeType == ThirdDao) {
      ThirdDao mydao = dao as ThirdDao;
      return mydao;
    }
  }

}

有什么方法可以改进代码吗?这类问题有什么最佳实践吗?

标签: flutterdart

解决方案


您可以为DAO类(例如IDAO)提供一个接口,并替换RollingListChoice<T>RollingListChoice<T extends IDAO>以将类型限制T为特定类。这样,您就不需要dao输入getDao()方法,并且您将确定它dao具有list()方法。

abstract class IDAO {
  String list();
}

class RollingListChoice<T extends IDAO> extends StatefulWidget {
  T dao;

  RollingListChoice(this.dao);

  @override
  _RollingListChoiceState createState() =>
      _RollingListChoiceState(dao);
 }

class _RollingListChoiceState<T extends IDAO> extends State<RollingListChoice> {
  T dao;

  _RollingListChoiceState(this.dao);

  @override
  Widget build(BuildContext context) => Text(dao.list());
}

如果您确实提到了更改,则不需要getDao()方法,但您也可以getDao()像这样更改方法:

getDao() {
  if (dao is FirstDao) {
    FirstDao mydao = dao as FirstDao;
    return mydao;
  } else if (dao is SecondDao) {
    SecondDaomydao = dao as SecondDao;
    return mydao;
  } else if (dao is ThirdDao) {
    ThirdDao mydao = dao as ThirdDao;
    return mydao;
  }
}

推荐阅读