简体   繁体   中英

show random images Image.asset() flutter

I want to show random images in image.asset() this is what I have tried

     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()),

Try this:

 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(),

Random number can gererate any number so if you are not using min or max value it will return you an error if random number generated is larger then your assets list index.

Just change your code to,

Image.asset(imageToShow.toString()),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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