Skip to content
Related Articles

Related Articles

Build Responsive UI with Flutter

Improve Article
Save Article
Like Article
  • Last Updated : 21 Sep, 2021

In this article, we’ll go over the different widgets using which we can build responsive applications with Flutter.

1. The LayoutBuilder:

Builds a widget tree that can depend on the parent widget’s size. This is useful if we want to change or hide something depending on the parent size.

Dart




LayoutBuilder(
        builder: (BuildContext context, BoxConstraints constraints) {
            
         // constraints provide us with maxWidth,maxHeight etc, using 
         // which we can show different widgets accordingly
         if (constraints.maxWidth > 600) {
             
            // as the width is greater than 600px,
            // we'll show wide screen container
            return _buildWideScreenContainers();
          } else {
            return _buildPortraitContainer();
          }
        },
),

Let’s see that in an actual User Interface.

Dart




import 'package:flutter/material.dart';
  
void main() => runApp(const MyApp());
  
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}
  
class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar:
          AppBar(title: Text("Geeks for Geeks"), backgroundColor: Colors.green),
      body: LayoutBuilder(
        builder: (BuildContext context, BoxConstraints constraints) {
            
          // constraints provide us with maxWidth,maxHeight etc, using
          // which we can show different widgets accordingly
            
          if (constraints.maxWidth > 600) {
            // as the width is greater than 600px, we'll show wide screen container
            // with two containers in a row
              
            return _buildWideScreenContainers();
          } else {
            return _buildPortraitContainer();
          }
        },
      ),
    );
  }
  
  Widget _buildPortraitContainer() {
      
// here we're returning a single container since the phone
// doesn't has the required width (600px)
    return Center(
      child: Container(
        height: 100.0,
        width: 100.0,
        color: Colors.red,
      ),
    );
  }
  
  Widget _buildWideScreenContainers() {
      
// here we're returning double containers since the phone
// has the required width (600px)
    return Center(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          Container(
            height: 100.0,
            width: 100.0,
            color: Colors.red,
          ),
          Container(
            height: 100.0,
            width: 100.0,
            color: Colors.yellow,
          ),
        ],
      ),
    );
  }
}

When we run the code written above, this is what we get.

 

Notice how we see a single box when in portrait mode and double boxes when we rotate the phone.

2. MediaQuery

MediaQuery also lets us have the constraints. MediaQuery will not take constraints from the parent widget though, but instead, take it from the whole layout. Let’s see an example using MediaQuery(), where we hide the AppBar() depending on the screen width.

Dart




class MediaQueryExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final screenW = MediaQuery.of(context).size.width;
    print(screenW);
  
    return Scaffold(
        
      // when screen's width is less than 600px, 
      // it shows a appbar, when it's over 600px,
      // it hides it.
      appBar: screenW <= 600
          ? AppBar(
              title: Text("Geeks for Geeks"), backgroundColor: Colors.green)
          : null,
      body: Center(
        child: Text("Mediaquery example"),
      ),
    );
  }
}

Using MediaQuery(), we can have the screen size, aspect ratio, and other useful data.

final query = MediaQuery.of(context); // provide us with the query
    print(query.size.aspectRatio); //aspect ratio
    print(query.size.height);//screen height
    print(query.size.width);//screen width

3. BreakPoints

The BreakPoint can also be used for developing responsive UIs in flutter apps.

const kTabletBreakpoint = 768.0; //breakpoint for a tablet (a tablet's width is 768 px)
const kDesktopBreakPoint = 1440.0;  //breakpoint for desktop (a desktop screen's width is 1440 px)

const kSideMenuWidth = 300.0; // for sidemenu
const kNavigationRailWidth = 72.0; // for navigation rail

const kMaxWidth = 1180.0; // maximum width

We can use the breakpoints written above to display different UI for different devices. For Example,

Dart




class ResponsiveWidget extends StatelessWidget {
  const ResponsiveWidget({
    Key? key,
    required this.mobileBody,
    this.tabletBody,
    this.desktopBody,
  }) : super(key: key);
  
  final Widget mobileBody;
  final Widget? tabletBody;
  final Widget? desktopBody;
  
  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, dimens) {
          
        // check if the device is a phone
        if (dimens.maxWidth < kTabletBreakpoint) {
          return mobileBody;
        } else if (dimens.maxWidth >= kTabletBreakpoint && dimens.maxWidth < kDesktopBreakPoint)
        {
         // returns mobileBody if tabletBody is null
          return tabletBody ?? mobileBody;
        } else {
            
          // returns mobileBody if desktopBody is null
          return desktopBody ?? mobileBody;
        }
      },
    );
  }
}

Output: 

 Shows and hides the AppBar depending on the screen’s width using MedaQuery().

Shows and hides the AppBar depending on the parent’s width using LayoutBuilder().

For more information on handling different UI for different devices, kindly read this article. That’s it. This is all we need in order to get started on building responsive apps with flutter.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!