How can I display random image in flutter?

95 views Asked by At

I have five different images in the assets folder.

final List images = [ 'images/1.jpg', 'images/2.jpg', 'images/3.jpg', 'images/4.jpg', 'images/5.jpg', ];

I want the images to be displayed in a random order every time the user presses the button by using EvaluatedButton

3

There are 3 answers

0
Developer On

Please find below code snippet for your requirement

import 'dart:math';
import 'package:flutter/material.dart';

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {
 @override
 Widget build(BuildContext context) {
   return MaterialApp(
  home: RandomImageDisplay(),
);
}
}

class RandomImageDisplay extends StatefulWidget {
@override
_RandomImageDisplayState createState() => _RandomImageDisplayState();
}

class _RandomImageDisplayState extends State<RandomImageDisplay> {
 List<String> images = [
  'assets/images/1.jpg',
  'assets/images/2.jpg',
  'assets/images/3.jpg',
  'assets/images/4.jpg',
  'assets/images/5.jpg',
 ];

void _shuffleImages() {
setState(() {
  images.shuffle();
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
  appBar: AppBar(
    title: Text('Random Image Display'),
  ),
  body: Center(
    child: Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        ElevatedButton(
          onPressed: _shuffleImages,
          child: Text('Show Random Image'),
        ),
        SizedBox(height: 20),
        if (images.isNotEmpty)
          Image.asset(
            images[0],
            width: 200,
            height: 200,
          ),
      ],
    ),
  ),
);
}
}

P.S :- Please put your correct path for images in List<String> images.

0
Naser Ebedo On

Hi by using this method you can get a random number on each event

import 'dart:math';

void main() {
  int getRandomInteger(int num) {
    final random = Random();
    return random.nextInt(num);
  }

  print(getRandomInteger(6)); // images.length
}
1
Mayur Sankhla On

Just do one thing -

    ElevatedButton(
      onPressed: () {
       setState(() {
        images.shuffle();
      });
     },
    child: Text('Show Random Image'),
  ),