简体   繁体   中英

Passing in a WIdget constructor function as an object parameter in Dart

I had a quick question about whether or not the following is possible in Dart:

I am currently organizing my various screens into Objects (Destinations):

class Destination {

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

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

}

I am then creating a static list of these objects:

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())
];

In this case, the functions I try to pass ("() => ProfileScreen()") cause errors:

  • "The values in a const list literal must be constants."
  • "Const variables must be initialized with a constant value."

I'd like to use the static list in the build function to call on the contructor and create those respective screens. This is purely organizational, so I was wondering if anyone knew if it was possible to do what I'm intending or to organize it in a clean fashion, it would be greatly appreciated.

Thank you.

A silly mistake - declaring the static List as "final" instead of "const" fixed the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM