如何确定当前页面是否在列表中?

huangapple go评论55阅读模式
英文:

How to find the page is currently in the list or not?

问题

我有一个页面列表。列表类型是 widget。当我尝试查找是否有任何元素与 HomePage 匹配时,它总是返回 false。

这是我的代码:

List<Widget> pages = [Home(), SecondPage(), ThirdPage(), SizedBox()]

当我使用条件 pages.contains(Home()) 进行检查时,它返回 false。

我该如何查找 HomePage 是否当前存在于列表中,以便我可以导航到正确的前一页。

英文:

I have a List of Pages. The list type is widget. when I tried to find if there is any element match with the HomePage it always return false.

This is my code:

List&lt;Widget&gt; pages = [Home(), SecondPage(), ThirdPage(),SizedBox()]

when I check with the condition pages.contains(Home()) it gives false.

how do I find if the HomePage is currently present in the list or not.So that I can navigate to the correct previous page.

答案1

得分: 2

你应该尝试使用 runtimeType

pages.map((e) -&gt; e.runtimeType).contains(Home().runtimeType)

原因:
在Flutter中,默认情况下,对象不相等(除了基本数据类型和字符串)。因此,两个 Home() 对象不相等。contains 方法使用相等性进行比较。类的 runtimeType 将是一个字符串,所以 contains 方法将有效。

英文:

You should try with runtimeType.

pages.map((e) -&gt; e.runtimeType).contains(Home().runtimeType)

Reason:
Objects in flutter are not equal (except primitive data types and String) by default. Hence 2 objects of Home() is not equals. contains works with equality. runtimeType of class will be string so contains will work.

答案2

得分: 1

这有助于你。

bool hasHome = pages.any((page) => page is Home);

Iterable any 方法

英文:

This helps you.

bool hasHome = pages.any((page) =&gt; page is Home);

Iterable any method

huangapple
  • 本文由 发表于 2023年2月8日 15:59:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/75382792.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定