What is AspectRatio Widget in Flutter: Simple Explanation and Example
AspectRatio widget in Flutter forces its child to have a specific width-to-height ratio. It helps keep UI elements proportional regardless of screen size by resizing the child to maintain the given ratio.How It Works
The AspectRatio widget works like a frame that keeps a fixed shape ratio for its child. Imagine you have a photo frame that always stays twice as wide as it is tall, no matter where you put it. The widget calculates the size it can take based on the available space and then adjusts its child's size to keep the ratio you set.
This means if the width grows, the height changes automatically to keep the same proportion, and vice versa. It’s very useful when you want consistent shapes on different screen sizes or orientations without manually calculating sizes.
Example
This example shows an AspectRatio widget with a ratio of 3:2 wrapping a colored box. The box will always be 1.5 times wider than it is tall.
import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('AspectRatio Example')), body: Center( child: AspectRatio( aspectRatio: 3 / 2, child: Container( color: Colors.blue, ), ), ), ), ); } }
When to Use
Use AspectRatio when you want to keep a consistent shape ratio for UI elements like images, videos, cards, or buttons across different devices. For example:
- Displaying a video player that must stay 16:9 regardless of screen size.
- Showing product images that should not stretch or squash.
- Creating buttons or cards that keep a balanced look on phones and tablets.
It saves you from manually calculating sizes and helps maintain a clean, professional design.
Key Points
- AspectRatio keeps child widget’s width and height proportional.
- The ratio is width divided by height (e.g., 3/2 means width is 1.5 times height).
- It adapts to available space but always respects the ratio.
- Useful for images, videos, cards, and any UI needing fixed proportions.