Flutter:无法访问从另一个屏幕传递的数据

发布于 2025-01-14 06:21:21 字数 433 浏览 1 评论 0原文

我正在尝试构建 2 个屏幕,一个包含产品列表,第二个包含产品详细信息,我使用 Firebase 来存储数据,因此我在第一个屏幕中从 Firestore 获取数据,一切都运行良好。 但是,在第二个屏幕中,我使用 Navigator 正确传递产品数据,但无法在 UI 中使用该数据。

这是我的第二个屏幕的代码:

[!https://i.sstatic.net/BT1c9.png]

如您所见,我无法在小部件树中使用名称变量,我看过以下视频youtube 和我发现有些人使用状态管理来解决这个问题,但对于我的情况,我只想传递数据并显示它。

I'm trying to build 2 screens one contains a list of products and the second has product details, I'm using Firebase to store data and so I fetch the data from Firestore in the first screen and it all works perfectly.
However, in the second screen, I pass product data correctly using Navigator but I cannot use that data in my UI.

Here is the code for my second screen:

[!https://i.sstatic.net/BT1c9.png]

As you can see I cannot use the name variable in my widget tree, I've seen videos on youtube and I found that some people use state management to solve this problem, but for my case I just want to pass data and display it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

Oo萌小芽oO 2025-01-21 06:21:21

您传递数据的方式是正确的,但访问数据的方式不正确。

每当您尝试访问处于其状态的类的变量时,您都可以使用widget来执行此操作。因此,要访问名称或其他变量,只需执行以下操作:

widget.name

此外,如果唯一目的是传递和显示数据,则不需要 StatefulWidget,请使用 相反,StatelessWidget。

The way you've passed the data is correct but the way you've accessed the data isn't.

Whenever you try to access the variables of a Class in its state, you do that using widget. So, to access the name or other variables, just do as follows:

widget.name

Additionally, if the only purpose is to pass and display the data, then, there's no need of a StatefulWidget, use a StatelessWidget instead.

§普罗旺斯的薰衣草 2025-01-21 06:21:21

[State] 对象的配置是相应的 [StatefulWidget] 实例。该属性由框架在调用 [initState] 之前初始化。如果父级将树中的此位置更新为与当前配置具有相同 [runtimeType] 和 [Widget.key] 的新小部件,则框架将更新此属性以引用新小部件,然后调用 [didUpdateWidget],传递旧配置作为参数。

为此,您可以使用 widget.key,这对您来说效果很好。

A [State] object's configuration is the corresponding [StatefulWidget] instance. This property is initialized by the framework before calling [initState]. If the parent updates this location in the tree to a new widget with the same [runtimeType] and [Widget.key] as the current configuration, the framework will update this property to refer to the new widget and then call [didUpdateWidget], passing the old configuration as an argument.

For that you can use widget.key, this will work fine for you.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文