Zeswen
Zeswen

Reputation: 271

Make an instantiable list of Widgets in Flutter

I want to instantiate a Widget based on an int.

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 Types?

The JS similar would be 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. Widget1 needs the hey argument which is generated in its own Widget.

Upvotes: 2

Views: 1385

Answers (1)

Lorenzo Imperatrice
Lorenzo Imperatrice

Reputation: 997

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).

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;
  }
}

Upvotes: 1

Related Questions