fit and size
- Flutter course
- Beginner
- Lesson 79/99
- 4 min
Learn image fit behavior with BoxFit.
What is BoxFit?
BoxFit is an enum that defines how an image fits into its allocated space. It is given via the fit parameter of the Image widget. The most common values are cover, contain, and fill; each shows a different fitting behavior.
Image.asset(
'assets/p.png',
fit: BoxFit.cover,
)cover, fill, and other values
BoxFit.cover fills the space completely while keeping the aspect ratio; overflowing parts are cropped. BoxFit.fill may break the aspect ratio to fill the space. Other values include fitWidth, fitHeight, none, and scaleDown.
BoxFit.cover // ratio kept, overflow cropped
BoxFit.fill // area filled, ratio may break
BoxFit.contain // whole image visible, gaps may remainPractice Set BoxFit.cover on Image.network
Show the image at https://picsum.photos/200 with Image.network and set fit to BoxFit.cover.
Starter code
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
// Image.network ile görsel göster, fit parametresini cover yap
child: null,
),
),
);
}
}Sample solution
import 'package:flutter/material.dart';
void main() {
print('BoxFit.cover');
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: Image.network(
'https://picsum.photos/200',
fit: BoxFit.cover,
),
),
),
);
}
}Expected output
BoxFit.cover
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does BoxFit.contain do?
- Only enlarges the image
- Stretches the image, breaking the aspect ratio
- Fills the area by cropping the image
- Fits the image keeping the aspect ratio, gaps may remain Correct answer
Explanation: BoxFit.contain shows the whole image proportionally; if the area isn't filled, gaps remain. To crop, use cover.
2 Set cover as the fit parameter
Image.asset(
'assets/p.png',
fit: ____,
)
Image.asset(
'assets/p.png',
fit: BoxFit.cover,
)
Explanation: cover fills the area completely and crops the overflow; contain leaves gaps.
3 BoxFit values
| Term | Meaning |
|---|---|
BoxFit.cover |
Keeps ratio, crops overflow |
BoxFit.contain |
Whole image visible, gaps remain |
BoxFit.fill |
Breaks ratio to fill the area |
BoxFit.scaleDown |
Shrinks but does not enlarge |