flutter - 从地图或列表加载小部件
问题描述
我有一个很长的报表小部件列表,它们基本上定义了数据的布局。我希望能够从其他一些执行条件(if/else)或切换的方式动态加载这些小部件。
class ReportLibrary {
final data;
ReportLibrary(this.data);
Map<String,Widget> _library = {
'QuestionsAndScores': QuestionScoresView,
};
Widget get(String key){
return _library[key](data);
}
}
我不确定这是否可能或有更好的方法。
这是错误:
flutter: Attempted to use type 'QuestionScoresView' as a function. Since types do not define a method 'call',
flutter: this is not possible. Did you intend to call the QuestionScoresView constructor and forget the 'new'
flutter: operator?
解决方案
您正在尝试创建字符串到子类映射 - 然后实例化子类的一个实例。这在没有镜像的 Dart 中是不允许的,你不能在 Flutter 中使用。
你为什么不使用 a switch
?它有点冗长,但会起作用。
Widget get(String key) {
case 'QuestionsAndScores':
return QuestionScoresView(data);
// etc
}
同样,你可以有一个字符串映射来运行:
final _library = <String, Function>{
'QuestionsAndScores': (data) => QuestionScoresView(data),
};
Widget foo = _library['QuestionsAndScores'](data);
推荐阅读
- python-3.x - altair 是否有滑块的“播放按钮”?
- c# - 使用 PictureBox 打开 dateTimePicker
- python-3.x - Python 类型注释,其中第二个参数是指第一个参数
- python - 将两个列表彼此相加,没有 sum 函数
- c# - 将 TransactionScope 与 OracleManagedDataAccess 一起使用会引发 System.PlatformNotSupportedException:“此平台不支持操作。”
- python - Pandas .isna() 循环时未被拾取
- android - 如何在颤动中破坏前一页?
- c - 不知道为什么我在这里遇到分段错误
- jquery - 如何从模型属性值的 jquery $each 循环中获取值
- java - 如何通过Java中的多个类写入单个文件?