Сменить изображение на Tap - PullRequest
0 голосов
/ 10 июля 2020

Пытался каждый раз менять изображение на тапе. Но почему-то имидж меняется только один раз. Просмотрите этот фрагмент кода и укажите, где я ошибаюсь

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 голосов
/ 10 июля 2020

Поместите 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),
              ),
            ),
          ),
        ),
      ),
    );
  }
}
...