关于dart:Flutter在List <Widget>中找到Widget

Flutter find Widget in List<Widget>

我有一个小部件列表:

1
2
3
4
5
6
List<Widget> widgetList = List<Widget>();

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

现在我想在列表中找到WidgetB:

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

我要使用" key"属性来唯一标识每个小部件,但是我不确定要使用哪种类型的密钥或如何通过该密钥查找,也不知道这是正确的方法。

任何信息将对您有所帮助。


您需要传递每个小部件的键:

1
2
3
4
5
6
7
8
9
10
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));

现在您可以搜索:

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


如果您只想按Widget名称/类型进行比较,而不考虑其他任何内容。这也可以:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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);

还请注意,文档包含以下内容:

1
2
3
4
5
6
  /// 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.