🐈

【Flutter】No MediaQuery widget ancestor found.を吐かれた時の対処

2022/10/16に公開

エラー文

======== Exception caught by widgets library =======================================================
The following assertion was thrown building Scaffold(dirty, state: ScaffoldState#f44d1(tickers: tracking 2 tickers)):
No MediaQuery widget ancestor found.

Scaffold widgets require a MediaQuery widget ancestor.
The specific widget that could not find a MediaQuery ancestor was: Scaffold
  dirty
  state: ScaffoldState#f44d1(tickers: tracking 2 tickers)
The ownership chain for the affected widget is: "Scaffold ← APIPage ← [root]"

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

This is a common mistake that happens when using Inherited Widgets like MediaQuery. Now you may not be using it explicitly but from your description it seems that Flutters' showModalBottomSheet method maybe using it.
The error is telling you that no MediaQuery ancestor(i.e. WidgetsApp, CupertinoApp or MaterialApp) could be found above context. It means above this context:

MediaQueryとかみたいなInherited Widgetを含むWidget・メソッドにはWidgetsApp, CupertinoApp, or MaterialApp widgetのどれかが親Widgetとして持っていなさいよ、ってことらしい。
具体的な有効なアクションとしてはcontextを含むbuild WidgetのreturnにMaterialAppを入れる
今回は「Scaffold widgets require a MediaQuery widget ancestor.」「ScaffoldはMediaQuery widgetを親に持て。」てこと

間違ってた部分

  • Scaffoldの親としてMaterialAppが無い。
main.dart
Widget build(BuildContext context) {
    child: Scaffold(
      appBar: AppBar(
        title: const Text('Flutter'),
      ),
      

直した部分

  • Scaffoldの親にreturn MaterialAppとして、home:Scaffoldを持たせる
main.dart
Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Flutter'),
        ),

結論

「No MediaQuery widget ancestor found.」=「親にMaterialApp付けろ」

所感

Inherited Widgetなどについて理解甘いのかなと思い要調査

大変参考になった記事

GitHubで編集を提案

Discussion