3 ways to fit image in whole Screen/Space in Flutter
Enlarging an image to cover the entire screen can create a powerful visual impact, especially for background images. It immerses users in a specific atmosphere or theme.
Using a stretched image across different screens can provide a consistent look and feel throughout the app. It ensures uniformity in design, which can enhance the overall user experience.
Stretching an image simplifies the design process, especially when dealing with responsive layouts. It avoids the need to crop or adjust images for different screen sizes, making development more straightforward.
Fit image on screen in Flutter
Today we will see three methods to fit image on screen or fit in available space.
Method 1: Use FittedBox
To stretch an image to fit on whole screen, we will use FittedBox.
In Flutter, FittedBox is a widget that scales and positions its child within itself. It ensures that the child widget fits within the available space while maintaining its aspect ratio.
When we wrap a widget with FittedBox, it scales the child widget proportionally to fit within the parent widget’s dimensions. If the child widget’s aspect ratio doesn’t match the aspect ratio of the parent, the child will be fully contained within the parent, either horizontally or vertically, depending on the parent’s dimensions.
FittedBox(
child: Image.network(imageUrl),
fit: BoxFit.fill,
)
)
Method 2 : Use Container
We can also achieve this with the use of Container widget. We will decorate our container using BoxDecoration class. This class contains an image parameter of DecorationImage type.Which uses a fit parameter. We will set its value to BoxFit.fill. It will stretch image to whole screen or whole available space.
Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
decoration: BoxDecoration(
image: DecorationImage(
fit: BoxFit.fill,
image: NetworkImage(imageUrl),
),
),
)
Mehtod 3. : Using Stack
Stack widget also provide this functionality to stretch its child to whole space. To do this we will use Positioned widget in Stack.
Stack(
children: <Widget>[
new Positioned.fill(
child: Image.network(imageUrl,fit: BoxFit.cover,),
),
],
)
Positioned.fill is a positioning widget that can be used within a Stack widget to size a child widget to fill the available space. When you place a widget inside a Positioned.fill, it automatically expands to fill the entire area allocated by the parent Stack widget.
You can also learn how to add border on images in Flutter