MediaQuery widget and Attributes

MediaQuery widget and Attributes

ยท

2 min read

The MediaQuery widget in Flutter is a powerful tool for building responsive layouts. It provides information about the current media, such as the size of the screen and device orientation. This allows developers to create UIs that adapt to various screen sizes and orientations.

Attributes:

  1. data (MediaQueryData?):

    • The media query data to use. If not provided, the MediaQuery widget will automatically obtain the MediaQueryData from the nearest ancestor MediaQuery widget.
  2. child (Widget):

    • The widget to which the media query data should be made available. Typically, the child widget consumes the MediaQuery data to adjust its layout or behavior accordingly.

Example:

import 'package:flutter/material.dart';

class MediaQueryExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('MediaQuery Widget Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Screen Width: ${MediaQuery.of(context).size.width}',
              style: TextStyle(fontSize: 18),
            ),
            Text(
              'Screen Height: ${MediaQuery.of(context).size.height}',
              style: TextStyle(fontSize: 18),
            ),
            SizedBox(height: 20),
            Text(
              'Orientation: ${MediaQuery.of(context).orientation}',
              style: TextStyle(fontSize: 18),
            ),
          ],
        ),
      ),
    );
  }
}

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

Explanation:

  • The MediaQuery widget is used to access information about the current media, such as screen size and orientation.

  • In the example, MediaQuery.of(context) retrieves the MediaQueryData for the current context.

  • The size property of MediaQueryData provides the size of the screen, and width and height are accessed to display the screen width and height.

  • The orientation property of MediaQueryData provides the orientation of the screen, whether it's portrait or landscape.

  • This information can be used to create responsive layouts that adapt to different screen sizes and orientations.

Did you find this article valuable?

Support Vinit Mepani (Flutter Developer) by becoming a sponsor. Any amount is appreciated!

ย