【问题标题】:Passing in a WIdget constructor function as an object parameter in Dart在 Dart 中将 WIdget 构造函数作为对象参数传入
【发布时间】:2020-07-04 22:31:36
【问题描述】:

我有一个简短的问题,关于 Dart 中是否可以执行以下操作:

我目前正在将我的各种屏幕组织成对象(目的地):

class Destination {

  final String title;
  final IconData icon;
  final Color color;
  final Function getScreen;

  const Destination(this.title, this.icon, this.color, this.getScreen);

}

然后我将创建这些对象的静态列表:

const List<Destination> allDestinations = <Destination>[
  Destination('Profile', Icons.person, backgroundColor, () => ProfileScreen()),
  Destination('Schedule', Icons.calendar_today, backgroundColor, () => ScheduleScreen()),
  Destination('Memberships', Icons.card_membership, backgroundColor, () => MembershipScreen())
];

在这种情况下,我尝试传递的函数 ("() => ProfileScreen()") 会导致错误:

  • “const 列表文字中的值必须是常量。”
  • “常量变量必须用常量值初始化。”

我想使用构建函数中的静态列表来调用构造函数并创建相应的屏幕。这纯粹是组织性的,所以我想知道是否有人知道是否有可能做我想做的事情或以一种干净的方式组织它,不胜感激。

谢谢。

【问题讨论】:

    标签: android iphone flutter dart mobile


    【解决方案1】:

    一个愚蠢的错误 - 将静态列表声明为“final”而不是“const”解决了这个问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-12
      • 1970-01-01
      • 2016-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-29
      • 2012-11-14
      相关资源
      最近更新 更多