'Flutter: State not working when creating many instances of the same class

I have a Target class that I'm constructing multiple instances of. I want to update a specific instance's image on tap (using GestureDetector). When I create multiple instances, they all seem to share the same state, and the last instance's image updates when I tap on any of the instances!

Here's code for the Target class:

import 'package:flutter/material.dart';

class Target extends StatefulWidget {
  final String image;
  final double height;
  final double width;

  Target(
      {Key? key,
      required this.image,
      required this.height,
      required this.width})
      : super(key: key);

  @override
  _TargetState createState() => _TargetState();
}

class _TargetState extends State<Target> {
  late String targetImage;
  late double targetHeight;
  late double targetWidth;

  @override
  void initState() {
    super.initState();
    targetImage = widget.image;
    targetHeight = widget.height;
    targetWidth = widget.width;
  }

  _on_click() {
    setState(() {
      if (targetImage == "assets/target.png") {
        targetImage = "assets/red_target.png";
      } else {
        targetImage = "assets/target.png";
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      child: ClipRRect(
        borderRadius: new BorderRadius.circular(40.0),
        child:
            Image.asset(targetImage, height: targetHeight, width: targetWidth),
      ),
      onTap: () => {_on_click()},
    );
  }
}

and when I create multiple instances as so:

Target headTarget = Target(
      key: const Key('A'), image: "assets/target.png", height: 160, width: 40);
  Target chestTarget = Target(
      key: const Key('B'), image: "assets/target.png", height: 400, width: 40);

only the chestTarget's image gets updated when I tap on either target.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source