【问题标题】:Change image onTap点击更改图像
【发布时间】:2020-07-10 11:31:42
【问题描述】:

我试图在每次 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),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    将您的 imagePath 放入您的 State 类(_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),
                  ),
                ),
              ),
            ),
          ),
        );
      }
    }
    

    【讨论】:

    猜你喜欢
    • 2019-02-01
    • 1970-01-01
    • 2011-11-05
    • 2012-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    相关资源
    最近更新 更多