ushioishii
@ushioishii (ushi oishii)

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

No MediaQuery widget ancestor found.の解決方法

解決したいこと

No MediaQuery widget ancestor found.のエラーを解消したい。

flutter初心者です。
AppBarにタイトルを表示するために、教材通りのコードを書いたはずなのですが、上記のエラーが出てしまい、困っています。

発生している問題・エラー

======== Exception caught by widgets library =======================================================
The following assertion was thrown building MyApp:
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#d656e(lifecycle state: initialized, tickers: tracking 2 tickers)
The ownership chain for the affected widget is: "Scaffold ← MyApp ← [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.

該当するソースコード

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

// ignore: use_key_in_widget_constructors
class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
     appBar: AppBar(
     title: const Text("ranking"),
    ),
    );
  }
}

自分で試したこと

Google検索等してみましたが、原因を見つけられませんでした。

0

1Answer

下記のようにMaterialApp()でScaffoldを囲ってあげると解決するかと思います。


import 'package:flutter/material.dart';

void main() => runApp(MyApp());

// ignore: use_key_in_widget_constructors
class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
       home:Scaffold(
     appBar: AppBar(
     title: const Text("ranking"),
    ),
    ));
  }
}
0Like

Your answer might help someone💌