skip to Main Content
import 'package:flutter/material.dart';
class Home extends StatelessWidget {
  const Home({super.key});

  @override
  Widget build(BuildContext context) {
    double screenWidth = MediaQuery.sizeOf(context).width;
    double screenHeight = MediaQuery.sizeOf(context).height;

    return SafeArea(
      child: Scaffold(),
    );
  }
}

What is the best way to declare MediaQuery objects? That should not effect the performance of the Flutter applciation.

4

Answers


  1. Chosen as BEST ANSWER

    I got a solution. Let me know is it correct or not

    import 'package:flutter/material.dart';
    extension MediaQueryValues on BuildContext {
      double get width => MediaQuery.of(this).size.width;
      double get height => MediaQuery.of(this).size.height;
    }
    

  2. I think you can measure the size values inside the build() method of root page, because root page in most cases won’t rebuild so it won’t gain the performance

    Then store these values in global variables, which can be accessed anywhere in the app

    Or even write down values to local storage and then read it next time without recalculation

    Login or Signup to reply.
  3. Use an extension to get it everywhere using context as a reference.

    import 'package:flutter/material.dart';
    
    extension MediaQueryValues on BuildContext {
        double get width => MediaQuery.sizeOf(context).width;
        double get height => MediaQuery.sizeOf(context).height;
    }
    
    Login or Signup to reply.
  4. You can create shortcut with extension class like

    import 'package:flutter/material.dart';
    extension MediaQueryExt on BuildContext {
      double get width => MediaQuery.of(this).size.width;
      double get height => MediaQuery.of(this).size.height;
    }
    

    And there is how to use it

    class Home extends StatelessWidget {
      const Home({super.key});
    
      @override
      Widget build(BuildContext context) {
        double screenWidth = context.width; // implement like this
        double screenHeight = context.height; // implement like this
    
        return SafeArea(
          child: Scaffold(),
        );
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search