Flutter:无法访问从另一个屏幕传递的数据
我正在尝试构建 2 个屏幕,一个包含产品列表,第二个包含产品详细信息,我使用 Firebase 来存储数据,因此我在第一个屏幕中从 Firestore 获取数据,一切都运行良好。 但是,在第二个屏幕中,我使用 Navigator
正确传递产品数据,但无法在 UI 中使用该数据。
这是我的第二个屏幕的代码:
如您所见,我无法在小部件树中使用名称变量,我看过以下视频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:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您传递数据的方式是正确的,但访问数据的方式不正确。
每当您尝试访问处于其状态的类的变量时,您都可以使用
widget
来执行此操作。因此,要访问名称或其他变量,只需执行以下操作:此外,如果唯一目的是传递和显示数据,则不需要
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:Additionally, if the only purpose is to pass and display the data, then, there's no need of a
StatefulWidget
, use aStatelessWidget
instead.[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.