Skip to main content

Flutter Set Container Widget Width Height in Percentage

In our previous tutorials we have learn about finding device screen width height in flutter. The same findings are used in our this tutorial. When we define Container widget width height in percentage format then it works device respectively. This would make our app responsive in every device small size, medium size and large size.

Flutter Set Container Widget Width Height in Percentage:

1. We are using MediaQuery widget to find current device width height first. Then we would minus the Status bar height from device height to get actual screen height without status bar height.
 double deviceWidth = MediaQuery.of(context).size.width;
 double statusBarHeight = MediaQuery.of(context).padding.top;
 double totalDeviceHeight = MediaQuery.of(context).size.height;
 double mainHeight = totalDeviceHeight - statusBarHeight;
Code Explanation:
  • deviceWidth : The Actual device width in double number format.
  • statusBarHeight : Status bar height.
  • totalDeviceHeight : Total device height including Status bar height.
  • mainHeight : Minus the status bar height from total device height. To get actual height of our Root Container.
Note: If you are creating mobile device app with Status bar visible design then you would use mainHeight. If you are creating mobile app without Status bar full screen then you would use totalDeviceHeight for final calculation.
2. Creating Container widget with width height defined in percentage using given formula.
   Container(
          height: mainHeight * 0.30,
          width: deviceWidth * 0.50,
          color: Colors.green,
        ),
  • Here mainHeight * 0.30 means 30% height of total screen height.
  • Here deviceWidth * 0.50 means 50% width of total screen width.
Complete source code for main.dart file:
import 'package:flutter/material.dart';

void main() => runApp(const App());

class App extends StatelessWidget {
  const App({super.key});
  @override
  Widget build(BuildContext context) {
    double deviceWidth = MediaQuery.of(context).size.width;
    double statusBarHeight = MediaQuery.of(context).padding.top;
    double totalDeviceHeight = MediaQuery.of(context).size.height;
    double mainHeight = totalDeviceHeight - statusBarHeight;

    return MaterialApp(
        home: Scaffold(
            body: SafeArea(
                child: Center(
      child: Column(children: [
        Container(
          height: mainHeight * 0.30,
          width: deviceWidth * 0.50,
          color: Colors.green,
        ),
        Container(
          height: mainHeight * 0.30,
          width: deviceWidth * 0.50,
          color: Colors.red,
        ),
        Container(
          height: mainHeight * 0.40,
          width: deviceWidth * 0.50,
          color: Colors.purple,
        ),
      ]),
    ))));
  }
}
Screenshot:
Flutter Set Container Widget Width Height in Percentage

Comments