Home > OS >  How to create a map of widget references?
How to create a map of widget references?

Time:01-01

I am trying to create a Map<String, Widget> so that I can use it to dynamically determine which widget to use on the fly based on the key.

Scenario:

class WidgetA extends StatelessWidget {...}
class WidgetB extends StatelessWidget {...}
class WidgetC extends StatelessWidget {...}
class WidgetD extends StatelessWidget {...}

I want to create a map like:

const Map<String, Widget> map_to_widget = {
   'widgetA': WidgetA,
   'widgetB': WidgetB,
   ...
}

This will allow me to dynamically create widgets based on a list of widgets I need rendered. All of the above widgets would take in the same parameter so I would intend to use it like (still need to figure out how I would pass parameters):

return Container(
   child: map_to_widget('widgetA')
)

When I try to create the map, I keep getting the The element type 'Type' can't be assigned to the map value type 'Widget'.dartmap_value_type_not_assignable error.

CodePudding user response:

So the specific error comes from this:

'widgetA': WidgetA,

Above, WidgetA is not a widget, it is a type, similar to how 1 is an int but int is a type.

To fix this you would want to do something like this:

'widgetA': WidgetA(),

in order to actually create a widget.

The problem comes, as you say, when you want to pass parameters to those widgets. If the parameters are always the same no matter what, then you can pass them directly:

'widgetA': WidgetA(title: 'this is widget A'),

but if the parameters may change as you use the widgets, then you can't use a map of widgets for this, I propose a map of functions instead:

Map<String, Widget Function(String)> widgets {
  'widgetA': (title) => WidgetA(title: title),
  ...
}

This way, when getting the widget:

widgets['widgetA']('this is my title');
  • Related