skip to Main Content

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

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search