首页 > 解决方案 > Navigator.push 后上下文丢失

问题描述

Provider.of<IsSpecialist>(context).value

可在此 Navigator.push 上方访问:

Navigator.push(context, MaterialPageRoute(builder: (c) => ChatScreen()));

但在 Navigator.push 之后,它在 ChatScreen 中不可用:

Provider.of<IsSpecialist>(context).value

返回

Could not find the correct Provider above this Widget

为什么上下文被破坏了?如何保持原有的语境?我目前的临时解决方案是在 Navigator 之前从 Provider 获取 isSpecialist 并将其作为参数发送到 ChatScreen,但我需要找到更好的解决方案。

标签: flutterprovidernavigator

解决方案


上下文不会丢失,您只是使用了错误的上下文。假设A -> B -> C是小部件层次结构。

我认为您正在推动您的IsSpecialistatB并访问它,C但您使用的是A.

如果您可以发布更多代码来了解您的小部件层次结构,那就更清楚了。


推荐阅读