多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[TOC] ## 概述 ## pubspec.yaml 指定文件 ``` flutter: assets: - assets/my_icon.png - assets/background.png ``` 指定目录 ``` flutter: assets: - directory/ - directory/subdirectory/ ``` ## 加载不同分辨率的图片 将逻辑请求资源映射到最接近当前[设备像素比](https://api.flutter-io.cn/flutter/dart-ui/FlutterView/devicePixelRatio.html)的资源 如 ``` .../my_icon.png .../2.0x/my_icon.png .../3.0x/my_icon.png ``` 设备像素比率为 1.8 的设备上,对应是`.../2.0x/my_icon.png`。如果是 2.7 的设备像素比,对应是`.../3.0x/my_icon.png` 加载资源的code ``` return const Image(image: AssetImage('graphics/background.png')); ``` > 注意:`lib/`是隐含的,所以它不应该包含在资源路径中 ## 平台共享 assets 在Android和 iOS 中加载 Flutter 资源文件 ### Android 在 Android 平台上,assets 通过[`AssetManager`](https://developer.android.google.cn/reference/android/content/res/AssetManager)API 读取 想要在 Java 插件中访问 icons/heart.png; ``` AssetManager assetManager = registrar.context().getAssets(); String key = registrar.lookupKeyForAsset("icons/heart.png"); AssetFileDescriptor fd = assetManager.openFd(key); ``` ### iOS 在 iOS 平台上,assets 资源文件通过[`mainBundle`](https://developer.apple.com/documentation/foundation/nsbundle/1410786-mainbundle)读取 ``` NSString* key = [registrar lookupKeyForAsset:@"icons/heart.png"]; NSString* path = [[NSBundle mainBundle] pathForResource:key ofType:nil]; ```