How to add padding or margin according to different screen sizes
Solution 1
Your can use MediaQuery.of(context).size.height
to get height of your screen and MediaQuery.of(context).size.width
to get width of your screen.
According to your image, it will be better to use Flex widgets like Expanded
, Spacer
, Flexible
to adjust the spacing between the widgets inside Column.
Solution 2
You can create two methods that accept BuildContext
double deviceHeight(BuildContext context) => MediaQuery.of(context).size.height;
double deviceWidth(BuildContext context) => MediaQuery.of(context).size.width;
And if you want uniform margin regardless of device width or height, use it like this
Padding(
padding: EdgeInsets.only(
top: deviceHeight(context) * 0.3,
left: deviceWidth(context) * 0.09,
bottom: deviceHeight(context) * 0.06,
),
child: Row(
children: <Widget>[
Image.asset(
'assets/logo.png',
height: 70,
width: 70,
),
Text(
' Whatsapp',
style: TextStyle(
fontSize: 26,
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
],
),
),
deviceHeight(context) * 0.3
simply means 30% of the screen Height, deviceWidth(context) * 0.09
means 9% of the screen Width & bottom: deviceHeight(context) * 0.06
means 6% of the screen Height
The advantage here is that you can adjust the figures to match, and it will take equal spacing on any device.
Arjun Mahar
Updated on December 20, 2022Comments
-
Arjun Mahar over 1 year
I want to give padding or margin according to screen sizes.
Below is code and images of two different sizes screens with same padding.
This is my code:
Padding( padding: const EdgeInsets.only(top: 160, left: 90, bottom: 20), child: Row( children: <Widget>[ Image.asset( 'assets/logo.png', height: 70, width: 70, ), Text( ' Whatsapp', style: TextStyle( fontSize: 26, color: Colors.white, fontWeight: FontWeight.bold, ), ), ], ), ),
My real device
Android Studio emulator