一、指定assets
Flutter也有asset这一概念,asset是打包到程序安装包中的,可在运行时访问。常见的asset类型包括静态数据(例如JSON文件)、配置文件、图标和图片(JPEG,WebP,GIF,动画WebP / GIF,PNG,BMP和WBMP)。
使用asset,需要先让asset被识别,在项目根目录中的pubspec.yaml中定义
flutter:
assets:
- images/user/login.png
- images/user/no_login.png
- images/swiper/photo1.jpg
- images/swiper/photo2.jpg
- images/record/record_start.png
- images/record/record_end.png
- assets/test.json
二、加载文本
DefaultAssetBundle.of(context).loadString("assets/test.json")
三、加载图片
image: DecorationImage(
fit: BoxFit.fitWidth,
image: AssetImage("images/user/splash.jpg"),
)
3.1 加载不同分辨率的图片
假设主要资源对应的分辨率为1.0,比如是72px72px,如果还有144px144px和216px216px的图片,那么可以在images文件夹下创建两个文件夹:2.0x和3.0x,将对应分辨率的图片拷贝进去,2.0x对应的是144px144px,3.0x对应的是216px*216px。
…images/login.png
…images/2.0x/login.png
…images/3.0x/login.png
在pubspec.yaml配置对应图片资源:
flutter:
assets:
- images/login.png
Flutter可以为当前设备加载适合其分辨率的图像,如果在设备像素比率为1.8会选择…images/2.0x/decode.png ,如果设备像素比率为2.8,会选择…images/3.0x/decode.png,设备选择的是相近的图片资源。
3.2 加载依赖包中的图片
AssetImage('icons/phone.png', package: 'best_icons')