flutter - 颤振广义参数?
问题描述
我有一个使用 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;
}
}
}
有什么方法可以改进代码吗?这类问题有什么最佳实践吗?
解决方案
您可以为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;
}
}
推荐阅读
- java - 砖块打破游戏:我如何打破砖块?
- javascript - 我有一种情况,如果 url 不起作用,我不想运行我的测试用例
- ios - 无法更改取消选择动画的动画持续时间
- c - 如何将混合类型数组转换为 char 数组并返回?
- php - 传递给 Maatwebsite\Excel\Excel::download() 的参数 2 必须是字符串类型,对象给定
- php - PHP获取第一个数字
- android - application/vnd.android.package-archive 未在 android 4.1 中显示 apk 文件
- visual-studio-code - 如何更改 VS Code 的“资源管理器”窗口中的字体?
- django - 表单操作中的 Django url 重定向
- database - 在 Dynamodb/Cassandra 类型数据库中查找 geohashes 的关键子字符串