The AspectRatio widget attempts to size the child to a specific aspect ratio.
Suppose we have a Container widget with width 100, and height 100. In that case the aspect ratio would be 100/100; that is, 1.0.
Now, each Widget has its own constraints. As a result, the AspectRatio Widget tries to find the best size to maintain aspect ratio. However, while doing so it respects it’s layout constraints.
Let’s see a screenshot where we have used three different types of aspect ratio.
![AspectRatio widget in Flutter](https://i0.wp.com/sanjibsinha.com/wp-content/uploads/2021/11/AspectRatio-widget-in-Flutter.jpg?ssl=1)
A Container widget has an AspectRatio widget, which has a child Container in a different color.
As a result, we see different types of color combination.
Let’s see the full code now.
import 'package:flutter/material.dart';
class AspectRatioSample extends StatelessWidget {
const AspectRatioSample({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'AspectRatio Sample',
debugShowCheckedModeBanner: false,
home: AspectRatioSampleHomme(),
);
}
}
class AspectRatioSampleHomme extends StatelessWidget {
const AspectRatioSampleHomme({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('AspectRatio Sample'),
),
body: Center(
child: Column(
children: [
Container(
color: Colors.red,
alignment: Alignment.center,
padding: const EdgeInsets.all(10),
width: 100.0,
height: 100.0,
child: AspectRatio(
aspectRatio: 2.0,
child: Container(
width: 50.0,
height: 50.0,
color: Colors.yellow,
),
),
),
const SizedBox(
height: 10,
),
Container(
color: Colors.blue,
alignment: Alignment.center,
width: 100.0,
height: 100.0,
child: AspectRatio(
aspectRatio: 2.0,
child: Container(
width: 80.0,
height: 70.0,
color: Colors.white,
),
),
),
const SizedBox(
height: 10,
),
Container(
color: Colors.green,
alignment: Alignment.center,
width: 100.0,
height: 100.0,
child: AspectRatio(
aspectRatio: 0.5,
child: Container(
width: 100.0,
height: 50.0,
color: Colors.black26,
),
),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {},
child: const Icon(Icons.add_a_photo),
),
);
}
}
Remember, in each case, the AspectRatio widget tries to find the best possible size and adjusts the child accordingly.
It comes to our help, when we try to change the size of an image on the fly.
Leave a Reply