Screen Size: MediaQuery
Part of the Layout That Fits section of Coddy's Flutter journey. Lesson 16 of 30.
Phones come in many widths. To size something by the screen, ask Flutter how big the screen is:
final size = MediaQuery.of(context).size;
final width = size.width; // 390 on this phone
final height = size.height; // 844MediaQuery.of(context) reads facts about the screen the app runs on. .size is its width and height, in the same pixels as every other size you write.
The context is the one build receives. This app keeps its page in its own widget, HomeScreen, and reads the size at the top of its build, next to the page that uses it.
With the width in a variable, sizes become arithmetic: size.width / 2 is half the screen on any phone, and on a tablet too.
Challenge
EasyThe banner is always 200 pixels wide. Make it half the width of the screen, whatever the screen is.
Try it yourself
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: HomeScreen(),
);
}
}
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
final size = MediaQuery.of(context).size;
return Scaffold(
appBar: AppBar(title: const Text('Screen Size')),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('This screen is ${size.width.toStringAsFixed(0)} pixels wide'),
const SizedBox(height: 16),
Container(
width: 200,
height: 80,
color: Colors.deepOrange,
child: const Center(
child: Text('Banner', style: TextStyle(color: Colors.white)),
),
),
],
),
),
);
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Layout That Fits
1Sharing a Row
Expanded Fills the RowSharing Space With flexFlexible Hugs Its ChildSpacer Pushes Apart4Sizes and Breakpoints
Full Width: double.infinityA Maximum WidthScreen Size: MediaQueryLayoutBuilder BreakpointsPractice on your own: Online Flutter compiler