Home > Back-end >  How do I access MediaQuery information on materialApp?
How do I access MediaQuery information on materialApp?

Time:01-04

How can I access MediaQuery information on top of MaterialApp?

I need the height and width information of the device

CODE :

    final height =  MediaQuery.of(context).size.height; // I WANT TO REACH THIS !!!
    final width =  MediaQuery.of(context).size.width; // I WANT TO REACH THIS !!! IN HERE
    

    return MaterialApp(
        theme: ThemeData(
          primarySwatch: Colors.blue,
          visualDensity: VisualDensity.adaptivePlatformDensity,
        ),
        home: Home(),
      
    );
  }
}

THIS IS ERROR :

FlutterError (No MediaQuery widget ancestor found. MyApp widgets require a MediaQuery widget ancestor. The specific widget that could not find a MediaQuery ancestor was: MyApp The ownership chain for the affected widget is: "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.)


CodePudding user response:

It's hard to tell from such a small code excerpt, but I assume you are calling this in a build() method. MediaQuery are created by specific widgets, including WidgetsApp and MaterialApp. MediaQuery.of looks up the subtree from your widget which includes a MaterialApp, it does include one as an ancestor (up the tree).

You can fix this in a couple of ways, and they will likely improve your app's performance. One solution is to create the MaterialApp in your main() method and include everything else in your build code in the home() widget as a child of the MaterialApp. That way, the entire MaterialApp will not be rebuilt as often.

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

You can remove the MaterialApp from your build method

final height =  MediaQuery.of(context).size.height;
final width =  MediaQuery.of(context).size.width;

print('H: $height  W: $width');

return Home();

This runs are prints out the width and height.

CodePudding user response:

You can use enter image description here

  •  Tags:  
  • Related