更改图片onTap

时间:2020-07-10 11:31:42

标签: flutter dart

我试图每次onTap更改图像。 但是以某种方式,图像仅被更改一次。 请查看这段代码,并指出我要去哪里哪里

import 'package:flutter/material.dart';

class Demo extends StatefulWidget {
  @override
  _DemoState createState() => _DemoState();
}

String imagePath = "images/img4.jpg";

class _DemoState extends State<Demo> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        child: Center(
          child: Container(
            width: 100,
            height: 100,
            child: GestureDetector(
              onTap: () {
                setState(() {
                  imagePath = "images/tmhm.jpg";
                });
              },
              child: CircleAvatar(
                maxRadius: 20.0,
                child: Image.asset(imagePath),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

1 个答案:

答案 0 :(得分:0)

将您的imagePath放入州立课程(_DemoState

import 'package:flutter/material.dart';

class Demo extends StatefulWidget {
  @override
  _DemoState createState() => _DemoState();
}

class _DemoState extends State<Demo> {
  String imagePath = "images/img4.jpg";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        child: Center(
          child: Container(
            width: 100,
            height: 100,
            child: GestureDetector(
              onTap: () {
                if(imagePath == "images/img4.jpg"){
                  imagePath = "images/tmhm.jpg";
                }else{
                  imagePath = "images/img4.jpg";
                }
                setState(() {});
              },
              child: CircleAvatar(
                maxRadius: 20.0,
                child: Image.asset(imagePath),
              ),
            ),
          ),
        ),
      ),
    );
  }
}