AspectRatio in Flutter

18-Sep-2024

Learn how to control the aspect ratio of widgets using the AspectRatio widget in Flutter

AspectRatio widget is used to apply a specific aspect ratio to its child elements.
This is often used when you want to ensure  a fixed aspect ratio for widgets such as: B.
To maintain the correct proportions of images, videos, or containers

There Are Some Common Attributes for AspectRatio

aspectRatio
Set the desired aspect ratio (width / height)

Here's a simple example of using a AspectRatio in Flutter:

File open lib->main.dart file −



import 'package:flutter/material.dart';

void main() {
runApp(
MaterialApp(
home: Scaffold(
appBar: AppBar(
backgroundColor: Colors.blue,
title: Text('AspectRatio Example',
style:TextStyle(fontSize: 20,color: Colors.white)),
),
body: MyApp(),
),
)
);
}

class MyApp extends StatelessWidget {

@override
Widget build(BuildContext context) {
return
Center(
child: Center(
child: AspectRatio(
aspectRatio: 20/9, // Set the desired aspect ratio (width / height)
child: Container(
color: Colors.blue,
child: Center(
child: Text(
'Micro Tutorial',
style: TextStyle(fontSize: 20.0, color: Colors.white),
),
),
),
),
),
);

}
}





Open Device Manager, run the emulator, and then run the application. Next, check the working output and check the output you declared in your code.


Output:


Comments