Elmer
Elmer

Reputation: 383

Flutter find Widget in List<Widget>

I have a list of widgets:

List<Widget> widgetList = List<Widget>();

widgetList.add(WidgetA());
widgetList.add(WidgetB());
widgetList.add(WidgetC());
widgetList.add(WidgetD());

Now I want to find WidgetB in the list:

Widget activeWidget = widgetList.firstWhere((x) => x.key == ??);

I'm assmuning the "key" property is what I should use to uniquely identify each widget but I'm not sure what type of key to use or how to find by the key, nor if this is the correct approach.

Any information would be helpful thanks.

Upvotes: 1

Views: 7720

Answers (2)

Blasanka
Blasanka

Reputation: 22437

If you just want to compare by only the Widget name/type without considering anything else. This is also works:

List<Widget> widgetList = [];

widgetList.add(WidgetA());
widgetList.add(WidgetB());
widgetList.add(WidgetC());
widgetList.add(WidgetD());

// using runtimeType
List widgets = widgetList.where((element) => element.runtimeType == WidgetD().runtimeType).toList();
Widget activeWidget = widgets.length > 0 ? widgets.first : null;
print(activeWidget);

// firstWhere() is the shorter form of above(I mean not how firstWhere implementation)
Widget activeWidget = widgetList.firstWhere((element) => element.runtimeType == WidgetD().runtimeType);
print(activeWidget);

Also note that doc contains like this:

  /// If the [runtimeType] and [key] properties of the two widgets are
  /// [operator==], respectively, then the new widget replaces the old widget by
  /// updating the underlying element (i.e., by calling [Element.update] with the
  /// new widget). Otherwise, the old element is removed from the tree, the new
  /// widget is inflated into an element, and the new element is inserted into the
  /// tree.

Upvotes: 1

Ademir Villena Zevallos
Ademir Villena Zevallos

Reputation: 1561

You need to pass the keys for each widget:

var keyA = UniqueKey();
var keyB = UniqueKey();
var keyC = UniqueKey();
var keyD = UniqueKey();
List<Widget> widgetList = List<Widget>();

widgetList.add(WidgetA(key: keyA));
widgetList.add(WidgetB(key: keyB));
widgetList.add(WidgetC(key: keyC));
widgetList.add(WidgetD(key: keyD));

And now you can search:

Widget activeWidget = widgetList.firstWhere((x) => x.key == keyB);

Upvotes: 5

Related Questions