簡體   English   中英

在 Dart 中將 WIdget 構造函數 function 作為 object 參數傳入

[英]Passing in a WIdget constructor function as an object parameter in Dart

我有一個關於 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);

}

然后我創建這些對象的 static 列表:

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 列表文字中的值必須是常量。”
  • “常量變量必須用常量值初始化。”

我想在構建 function 中使用 static 列表來調用構造函數並創建相應的屏幕。 這純粹是組織性的,所以我想知道是否有人知道是否有可能做我想做的事情或以一種干凈的方式組織它,我將不勝感激。

謝謝你。

一個愚蠢的錯誤——將 static 列表聲明為“final”而不是“const”解決了這個問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM