The AspectRatio widget in Flutter is used to enforce a specific aspect ratio for its child widget. It's commonly used to maintain the aspect ratio of a widget regardless of the parent's constraints, ensuring that the child widget maintains its desired width-to-height ratio.
Attributes:
aspectRatio (double):
- The desired aspect ratio to enforce for the child widget. It's specified as a ratio of width to height.
child (Widget):
- The child widget whose aspect ratio needs to be maintained.
Example:
import 'package:flutter/material.dart';
class AspectRatioExample extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('AspectRatio Widget Example'),
),
body: Center(
child: AspectRatio(
aspectRatio: 16 / 9, // Example aspect ratio: 16:9
child: Container(
color: Colors.blue,
child: Center(
child: Text(
'Aspect Ratio Example',
style: TextStyle(color: Colors.white),
),
),
),
),
),
);
}
}
void main() {
runApp(MaterialApp(
home: AspectRatioExample(),
));
}
In this example:
An AspectRatio widget is used to enforce a 16:9 aspect ratio for its child widget.
The aspectRatio attribute is set to 16 / 9, which represents the desired width-to-height ratio.
Inside the AspectRatio widget, a Container widget is used as the child widget, with a blue background color.
The child widget's content, a Text widget with the text "Aspect Ratio Example", is centered within the Container.
When you run this code, the child widget will maintain a 16:9 aspect ratio, ensuring that it retains its proportionality even as the parent's constraints change.