flutter how do i set a command that my image will not repeat

flutter how do i set a command that my image will not repeat

Problem Description:

i have multiple image and it will change on every tap but currently the image will repeat.

how do i stop the image to repeat and after the last image is surface, there will have a pop up button.

Thanks in advance

class _SettingpageState extends State<Settingpage> {
  List<String> imagelist = [
    'lib/images/image1.png',
    'lib/images/image2.png',
    'lib/images/image3.png',
    'lib/images/image4.png',
    'lib/images/image5.png',
  ];
  late String imagePath;

  @override
  Widget build(BuildContext context) {
    imagelist.shuffle(); //shuffle over here
    var imagePath = imagelist[0]; //store random image over here
    return Scaffold(
      backgroundColor: Colors.black,
      body: Center(
          child: Container(
              height: 600,
              width: 600,
              color: Colors.black,
              child: GestureDetector(
                  child: Center(child: Image.asset(imagePath)),
                  onTap: () {
                    setState(() {});
                  }))),
    );
  }
}

Solution – 1

try this:

class _SettingpageState extends State<Settingpage> {
  List<String> imagelist = [
    'lib/images/image1.png',
    'lib/images/image2.png',
    'lib/images/image3.png',
    'lib/images/image4.png',
    'lib/images/image5.png',
  ];

  late int imageIndex;
  late String imagePath;

  void initRandomImage() {
    imageIndex = 0;
    imagelist.shuffle();
    imagePath = imagelist[0];
  }

  @override
  void initState() {
    initRandomImage();
    super.initState();
  }

  void showPopUpButton(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('shuffle list'),
        content: TextButton(
          child: Text('shuffle list'),
          onPressed: () {
            initRandomImage();
            Navigator.pop(context);
            setState(() {});
          },
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Center(
        child: Container(
          height: 600,
          width: 600,
          color: Colors.black,
          child: GestureDetector(
            child: Center(
              child: Center(child: Image.asset(imagePath)),
            ),
            onTap: () {
              if (imageIndex == imagelist.length - 1) {
                showPopUpButton(context);
              } else {
                imageIndex++;
                setState(() {
                  imagePath = imagelist[imageIndex];
                });
              }
            },
          ),
        ),
      ),
    );
  }
}
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject