Flutter code that continues to switch pics until you release screen

孤街醉人 提交于 2019-12-11 18:44:57

问题


i wanted to make a sample app,

where it will switch from pic 1, when longpressed to pic 2, then released it will switch to pic 3, then switch back to 1,

i have created a sample code, didnt work on my end using gesturedetector, it just stays on pic 1,

String image;

class unostate extends State<uno> {

  @override
  Widget build(BuildContext context) {

    return Center(
      child: GestureDetector(
        child: Image.asset(
          image = "assets/11.png",
          fit: BoxFit.none,
        ),
        onTapDown: (_){
          setState(() {
            image = "assets/12.png";
          });
        },
        onTapUp: (_){
          setState(() {
            image = "assets/13.png";
          });
        },
      ),
    );

  }

}

回答1:


Review your logic. I suggest you create a function that return the correct pic, and use only onTapDown or only onTapUp. On tap, your can call your function that return the correct pic.




回答2:


Something like that (not tested code):

String image;

class unostate {
  final allImages = ['assets/11.png', 'assets/12.png'];
  String currentImage;

  String getImagem(){
    allImages.forEach((String imageName){
      if(currentImage != imageName){
        //return a difrente image
        return imageName;
      }
    });
    //if not found, return a default image name
    return allImages[0];
  }

  @override
  Widget build(BuildContext context) {

    return Center(
      child: GestureDetector(
        child: Image.asset(
          image = currentImagem,
          fit: BoxFit.none,
        ),
        onTapDown: (_){
          setState(() {
            currentImage = getImagem();
          });
        },
      ),
    );

  }

}


来源:https://stackoverflow.com/questions/59178733/flutter-code-that-continues-to-switch-pics-until-you-release-screen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!