简体   繁体   English

在 Flutter 中创建一个可实例化的 Widget 列表

[英]Make an instantiable list of Widgets in Flutter

I want to instantiate a Widget based on an int.我想实例化一个基于 int 的 Widget。

const List<Widget> WIDGETS = <Widget>[
  Widget1,
  Widget2,
  Widget3,
  Widget4,
];

final int index = 1;

Navigator.pushReplacement(context, MaterialPageRoute<Widget>(builder: (BuildContext context) => WIDGETS[index](hey: index))));

However, I am getting the following error in the Widget list:但是,我在小部件列表中收到以下错误:

The element type 'Type' can't be assigned to the list type 'Widget'. dart(list_element_type_not_assignable)

I don't want to use dynamic or something similar, is there any way to declare that these are Widget Type s?我不想使用dynamic或类似的东西,有没有办法声明这些是 Widget Type s?

The JS similar would be typeof .类似的 JS 将是typeof


This is possible:这个有可能:

void a() {
  print('a');
}

void b() {
  print('b');
}

const List<Function> EXAM_SCREENS = <Function>[
  a,
  b,
  a,
  a,
];

Why isn't my scenario as such?为什么我的场景不是这样?

Edit: Just to clarify, I need to pass dynamic arguments to these widgets.编辑:为了澄清,我需要将动态 arguments 传递给这些小部件。 Widget1 needs the hey argument which is generated in its own Widget. Widget1需要在它自己的 Widget 中生成的hey参数。

Because they are not Widget until you initialize them, instead functions doesn't need to be initialized as they act like a variable (you are passing the pointer to the function).因为在初始化它们之前它们不是 Widget,因此不需要初始化函数,因为它们就像变量一样(您将指针传递给函数)。

So in this way:所以以这种方式:

const List<Widget> WIDGETS = <Widget>[
  Widget1,
  Widget2,
  Widget3,
  Widget4,
];

you're storing a list of Type, then if you try to change them like this you'll not get any errors.您正在存储类型列表,那么如果您尝试像这样更改它们,您将不会收到任何错误。

const List<Type> WIDGETS = <Type>[
  Widget1,
  Widget2,
  Widget3,
  Widget4,
];

For doing what you ask is necessary to radically change the approach by using a method to create the desired widget, to this method pass the index as parameter (or any parameters needed for choose the right widget to create) and, based on the parameters, the method will return the right Widget.为了做你所要求的,有必要通过使用创建所需小部件的方法从根本上改变方法,将索引作为参数(或选择要创建的正确小部件所需的任何参数)传递给该方法,并根据参数,该方法将返回正确的小部件。

Widget _chooseTheRightOne(int index, dynamic hey) {
  switch(index) {
     case 0: Widget1(hey: hey); break;
     case 1: Widget2(hey: hey); break;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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