Sub topic 4
Resolution-aware images with 2.0x and 3.0x folders
This chapter assumes you can declare assets in pubspec.yaml, load an image with Image.asset, and know that devicePixelRatio describes how many physical pixels make up one logical pixel. It covers how Flutter picks among several copies of one image, how those copies affect displayed size, and the mistakes that make images look blurry or oversized.
Why one image file is not enough
Flutter lays out widgets in logical pixels. A logical pixel is not a fixed number of screen pixels. On a basic display, one logical pixel is one physical pixel. On a typical phone it is two or three physical pixels. The ratio is the device pixel ratio (DPR).
A 100x100 image shown in a 100x100 logical box has enough detail on a DPR 1.0 screen. On a DPR 3.0 screen the same box covers 300x300 physical pixels, so the file is stretched threefold and looks soft. You could ship a 300x300 file for everyone, but then low-density devices decode and store nine times more pixels than they can display.
Flutter's answer is to let you ship several renditions of the same image and choose one at runtime. Your code names the image once. Flutter picks the file.
The folder convention
Put the base image in a directory. Next to it, create subdirectories named after the scale factor, each holding a file with the same name:
assets/images/logo.png (1.0x, 100 x 100 pixels)
assets/images/2.0x/logo.png (2.0x, 200 x 200 pixels)
assets/images/3.0x/logo.png (3.0x, 300 x 300 pixels)Four rules define the convention:
- The base file, directly in the directory, is the 1.0x version. Flutter treats it as the design size and as the fallback.
- A variant lives in a sibling subdirectory named for its scale: a number followed by
x. The usual names are2.0xand3.0x.1.5xand4.0xwork the same way. - The variant has the same file name and extension as the base file.
2.0x/logo.pngis a variant oflogo.png.2.0x/[email protected]is not. - The variant directory sits inside the directory that holds the base file. A
2.0xfolder at the top ofassets/does not apply toassets/images/logo.png.
You declare only the base assets in pubspec.yaml. The build tool looks for variant folders next to each declared file and bundles what it finds:
flutter:
assets:
- assets/images/Declaring a single file works the same way. The variants of logo.png are still discovered and bundled:
flutter:
assets:
- assets/images/logo.pngYou do not list assets/images/2.0x/ or assets/images/3.0x/. Listing them is harmless but unnecessary. It can also lead you to reference the variant paths directly, which is a mistake covered later.
The code that displays the image mentions only the base path:
import 'package:flutter/material.dart';
class Logo extends StatelessWidget {
const Logo({super.key});
@override
Widget build(BuildContext context) {
return Image.asset('assets/images/logo.png');
}
}How Flutter picks a variant
When an Image.asset widget resolves its image, it builds an image configuration from the current MediaQuery, which includes the device pixel ratio. AssetImage then compares that ratio with the scales available for the requested asset. The list of available scales comes from the asset manifest, which the build step generates from the folders it found.
The selection logic is:
- If a variant has exactly the device pixel ratio, use it.
- If the ratio is below the smallest scale, use the smallest.
- If the ratio is above the largest scale, use the largest.
- Otherwise the ratio falls between two scales. Compute their midpoint. If the ratio is below the midpoint, use the lower scale. If it is at or above the midpoint, use the upper scale.
The tie-breaking rule favors the larger file. On dense screens a slightly oversampled image looks better than a stretched one.
Here are the results for the 1.0x, 2.0x, and 3.0x set above:
| Device pixel ratio | Variant chosen | File size in pixels | Why |
|---|---|---|---|
| 1.0 | `logo.png` | 100 x 100 | Exact match |
| 1.25 | `logo.png` | 100 x 100 | Below the 1.0/2.0 midpoint of 1.5 |
| 1.5 | `2.0x/logo.png` | 200 x 200 | At the midpoint, so upper |
| 2.0 | `2.0x/logo.png` | 200 x 200 | Exact match |
| 2.625 | `3.0x/logo.png` | 300 x 300 | Above the 2.0/3.0 midpoint of 2.5 |
| 3.0 | `3.0x/logo.png` | 300 x 300 | Exact match |
| 3.5 | `3.0x/logo.png` | 300 x 300 | Above the largest scale |
Many Android phones report fractional ratios such as 2.625 or 2.75. The midpoint rule is what picks a file for them, so you do not need a variant for every ratio.
Missing variants change the table. If you ship only the base and 3.0x, the candidates are 1.0 and 3.0. The midpoint is 2.0, so a DPR 2.0 device gets the 3.0x file, and a DPR 1.9 device gets the 1.0x file. That second case is easy to miss and gives a visibly blurry image.
Logical size versus pixel size
The scale of the chosen file also sets the image's default displayed size. Flutter decodes the file and tags it with its scale. Without explicit dimensions, the widget's logical size is the pixel size divided by that scale:
- On DPR 1.0,
logo.pngis 100 pixels at scale 1.0, so the widget is 100 x 100 logical pixels. - On DPR 2.0,
2.0x/logo.pngis 200 pixels at scale 2.0, so the widget is still 100 x 100 logical pixels. - On DPR 3.0,
3.0x/logo.pngis 300 pixels at scale 3.0, so the widget is again 100 x 100 logical pixels.
The image occupies the same layout space on every device, and only the sharpness changes. This works only if each variant is the base size multiplied by its scale. If your 2.0x file is 250 pixels wide instead of 200, the widget will be 125 logical pixels wide on a DPR 2.0 phone, and your layout will differ between devices.
Explicit dimensions change the picture. If you write Image.asset('assets/images/logo.png', width: 120), Flutter still selects the variant by DPR, but then scales it to 120 logical pixels. On a DPR 3.0 device the 300-pixel file is drawn into 360 physical pixels, which is a slight upscale. Choose your base size to match the size you display it at.
Seeing the selection in your own app
You can ask AssetImage which file it would choose for any ratio, without a device that has that ratio. The following app resolves the key for several ratios and lists the results. It assumes the three logo.png files above exist and are declared as shown earlier.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: VariantReport()));
class VariantReport extends StatefulWidget {
const VariantReport({super.key});
@override
State<VariantReport> createState() => _VariantReportState();
}
class _VariantReportState extends State<VariantReport> {
late final Future<List<String>> _lines = _resolveAll();
Future<List<String>> _resolveAll() async {
const asset = AssetImage('assets/images/logo.png');
final lines = <String>[];
for (final ratio in [1.0, 1.5, 2.0, 2.625, 3.0, 3.5]) {
final key = await asset.obtainKey(
ImageConfiguration(devicePixelRatio: ratio),
);
lines.add('DPR $ratio -> ${key.name} (scale ${key.scale})');
}
return lines;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Variant selection')),
body: FutureBuilder<List<String>>(
future: _lines,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
}
if (!snapshot.hasData) {
return const Center(child: CircularProgressIndicator());
}
return ListView(
children: [
for (final line in snapshot.data!) ListTile(title: Text(line)),
],
);
},
),
);
}
}With the full 1.0x, 2.0x, 3.0x set, the list reads:
DPR 1.0 -> assets/images/logo.png (scale 1.0)
DPR 1.5 -> assets/images/2.0x/logo.png (scale 2.0)
DPR 2.0 -> assets/images/2.0x/logo.png (scale 2.0)
DPR 2.625 -> assets/images/3.0x/logo.png (scale 3.0)
DPR 3.0 -> assets/images/3.0x/logo.png (scale 3.0)
DPR 3.5 -> assets/images/3.0x/logo.png (scale 3.0)If you delete the 2.0x file and restart the app, the DPR 1.5 and 2.0 lines change to the 3.0x file or the base file according to the midpoint rule. Try it. Watching the output change is the quickest way to learn the rule.
Widget tests use a default device pixel ratio of 3.0. A test that finds the 3.0x file does not show what a DPR 2.0 device sees. Set the ratio explicitly in the test, for example with tester.view.devicePixelRatio, when you care about the choice.
Edge cases and common errors
Variants apply only to images loaded through AssetImage. Image.asset uses AssetImage internally, so it gets variants. rootBundle.load and rootBundle.loadString do not. They return the exact file you name, which is the base file. Do not expect a 2.0x copy of a JSON file to be selected on a high-density phone. Non-image data has no resolution.
Do not reference a variant path in code. Image.asset('assets/images/2.0x/logo.png') loads that file as an ordinary asset. It will use the 2.0x file on every device and may not even be treated as scale 2.0. Always name the base path and let Flutter choose.
Always ship the base file. The base file is the fallback and the key that code and the manifest refer to. A directory with only 2.0x/logo.png and 3.0x/logo.png may fail to resolve or fail the build. Provide the 1.0x file even if few devices use it.
Match names exactly. File names are case-sensitive on many systems. 2.0x/Logo.png does not pair with logo.png, and you will see a correct image on a case-insensitive macOS development machine and a missing variant in a Linux CI build.
Match the extension. A logo.png base with a 2.0x/logo.jpg variant is not paired.
Wrong sizes cause layout drift. Variants must be exact multiples of the base. The most common symptom is an icon that is slightly larger on one phone than on another. Check each file's pixel dimensions against the base multiplied by the scale.
A new variant does not appear after you add it. Asset files are collected when the app is built. A hot reload may not pick up a new file or folder. Stop the app and run it again. If the problem persists, run flutter clean and rebuild.
Variant folders in unrelated directories are ignored. Flutter does not search the whole project for 2.0x folders. Each variant folder must sit beside the base file it belongs to. If you reorganize assets/images/ into subfolders, such as assets/images/icons/, move the variant folders too, and declare each subfolder in pubspec.yaml because directory declarations are not recursive.
Designing the asset set
Every extra scale adds files, and size grows with the square of the scale. A 3.0x file has nine times the pixels of the base. Before generating three copies of everything, weigh these points:
- Photos and detailed raster art benefit most from 2.0x and 3.0x, and they are also the largest files. Compress them, and consider whether a 3.0x copy is visible at the displayed size.
- Simple icons and logos often suit a vector format instead. That needs a rendering package, which is outside this chapter, but it removes the variant folders entirely.
- Images used at several display sizes should be exported for the largest size you show, not the base size. Then every smaller use only downsamples.
- A deliberate gap is acceptable. Many projects ship 1.0x, 2.0x, and 3.0x and skip 1.5x and 4.0x, because the midpoint rule maps nearby ratios onto the files you do have.
- Large images shown small can use the
cacheWidthandcacheHeightparameters ofImage.assetso Flutter decodes at a smaller size and holds less memory. This is separate from variant selection, but it addresses the same concern.
Start from the largest source you have, and generate the smaller files by downscaling. Upscaling a small file to make a 3.0x variant adds bytes without adding detail.
Exercise
Your assets/images/ directory contains banner.png and 3.0x/banner.png, with no 2.0x folder. Which file does a device with a pixel ratio of 2.0 load when your code calls Image.asset('assets/images/banner.png')? Which file does a device with a ratio of 1.9 load?
Show answer
The available scales are 1.0 and 3.0, so the midpoint is 2.0. A ratio of 2.0 is not below the midpoint, so Flutter uses the upper scale and loads 3.0x/banner.png. A ratio of 1.9 is below the midpoint, so Flutter loads the base banner.png, which will look blurry. Adding a 2.0x/banner.png fixes this.
Exercise
A base icon.png is 48 x 48 pixels. You export 2.0x/icon.png at 100 x 100 pixels by mistake. On a device with a ratio of 2.0, what is the icon's logical size when you use Image.asset('assets/images/icon.png') with no width or height? What should the file size have been?
Show answer
The 2.0x file is chosen and tagged with scale 2.0, so the logical size is 100 / 2.0 = 50 logical pixels, not the intended 48. The file should have been 96 x 96 pixels, which is the base size times the scale.
Exercise
You call rootBundle.loadString('assets/data/config.json') on a phone with a pixel ratio of 3.0, and you have placed a different config.json in assets/data/3.0x/. Which file is read, and why?
Show answer
The base assets/data/config.json is read. Variant selection is done by AssetImage for images. rootBundle.loadString returns exactly the file you name, so the 3.0x copy is never chosen.