Question #317EasyWidgets & UI

What is an AspectRatio widget used for?

#widget#layout#aspectratio

Answer

Overview

The

text
AspectRatio
widget forces its child to maintain a specific width-to-height ratio, regardless of the available space.


Basic Usage

dart
AspectRatio(
  aspectRatio: 16 / 9,  // Width:Height = 16:9
  child: Container(
    color: Colors.blue,
  ),
)

If the available width is

text
320px
, the height will automatically be
text
180px
(320 × 9/16).


Common Aspect Ratios

RatioUse Case
text
16 / 9
Video players, YouTube thumbnails
text
4 / 3
Classic photos, older screens
text
1 / 1
Square images, profile photos
text
3 / 2
Photography (DSLR standard)
text
21 / 9
Ultrawide video

Video Player Example

dart
AspectRatio(
  aspectRatio: 16 / 9,
  child: VideoPlayer(_videoController),
)

Image Card Example

dart
Card(
  child: Column(
    children: [
      AspectRatio(
        aspectRatio: 16 / 9,
        child: Image.network(
          'https://example.com/image.jpg
          fit: BoxFit.cover,
        ),
      ),
      Padding(
        padding: EdgeInsets.all(8),
        child: Text('Image Title'),
      ),
    ],
  ),
)

Inside a List

dart
ListView.builder(
  itemCount: items.length,
  itemBuilder: (context, index) {
    return AspectRatio(
      aspectRatio: 16 / 9,
      child: Image.network(items[index].imageUrl, fit: BoxFit.cover),
    );
  },
)

How It Works

  1. text
    AspectRatio
    receives the available width from its parent constraint
  2. It calculates height = width / aspectRatio
  3. If the calculated height exceeds available height, it uses height and calculates width instead

Use Case: Use

text
AspectRatio
whenever you need a child widget to always maintain consistent proportions across different screen sizes — especially for media content like images and videos.