Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

docs.flutter.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.

Learn more

Flutter 3.41 is live! Check out theFlutter 3.41 blog post!

Adding assets and images

How to use images (and other assets) in your Flutter app.

Flutter apps can include both code andassets (sometimes called resources). An asset is a file that is bundled and deployed with your app, and is accessible at runtime. Common types of assets include static data (for example, JSON files), configuration files, icons, and images (JPEG, WebP, GIF, animated WebP/GIF, PNG, BMP, and WBMP).

Specifying assets

#

Flutter uses thepubspec.yaml file, located at the root of your project, to identify assets required by an app.

Here is an example:

yaml
flutter:assets:-assets/my_icon.png-assets/background.png

To include all assets under a directory, specify the directory name with the/ character at the end:

yaml
flutter:assets:-directory/-directory/subdirectory/
Note

Only files located directly in the directory are included.Resolution-aware asset image variants are the only exception. To add files located in subdirectories, create an entry per directory.

Note

Indentation matters in YAML. If you see an error likeError: unable to find directory entry in pubspec.yaml then youmight have indented incorrectly in your pubspec file. Consider the following [broken] example:

yaml
flutter:assets:-directory/

Theassets: line should be indented by exactly two spaces below theflutter: line:

yaml
flutter:assets:-directory/

Theassets subsection of theflutter section specifies files that should be included with the app. Each asset is identified by an explicit path (relative to thepubspec.yaml file) where the asset file is located. The order in which the assets are declared doesn't matter. The actual directory name used (assets in first example ordirectory in the above example) doesn't matter.

During a build, Flutter places assets into a special archive called theasset bundle that apps read from at runtime.

Automatic transformation of asset files at build time

#

Flutter supports using a Dart package to transform asset files when building your app. To do this, specify the asset files and transformer package in your pubspec file. To learn how to do this and write your own asset-transforming packages, seeTransforming assets at build time.

Loading assets

#

Your app can access its assets through anAssetBundle object.

The two main methods on an asset bundle allow you to load a string/text asset (loadString()) or an image/binary asset (load()) out of the bundle, given a logical key. The logical key maps to the path to the asset specified in thepubspec.yaml file at build time.

Loading text assets

#

Each Flutter app has arootBundle object for easy access to the main asset bundle. It is possible to load assets directly using therootBundle global static frompackage:flutter/services.dart.

However, it's recommended to obtain theAssetBundle for the currentBuildContext usingDefaultAssetBundle, rather than the default asset bundle that was built with the app; this approach enables a parent widget to substitute a differentAssetBundle at run time, which can be useful for localization or testing scenarios.

Typically, you'll useDefaultAssetBundle.of() to indirectly load an asset, for example a JSON file, from the app's runtimerootBundle.

Outside of aWidget context, or when a handle to anAssetBundle is not available, you can userootBundle to directly load such assets. For example:

dart
import'package:flutter/services.dart'showrootBundle;Future<String>loadAsset()async{returnawaitrootBundle.loadString('assets/config.json');}

Loading images

#

To load an image, use theAssetImage class in a widget'sbuild() method.

For example, your app can load the background image from the asset declarations in the previous example:

dart
returnconstImage(image:AssetImage('assets/background.png'));

Resolution-aware image assets

#

Flutter can load resolution-appropriate images for the currentdevice pixel ratio.

AssetImage will map a logical requested asset onto one that most closely matches the currentdevice pixel ratio.

For this mapping to work, assets should be arranged according to a particular directory structure:

.../image.png.../Mx/image.png.../Nx/image.png...etc.

WhereM andN are numeric identifiers that correspond to the nominal resolution of the images contained within. In other words, they specify the device pixel ratio that the images are intended for.

In this example,image.png is considered themain asset, whileMx/image.png andNx/image.png are considered to bevariants.

The main asset is assumed to correspond to a resolution of 1.0. For example, consider the following asset layout for an image namedmy_icon.png:

