How to Specify Height and Width in Percent with respect to the screen in Flutter

Mobile phone devices are of various sizes and resolutions. Developing a mobile app which looks similar in all these phones is not easy. In such cases, mentioning height and width in percent with respect to the screen can help you.

In Flutter, you can’t really specify some percent of width or height directly. You can make use of MediaQuery class which helps you to obtain metrics of the current screen. MediaQuery.of(context).size.width will give you the current width whereas MediaQuery.of(context).size.height will give you the current height.

Then, multiplying the obtained width or height with fractions will give you height or width with respect to the screen. For example MediaQuery.of(context).size.width*0.5 will give you 50% width with respect to the screen.

See the Flutter example below where the height of the button is 10% of the height of the screen and the width is 50% of the width of the screen.

import 'package:flutter/material.dart';


void main() => runApp(MyApp());


class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Welcome to Flutter',
      home: Body()
    );
  }
}

/// This is the stateless widget that the main application instantiates.
class Body extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Height and Width in Percent Example'),
      ),
      body: Center(
          child: SizedBox(
          width: MediaQuery.of(context).size.width*0.5,
          height: MediaQuery.of(context).size.height*0.1,
         child:RaisedButton(
            onPressed: () {},
            child: const Text('Button in Percent!', style: TextStyle(fontSize: 20)),
            color: Colors.blue,
            textColor: Colors.white,
            elevation: 5,
            
          )
          )
        ),
    );
  }
}

Following is the output of this Flutter example.

height and width in percent in flutter

Leave a Comment

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