In this example, we are going to show you the way to get screen height and width and apply the sizing of child widgets according to the percentage of Screen height and width. It is very important for responsive design. See the example below:
See this also: How to get Device Screen Height and Width in Flutter App
double height = MediaQuery.of(context).size.height;
double width = MediaQuery.of(context).size.width;
You may get "No MediaQuery widget found" error, click here to fix this issue.
Container(
height: height * 0.1, //height to 10% of screen height, 100/10 = 0.1
width: width * 0.7, //width t 70% of screen width
color: Colors.lightBlue,
)
height and width variables are from the first code snippt.
SizedBox(
height: height * 0.09, //height to 9% of screen height,
width: width * 0.4, //width t 40% of screen width
child: ElevatedButton(
child: Text("Hello World"),
onPressed: (){
},
),
)
import 'package:flutter/material.dart';
void main() {
runApp(
MaterialApp( home: MyApp(),)
);
}
class MyApp extends StatefulWidget{
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
double height = MediaQuery.of(context).size.height;
double width = MediaQuery.of(context).size.width;
return Scaffold(
appBar: AppBar(
title:Text("Percentage wise Sizing of Widget"),
backgroundColor: Colors.deepPurpleAccent
),
body: Container(
padding: EdgeInsets.all(15),
child: Column(
children:[
Container(
height: height * 0.1, //height to 10% of screen height, 100/10 = 0.1
width: width * 0.7, //width t 70% of screen width
color: Colors.lightBlue,
),
Divider(),
SizedBox(
height: height * 0.09, //height to 9% of screen height,
width: width * 0.4, //width t 40% of screen width
child: ElevatedButton(
child: Text("Hello World"),
onPressed: (){
},
),
),
]
)
)
);
}
}
In this way, you can size widget according to Device screen height and width in Flutter.
Please Wait...
No any Comments on this Article