Search code examples
fluttermedia-queriesflutter-web

MaterialApp as ancestor of MediaQuery widget. But how?


I am trying to make three different layouts according to the width of the window/screen. I get the error "No MediaQuery widget ancestor found." Since there are a lot of examples where people had problems with MediaQuery widget ancestry, I figured, I have to give the MediaQuery widget a MaterialApp as an ancestor. But I can't wrap my head around it, how I can achieve that? Can anybody help me?

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    var screenSize = MediaQuery.of(context).size;
    if (screenSize.width < 600) {
      return lay1();
    } else if (screenSize.width < 800) {
      return lay2();
    } else {
      return lay3();
    }
  }
}

Widget lay1() {
  return Container(
    color: Colors.lightGreenAccent,
  );
}

Widget lay2() {
  return Container(
    color: Colors.lightBlueAccent,
  );
}

Widget lay3() {
  return Container(
    color: Colors.orangeAccent,
  );
}

Solution

  • You should wrap your MyApp widget in a MaterialApp widget like this:

    void main() {
      runApp(const MaterialApp(
        home: MyApp(),
      ));
    }
    

    The MediaQuery instance is provided by MaterialApp. This is why you need to call MediaQuery.of(context) when getting the current instance of MediaQuery, and from there extracting the size of the view