flutterwidgetsetstategesturedetectoruser-interaction

Flutter - rebuild GestureDetector widget without user interaction


I am trying to display 3 images one after another by using GestureDetector and its onTap method but one image should be displayed without tapping. Supposing I have three images 1.png, 2.png, 3.png I would like to display the first image 1.png at the first place. Clicking on it will result in displaying the second image 2.png.
The second image 2.png should now be replaced after x seconds by displaying the image 3.png.

I am using a stateful widget that stores which image is currently shown. For the first image change the onTap will execute setState( () {screen = "2.png"} and the widget is rebuilt. However, I am pretty stuck now when the third image should be displayed after x seconds delay because there should not be any user interaction and I am not sure where to change it. I tried a lot of stuff especially editting the state from outside the widget but I did not succeed til now.

This is the code I am using:

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    debugShowCheckedModeBanner: false,
    title: 'Navigation Basics',
    home: MyScreen(),
  ));
}

class MyScreen extends StatefulWidget {
  @override
  _MyScreenState createState() => _MyScreenState();
}

class _MyScreenState extends State<MyScreen> {
  String currentScreen = 'assets/images/1.png';

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      child: FittedBox(
        child: Container(
          child: Image.asset(currentScreen),
        ),
        fit: BoxFit.fill,
      ),
      onTap: () {
        if (currentScreen == 'assets/images/1.png') {
          setState(() {
            currentScreen = 'assets/images/2.png';
          });
        }
      },
    );
  }
}


Displaying the second image worked without any issues but I have no idea what/where to code in order to display the third image.

Thanks for any help!


Solution

  • I'm assuming you don't want the second and third picture to respond to the gesture detection. Try this, please.

     onTap: () {
            if (currentScreen == 'assets/images/1.png') {
              setState(() {
                currentScreen = 'assets/images/2.png';
              });
    
              Future.delayed(const Duration(milliseconds: 3000), () {
                setState(() {
                  currentScreen = 'assets/images/3.png';
                });
              });
            } else {
              return;
            }
          },