.../my_icon.png       (mdpi baseline).../1.5x/my_icon.png  (hdpi).../2.0x/my_icon.png  (xhdpi).../3.0x/my_icon.png  (xxhdpi).../4.0x/my_icon.png  (xxxhdpi)

On devices with a device pixel ratio of 1.8, the asset.../2.0x/my_icon.png is chosen. For a device pixel ratio of 2.7, the asset.../3.0x/my_icon.png is chosen.

If the width and height of the rendered image are not specified on theImage widget, the nominal resolution is used to scale the asset so that it occupies the same amount of screen space as the main asset would have, just with a higher resolution. That is, if.../my_icon.png is 72px by 72px, then.../3.0x/my_icon.png should be 216px by 216px; but they both render into 72px by 72px (in logical pixels), if width and height are not specified.

Note

Device pixel ratio depends onMediaQueryData.size, which requires having eitherMaterialApp orCupertinoApp as an ancestor of yourAssetImage.

Bundling of resolution-aware image assets

#

You only need to specify the main asset or its parent directory in theassets section ofpubspec.yaml. Flutter bundles the variants for you. Each entry should correspond to a real file, with the exception of the main asset entry. If the main asset entry doesn't correspond to a real file, then the asset with the lowest resolution is used as the fallback for devices with device pixel ratios below that resolution. The entry should still be included in thepubspec.yaml manifest, however.

Anything using the default asset bundle inherits resolution awareness when loading images. (If you work with some of the lower level classes, likeImageStream orImageCache, you'll also notice parameters related to scale.)

Asset images in package dependencies

#

To load an image from apackage dependency, thepackage argument must be provided toAssetImage.

For instance, suppose your application depends on a package calledmy_icons, which has the following directory structure:

.../pubspec.yaml.../icons/heart.png.../icons/1.5x/heart.png.../icons/2.0x/heart.png...etc.

To load the image, use:

dart
returnconstAssetImage('icons/heart.png',package:'my_icons');

Assets used by the package itself should also be fetched using thepackage argument as above.

Bundling of package assets

#

If the desired asset is specified in thepubspec.yaml file of the package, it's bundled automatically with the application. In particular, assets used by the package itself must be specified in itspubspec.yaml.

A package can also choose to have assets in itslib/ folder that are not specified in itspubspec.yaml file. In this case, for those images to be bundled, the application has to specify which ones to include in itspubspec.yaml. For instance, a package namedfancy_backgrounds could have the following files:

.../lib/backgrounds/background1.png.../lib/backgrounds/background2.png.../lib/backgrounds/background3.png

To include, say, the first image, thepubspec.yaml of the application should specify it in theassets section:

yaml
flutter:assets:-packages/fancy_backgrounds/backgrounds/background1.png

Thelib/ is implied, so it should not be included in the asset path.

If you are developing a package, to load an asset within the package, specify it in thepubspec.yaml of the package:

yaml
flutter:assets:-assets/images/

To load the image within your package, use:

dart
returnconstAssetImage('packages/fancy_backgrounds/backgrounds/background1.png');

Sharing assets with the underlying platform

#

Flutter assets are readily available to platform code using theAssetManager on Android andNSBundle on iOS.

Loading Flutter assets in Android

#

On Android the assets are available through theAssetManager API. The lookup key used in, for instanceopenFd, is obtained fromlookupKeyForAsset onPluginRegistry.Registrar orgetLookupKeyForAsset onFlutterView.PluginRegistry.Registrar is available when developing a plugin whileFlutterView would be the choice when developing an app including a platform view.

As an example, suppose you have specified the following in your pubspec.yaml

yaml
flutter:assets:-icons/heart.png

This reflects the following structure in your Flutter app.

.../pubspec.yaml.../icons/heart.png...etc.

To accessicons/heart.png from your Java plugin code, do the following:

java
AssetManagerassetManager=registrar.context().getAssets();Stringkey=registrar.lookupKeyForAsset("icons/heart.png");AssetFileDescriptorfd=assetManager.openFd(key);

Loading Flutter assets in iOS

#

On iOS the assets are available through themainBundle. The lookup key used in, for instancepathForResource:ofType:, is obtained fromlookupKeyForAsset orlookupKeyForAsset:fromPackage: onFlutterPluginRegistrar, orlookupKeyForAsset: orlookupKeyForAsset:fromPackage: onFlutterViewController.FlutterPluginRegistrar is available when developing a plugin whileFlutterViewController would be the choice when developing an app including a platform view.

As an example, suppose you have the Flutter setting from above.

To accessicons/heart.png from your Objective-C plugin code you would do the following:

objc
NSString*key=[registrarlookupKeyForAsset:@"icons/heart.png"];NSString*path=[[NSBundlemainBundle]pathForResource:keyofType:nil];

To accessicons/heart.png from your Swift app you would do the following:

swift
letkey=controller.lookupKey(forAsset:"icons/heart.png")letmainBundle=Bundle.mainletpath=mainBundle.path(forResource:key,ofType:nil)

For a more complete example, see the implementation of the Fluttervideo_player plugin on pub.dev.

Loading iOS images in Flutter

#

When implementing Flutter byadding it to an existing iOS app, you might have images hosted in iOS that you want to use in Flutter. To accomplish that, useplatform channels to pass the image data to Dart asFlutterStandardTypedData.

Platform assets

#

There are other occasions to work with assets in the platform projects directly. Below are two common cases where assets are used before the Flutter framework is loaded and running.

Updating the app icon

#

Updating a Flutter application's launch icon works the same way as updating launch icons in native Android or iOS applications.

Launch icon

Android

#

In your Flutter project's root directory, navigate to.../android/app/src/main/res. The various bitmap resource folders such asmipmap-hdpi already contain placeholder images namedic_launcher.png. Replace them with your desired assets respecting the recommended icon size per screen density as indicated by theAndroid Developer Guide.

Android icon location

Note

If you rename the.png files, you must also update the corresponding name in yourAndroidManifest.xml's<application> tag'sandroid:icon attribute.

In your Flutter project's root directory, navigate to.../ios/Runner. TheAssets.xcassets/AppIcon.appiconset directory already contains placeholder images. Replace them with the appropriately sized images as indicated by their filename as dictated by the AppleHuman Interface Guidelines. Keep the original file names.

iOS icon location

Updating the launch screen

#

Launch screen

Flutter also uses native platform mechanisms to draw transitional launch screens to your Flutter app while the Flutter framework loads. This launch screen persists until Flutter renders the first frame of your application.

Note

This implies that if you don't callrunApp() in themain() function of your app (or more specifically, if you don't callFlutterView.render() in response toPlatformDispatcher.onDrawFrame), the launch screen persists forever.

Android

#

To add a launch screen (also known as "splash screen") to your Flutter application, navigate to.../android/app/src/main. Inres/drawable/launch_background.xml, use thislayer list drawable XML to customize the look of your launch screen. The existing template provides an example of adding an image to the middle of a white splash screen in commented code. You can uncomment it or use otherdrawables to achieve the intended effect.

For more details, seeAdding a splash screen to your Android app.

iOS

#

To add an image to the center of your "splash screen", navigate to.../ios/Runner. InAssets.xcassets/LaunchImage.imageset, drop in images namedLaunchImage.png,LaunchImage@2x.png,LaunchImage@3x.png. If you use different filenames, update theContents.json file in the same directory.

You can also fully customize your launch screen storyboard in Xcode by opening.../ios/Runner.xcworkspace. Navigate toRunner/Runner in the Project Navigator and drop in images by openingAssets.xcassets or do any customization using the Interface Builder inLaunchScreen.storyboard.

Adding launch icons in Xcode

For more details, seeAdding a splash screen to your iOS app.

Was this page's content helpful?

Unless stated otherwise, the documentation on this site reflects Flutter 3.38.6. Page last updated on 2025-09-05.View source orreport an issue.


[8]ページ先頭

©2009-2026 Movatter.jp