首页 > 解决方案 > 从地图或列表加载小部件

问题描述

我有一个很长的报表小部件列表,它们基本上定义了数据的布局。我希望能够从其他一些执行条件(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?

标签: flutter

解决方案


您正在尝试创建字符串到子类映射 - 然后实例化子类的一个实例。这在没有镜像的 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);

推荐阅读