一、图片问题 Unable to load asset: images/bg.png
?
Performing hot reload...
Syncing files to device iPhone 12 Pro Max...
Reloaded 0 libraries in 36ms.
======== Exception caught by image resource service ================================================
The following assertion was thrown resolving an image codec:
Unable to load asset: images/bg.png
When the exception was thrown, this was the stack:
#0 PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:227:7)
<asynchronous suspension>
#1 AssetBundleImageProvider._loadAsync (package:flutter/src/painting/image_provider.dart:667:14)
<asynchronous suspension>
Image provider: AssetImage(bundle: null, name: "images/bg.png")
Image key: AssetBundleImageKey(bundle: PlatformAssetBundle#ae84f(), name: "images/bg.png", scale: 1.0)
====================================================================================================
解决方案:
-
pubspec.yaml
中,assets:
需要和uses-material-design: true
对齐 -
- 根目录/bg.png
,文件需从根目录开始引用 - 引用也需要从根目录开始
body: Image.asset('根目录/bg.png'),
二、@1x @2x @3x 适配?
解决方案:
在
images/
目录下生成2.0x
、3.0x
文件夹assets
中引用- images/2.0x/图片.png
、- images/3.0x/图片.png
三、声明所有图片?
解决方案:
在assets
中 只声明 文件夹名称,系统会自动适配。
assets:
- images/
- images/2.0x/
- images/3.0x/
四、图片如何 铺满全屏?
解决方案:
Image.asset(
'images/bg.png',
fit: BoxFit.fill,
width: double.infinity,
height: double.infinity,
),
单独铺满 BoxFit.fill
无效,需要配合 width
,height
来适配全屏幕。这里 double.infinity
表示最大值。
infinity
的值为:
static const double infinity = 1.0 / 0.0;
数学上 分母不为零,在Flutter
,表示无限大。
五、如何设置背景图片?
解决方案:
Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(
'images/bg.png', // 背景图片
),
fit: BoxFit.fill,
),
),
),