Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MediaQuery.of throws an exception inside MaterialApp

I’m newbie in Flutter.
I have very simple app

main.dart:

import 'package:dart_test/views/widgets/items/pack_items.dart';
import 'package:dart_test/views/widgets/items/pack_row.dart';
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    print("app build");
    var pdata =
        PackData(packId: 'npack1', name: 'Pack1', name_ru: 'пак 1', nImages: 5);
    //print("~w:$contW");
    return MaterialApp(
        home: PackBody(data: pdata, offset: 0).build(context));
  }
}

PackBody.dart:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class PackBody extends ListItem {
  final PackData data;
  final int offset;
  PackBody({required this.data, required this.offset});

  @override
  Widget build(BuildContext context) {
    var ar = 896.0 / 768;
    //var contWidth=MediaQuery.of(context).size.width;
    return Container(
      width: MediaQuery.of(context).size.width,
      height: 50,
      child: Text('khkljgkjhgkjhg'),
    );
  }
}

And it throws an exception:
enter image description here
I tried to wrap PackBody with MediaQuery – no luck
Shouldn’t MaterialApp provide MediaQuery down to the hierarchy?

>Solution :

What you are doing is the same as writing:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    print("app build");
    var pdata = PackData(packId: 'npack1', name: 'Pack1', name_ru: 'пак 1', nImages: 5);
    //print("~w:$contW");
    return MaterialApp(
      home: Container(
        width: MediaQuery.of(context).size.width,
        height: 50,
        child: Text('khkljgkjhgkjhg'),
      ),
    );
  }
}

The MediaQuery widget establishes a subtree in which media queries resolve to the given data. MaterialApp introduces a MediaQuery and keeps it up to date with the current screen metrics as they change. In order for MediaQuery.of(context) to work it needs to be in that subtree, and from the previous code sample I provided it clearly is not.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading