在Flutter中预加载本地图像资产 [英] Preloading local image assets in Flutter
问题描述
我有一个简单的图像资产列表,并且在屏幕上有一个Image小部件。
I have a simple list of image assets, and I have one Image widget onscreen. I use a button to cycle through them, using setState().
const List<String> _photoData = const [
"assets/generic-cover.jpg",
"assets/generic-cover2.jpg",
"assets/generic-cover3.jpg",
"assets/generic-cover4.jpg",
];
class _MyHomePageState extends State<MyHomePage> {
int _coverPhoto = 0;
void _switchCoverPhoto() {
setState(() {
_coverPhoto++;
if (_coverPhoto == _photoData.length) {
_coverPhoto = 0;
}
});
}
@override
Widget build(BuildContext context) {
return new Scaffold(
body: new Stack(
children: <Widget>[
new Image.asset (
_photoData[_coverPhoto],
fit: ImageFit.cover,
height: 600.0,
),
new Positioned ( // photo toggle button
child: new IconButton(
icon: new Icon (Icons.photo),
onPressed: _switchCoverPhoto,
color: Colors.white,
),
top: 32.0,
right: 32.0,
),
]
)
);
}
第一张图像效果很好。但是,当我调用_switchCoverPhoto()时,在显示 assets / generic-cover2.jpg之前会有短暂的白色闪烁。
The first image renders fine. However, when I call _switchCoverPhoto(), there's a brief white flash before "assets/generic-cover2.jpg" gets shown.
这会引出一个简单的问题:是否有一种简单的方法可以将一个或多个后续图像预加载到内存中,从而使事先没有闪存?
Which leads to a simple question: Is there an easy way to preload a subsequent image (or images) into memory, so that there's no flash beforehand?
推荐答案
确保将 gaplessPlayback
设置为 true
为您的图片。
Make sure you have gaplessPlayback
set to true
for your image.
这不会解决预加载问题,但可以防止在切换资产时图片闪烁为白色
This won't solve the preloading problem, but it will prevent the image from flashing to white when switching assets.
gaplessPlayback设置为true,您的原始图像将一直保留到新图像完成加载为止,并且不会出现白色闪光间隙。
With gaplessPlayback set to true, your original image will remain until the new image has completed loading and no "white flash gap" will be present.
var img = new Image.asset(
_photoData[_coverPhoto],
fit: ImageFit.cover,
height: 600.0,
gaplessPlayback: true,
);
这篇关于在Flutter中预加载本地图像资产的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!