flutter MediaQuery.of(context) called with a context that does not contain a MediaQuery.

本文详细探讨了在Flutter中使用MediaQuery.of(context)时遇到的常见错误及其解决方案。错误主要发生在未正确设置上下文或层级结构不当的情况下,尤其是在StatefulWidget内。文章提供了调整布局结构以避免错误的具体方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

更新:

这个问题基本上解决了。

有两种情况会发生这个问题。

一,widget外面不包含材料设计库的widget,材料设计库里面的widget有MediaQuery

二,层次性的会处于上面的东西会报这种错,比如说floatingactionbutton就是在其他层级上面的,在里面调用MediaQuery.of(context)也会报这个错

提示错误:

No MediaQuery ancestor could be found starting from the context that was passed to MediaQuery.of().
This can happen because you do not have a WidgetsApp or MaterialApp widget (those widgets introduce
 a MediaQuery), or it can happen if the context you use comes from a widget above those widgets.

上面的提示基本上已经解决了

----------------------------------------------------------------------------------------------------

MediaQuery.of(context)

这个函数经常报错,原因不清楚,flutter现在的资料实在是太少了

我这个报错的情况是将其放在了statefulwidget里面

所以,一定要将根布局换成一个statelesswidget里面

但是非常蛋疼,放在statelesswidget里面后textfield的状态又没法保存

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值