How to set Aspect Ratio on Image Size in Flutter

In this example, we are going to show you the easiest way to set auto aspect ratio on Image size in Flutter App. We will use AspectRatio() widget to achieve aspect ratio on the Image widget in Flutter.

Read This Also: How to Insert Image from Asset Folder in Flutter App

Container(
  child: AspectRatio(
    aspectRatio: 16/9, //aspect ratio for Image
    child: Image(
      image: AssetImage('assets/img.png'),
      fit: BoxFit.fill, //fill type of image inside aspectRatio
    ),
  ),
)

import 'package:flutter/material.dart';

void main() {
  runApp(
    MaterialApp( 
      home: MyApp()
    )
  );
}

class MyApp extends StatefulWidget{
  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
          appBar: AppBar(
              title:Text("Set Aspect Ratio on Image Size"), //appbar title
              backgroundColor: Colors.redAccent //appbar background color
          ),
          body: Container(
            alignment:Alignment.topCenter,
            padding: EdgeInsets.all(15),
             child: Column( 
                children:[
                      
                      Container(
                        child: AspectRatio(
                          aspectRatio: 16/9, //aspect ratio for Image
                          child: Image(
                            image: AssetImage('assets/img.png'),
                            fit: BoxFit.fill, //fill type of image inside aspectRatio
                          ),
                        ),
                      )

                ]
             )
          )
      );
  }
}

In this way, you can set the Aspect Ratio on the Image widget in Flutter.

No any Comments on this Article


Please Wait...