簡體   English   中英

Flutter 在列表中查找 Widget<Widget>

[英]Flutter find Widget in List<Widget>

我有一個小部件列表:

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

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

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

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

我認為“key”屬性是我應該用來唯一標識每個小部件的屬性,但我不確定要使用什么類型的鍵或如何通過鍵找到,也不確定這是否是正確的方法。

任何信息都會有所幫助,謝謝。

您需要為每個小部件傳遞密鑰:

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

現在您可以搜索:

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

如果您只想通過Widget名稱/類型進行比較而不考慮其他任何內容。 這也有效:

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

還要注意 doc 包含這樣的:

 /// 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 (ie, 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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM