显示随机图像Image.asset()抖动

时间:2019-11-18 04:42:36

标签: flutter flutter-layout

我想在image.asset()中显示随机图像,这就是我尝试过的

     static var listImagesnotFound = [
    "assets/cactusno.jpg",
    "assets/colorednot.jpg",
    "assets/juno.jpg",
    "assets/notfound.png",
    "assets/robno.png",
    "assets/spano.jpg"
  ];
  static var _random = Random();
  var imageToShow =
      listImagesnotFound[_random.nextInt(listImagesnotFound.length)];
}
Image.asset(listImagesnotFound.toString()),

2 个答案:

答案 0 :(得分:1)

只需将代码更改为

Image.asset(imageToShow.toString()),

答案 1 :(得分:1)

尝试一下:

 dynamic listImagesnotFound = [
    "assets/cactusno.jpg",
    "assets/colorednot.jpg",
    "assets/juno.jpg",
    "assets/notfound.png",
    "assets/robno.png",
    "assets/spano.jpg"
  ];
Random rnd;

Widget buildImage(BuildContext context) {
  int min = 0;
  int max = listImagesnotFound.length-1;
  rnd = new Random();
  int r = min + rnd.nextInt(max - min);
  String image_name  = listImagesnotFound[r].toString();
  return Image.asset(image_name);
}

Or

Image img() {
  int min = 0;
  int max = listImagesnotFound.length-1;
  rnd = new Random();
  int r = min + rnd.nextInt(max - min);
  String image_name  = listImagesnotFound[r].toString();
  return Image.asset(image_name);
}

Then call your buildImage or img function like :

buildImage(context), 

or

img(),

随机数可以生成任意数字,因此,如果您未使用最小值或最大值,则如果生成的随机数大于资产列表索引,则会返回错误。