How to create Responsive UIs in Flutter Using MediaQuery

Creating responsive user interfaces (UIs) in Flutter is essential for ensuring that your app looks great on any device, whether it’s a smartphone, tablet, or desktop. One of the most powerful tools for achieving this in Flutter is MediaQuery. In this blog, we’ll explore what MediaQuery is, how it works, and how you can use it to build responsive layouts that adapt to different screen sizes and orientations.

Responsive UIs in Flutter Using MediaQuery

What is MediaQuery?

In Flutter, MediaQuery is a widget that provides information about the size and orientation of the screen, as well as other properties like text scale factor, padding, and more. Essentially, MediaQuery is your go-to tool for responsive design. It helps you access important details about the device’s screen so that you can adjust your app’s layout accordingly.

Setting Up the Project

To get started with MediaQuery in Flutter, let’s set up a new Flutter project. If you haven’t already created one, you can do so by running the following command in your terminal:

flutter create media_query_demo

Once your project is ready, open it in your favorite code editor. Now, let’s dive into how MediaQuery works!

Basic MediaQuery Usage

Let’s start by exploring the basic usage of MediaQuery. We’ll create a simple Flutter app that displays the screen’s width and height.

import 'package:flutter/material.dart';

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

class MediaQueryDemoApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'MediaQuery Demo',
      home: MediaQueryExample(),
    );
  }
}

class MediaQueryExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // Get the screen width and height using MediaQuery
    final screenWidth = MediaQuery.of(context).size.width;
    final screenHeight = MediaQuery.of(context).size.height;

    return Scaffold(
      appBar: AppBar(
        title: Text('MediaQuery Example'),
      ),
      body: Center(
        child: Text(
          'Screen Width: $screenWidth\nScreen Height: $screenHeight',
          textAlign: TextAlign.center,
          style: TextStyle(fontSize: 20),
        ),
      ),
    );
  }
}

In this example, we’re using MediaQuery.of(context).size to get the width and height of the screen. This information is then displayed in the center of the screen using a Text widget.

Responsive Layout with MediaQuery

Now that we know how to get the screen dimensions, let’s use this information to create a responsive layout. We’ll design a simple app that displays different layouts based on the screen width.

class MediaQueryExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final screenWidth = MediaQuery.of(context).size.width;

    return Scaffold(
      appBar: AppBar(
        title: Text('MediaQuery Example'),
      ),
      body: screenWidth < 600 ? _buildSmallScreenLayout() : _buildLargeScreenLayout(),
    );
  }

  Widget _buildSmallScreenLayout() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.phone_android, size: 50),
          SizedBox(height: 20),
          Text('This is a small screen', style: TextStyle(fontSize: 20)),
        ],
      ),
    );
  }

  Widget _buildLargeScreenLayout() {
    return Center(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.desktop_windows, size: 50),
          SizedBox(width: 20),
          Text('This is a large screen', style: TextStyle(fontSize: 20)),
        ],
      ),
    );
  }
}

In this example, we’re using the screen width to determine which layout to show. If the screen width is less than 600 pixels, we display a column layout for small screens. Otherwise, we display a row layout for larger screens. This is a simple but powerful way to make your app responsive.

Handling Screen Orientation

Another common use case for MediaQuery is handling screen orientation. Let’s see how we can adjust our layout when the device is in landscape mode.

To detect the orientation, we can use MediaQuery.of(context).orientation. Here’s how you can modify your layout based on the screen orientation:

class MediaQueryExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final orientation = MediaQuery.of(context).orientation;

    return Scaffold(
      appBar: AppBar(
        title: Text('MediaQuery Example'),
      ),
      body: orientation == Orientation.portrait ? _buildPortraitLayout() : _buildLandscapeLayout(),
    );
  }

  Widget _buildPortraitLayout() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.portrait, size: 50),
          SizedBox(height: 20),
          Text('Portrait Mode', style: TextStyle(fontSize: 20)),
        ],
      ),
    );
  }

  Widget _buildLandscapeLayout() {
    return Center(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.landscape, size: 50),
          SizedBox(width: 20),
          Text('Landscape Mode', style: TextStyle(fontSize: 20)),
        ],
      ),
    );
  }
}

Now, when you rotate your device, the layout will change based on the orientation. In portrait mode, we display a column, and in landscape mode, we switch to a row.

Advanced MediaQuery Properties

MediaQuery offers more than just screen size and orientation. Let’s explore some advanced properties that can further enhance your responsive design.

Here are a few additional properties you might find useful:

Let’s modify our example to use these properties:

class MediaQueryExample extends StatelessWidget {
@override
Widget build(BuildContext context) {
final padding = MediaQuery.of(context).padding;
final textScaleFactor = MediaQuery.of(context).textScaleFactor;
final devicePixelRatio = MediaQuery.of(context).devicePixelRatio;

return Scaffold(
appBar: AppBar(
title: Text('Advanced MediaQuery Example'),
),
body: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Padding: $padding', style: TextStyle(fontSize: 16 * textScaleFactor)),
Text('Text Scale Factor: $textScaleFactor', style: TextStyle(fontSize: 16 * textScaleFactor)),
Text('Device Pixel Ratio: $devicePixelRatio', style: TextStyle(fontSize: 16 * textScaleFactor)),
],
),
),
);
}
}

In this example, we display the screen’s padding, text scale factor, and device pixel ratio. These properties can be crucial for fine-tuning your app’s UI to look consistent across different devices.

Best Practices and Tips

Before we wrap up, here are some best practices for using MediaQuery effectively in your Flutter apps:

By following these tips, you can create Flutter apps that provide a great user experience on any device.

Show Your Kind Support

Explore Other Flutter Topics…

  1. What is Flutter
  2. Stateful VS Stateless Widget
  3. Page Transition in Flutter
  4. Web Animation in Flutter
  5. Flutter Injectable
  6. Dependency Injection in Flutter
  7. Async and Await in Flutter
  8. Flutter Reusable Custom Widget
  9. Custom Shapes in Flutter using ClipPath
  10. Responsive UIs in flutter using MediaQuery

One Response

Leave a Reply

Your email address will not be published. Required fields are marked *