How to change image dynamically in a list trailing onTap

653 views Asked by At

I was trying to change tutorial code. by adding a dynamic image in trailing and ontap to change the image. however the variable is changing but the image is not updating. Here is the relevant code:

void _pushSaved(){
    Navigator.of(context).push(
      MaterialPageRoute<void>(
        builder: (context){
          
          final tiles = _saved.map(
            (pair) {
              
              return ListTile(
                title: Text(
                  pair.asPascalCase,
                  style: _biggerFont
                ),
                trailing: GestureDetector(
                  
                  onTap: (){
                    if (imgName == "images/lion.jpg"){
                      imgName = "images/cat.jpg";
                    }else{
                      imgName = "images/lion.jpg";
                    }
                    setState(() {

                    });
                  },
                  child:Image.asset(imgName, fit: BoxFit.fitWidth),
                )
              );
            }
          );
          final divided = tiles.isNotEmpty ? 
            ListTile.divideTiles(
              context: context,
              tiles: tiles
            ).toList() : <Widget>[];
          
          return Scaffold(
            appBar: AppBar(
              title: const Text('Saved Suggestions'),
            ),
            body: ListView(children: divided)
          );
        }
      )
    );
  }

_pushSaved is called from onPressed and imgName defined at the top:

  String imgName = "images/cat.jpg";
  
  @override
  Widget build(BuildContext context) {
    /*
    final wordPair = WordPair.random();
    return Text(wordPair.asPascalCase);*/
    return Scaffold(
        appBar: AppBar(
          title: const Text('Startup Name Generator'),
          actions: [
            IconButton(
              icon: const Icon(Icons.list),
              onPressed: _pushSaved,
              tooltip: 'Saved Suggestions',
            )
          ]
        )

Tapping image doesn't change it but

1

There are 1 answers

2
user18309290 On

state is not changing, if a new value is not provided.

setState(() {
  if (imgName == "images/lion.jpg"){
    imgName = "images/cat.jpg";
  }else{
    imgName = "images/lion.jpg";
  }
});