简体   繁体   English

在 Flutter/Dart 中使用动态预加载图像

[英]Using dynamic preloaded image in Flutter/Dart

I currently have images which the image name is returned by a function and is dynamically called based on a variable like this:我目前有图像,其图像名称由函数返回,并基于这样的变量动态调用:

String _setImage() {
  if (currentQuestion > 1 && currentQuestion < 11) {
    return "assets/images/image_$intensityIndex.png";
  } else {
    return "assets/images/image.png";
  }
}

I want to switch to preloading the images and I am using the technique described at Preload images in a stateful widget on Flutter , but I am not sure how to have the function return an image which the name is dynamically determined based on another variable.我想切换到预加载图像,我正在使用在 Flutter 上的有状态小部件预加载图像中描述的技术,但我不确定如何让函数返回一个图像,该图像的名称是基于另一个变量动态确定的。 Here is what I have so far:这是我到目前为止所拥有的:

void initState() {
   super.initState();

  image0 = Image.asset('assets/images/image_0.png'); 
  image1 = Image.asset('assets/images/image_1.png');
  image2 = Image.asset('assets/images/image_2.png');
  image3 = Image.asset('assets/images/image_3.png');
}

void didChangeDependencies() {
  super.didChangeDependencies();

  precacheImage(image0.image, context);
  precacheImage(image1.image, context);
  precacheImage(image2.image, context);
  precacheImage(image3.image, context);
}

Image _setImage() {
  if (currentQuestion > 1 && currentQuestion < 11) {
    return ______________;
  } else {
    return image0;
  }
}

All help is appreciated!感谢所有帮助!

Am not sure how to return an image which the name is dynamically determined based on another variable我不确定如何返回名称是基于另一个变量动态确定的图像

You don't need to return with precach because if you use exact image that you cache.您不需要使用 precach return ,因为如果您使用缓存的确切图像。

Ex:前任:

precacheImage('assets/images/image_1.png'); // if this is the image name

Image.asset('assets/images/image_1.png'); // when you use this it is getting from the cache but the path should be same.

If I explain it another way:如果我换一种方式解释:

precacheImage("assets/images/image_$intensityIndex.png"); // image_1.png
Image.asset('assets/images/image_1.png'); // when you do this, asset taking from the cache by looking at the path.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM