Flutter:有没有办法确定上下文是否具有所需的提供者或上下文是否具有 MediaQuery

Flutter: Is There a way to identify if the context has the required provider or if context has MediaQuery

我有这样的情况,我在一个函数中使用 .of(context) 来获取作用域对象数据并使用它。但是,此函数有时会在未提供所需上下文的上下文中调用,因此无法使用并采用默认值。

我想做的是检查给定的 say MediaQuery 是否在上下文范围内并执行其他操作而不是使用默认值。

我们可以使用此方法找到小部件或数据在上下文的祖先中。

context.findAncestorWidgetOfExactType<T>() != null 

例如检查媒体查询数据是否在传递的上下文中 context.findAncestorWidgetOfExactType<MediaQuery>() != null

如果此检查 returns 为真,则我们在传递的上下文中有可用的 MediaQueryData。