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

时间:2019-12-14 11:30:25

标签: image flutter dart

我目前有一些图像,这些图像的名称由函数返回,并基于这样的变量被动态调用:

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

我想切换到预加载图像,并且正在使用Preload images in a stateful widget on Flutter中描述的技术,但是我不确定如何让函数返回图像,该图像的名称是根据另一个变量动态确定的。这是我到目前为止的内容:

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;
  }
}

感谢所有帮助!

1 个答案:

答案 0 :(得分:0)

  

我不确定如何返回名称动态的图像   根据另一个变量确定

您不需要return,因为如果您使用要缓存的确切图像。

例如:

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.

如果我用另一种方式解释它:

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.