Flutter 添加图片和其他资源

400 阅读1分钟

Flutter 添加图片和其他资源

Flutter 使用 pubspec.yaml 文件,位于项目根目录,来识别应用程序所需的资源。

导入单张图片

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

批量导入图片

如果要包含一个目录下的所有 assets,需要在目录名称的结尾加上 /

flutter:
  assets:
    - directory/
    - directory/subdirectory/

需要注意的点

仅包含当前目录下的所有文件,以及子目录下(与主目录中的文件)的同名文件(请参阅 Asset 变体)。如果想要添加子文件夹中的文件,请为每个目录创建一个条目。

导入多分辨率的图片

.../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)

使用依赖包中的资源图片

例如,你的应用程序依赖于一个名为 my_icons 的 package,它的目录结构如下:

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

然后加载 image, 使用:

return const AssetImage('icons/heart.png', package: 'my_icons');