yolo
yolo

Reputation: 729

Changing one instance changes other instances of the same class

What I Did

I have a widget defined like this:

class Test extends StatelessWidget{
    @override
    Widget build(BuildContext context){
        bool disabled = false;

        return disabled ? A() : B();
    }
}

This Test class toggles between displaying A() and displaying B() in build. Also, they are also instantiated and stored in list.

List<Test> testList = [];

Finally, these are show in column:

Column(children: testList);

Problem

The problem is that if one of the instances has disabled = true, all instances in the same list will be treated as disabled = true.

For example, there are 100 testList elements, and disabled is set to true for the 0th instance as follows.

Then I checked 0th instance's disabled was true, and other instances disabled is falase with print().

But all instances return A().

What I Want to Do

What I want to do is change disabled to true for only some instances. I don't want changing one instance to affect other instances that didn't change.

Upvotes: 1

Views: 37

Answers (1)

Ante Bule
Ante Bule

Reputation: 2136

Your Test widget should be the StatefulWidget in order for it to have its own state and toggle for itself only. Something like this:

class Sample extends StatefulWidget {
  const Sample({Key? key}) : super(key: key);
  @override
  State<Sample> createState() => _SampleState();
}

class _SampleState extends State<Sample> {
  List<Test> widgets = [
    Test(),
    Test(),
    Test(),
    Test(),
    Test(),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Column(
          children: widgets,
        ),
      ),
    );
  }
}

class Test extends StatefulWidget {
  const Test({super.key});

  @override
  State<Test> createState() => _TestState();
}

class _TestState extends State<Test> {
  bool disabled = false;

  toggleDisabled() {
    setState(() {
      disabled = !disabled;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        disabled ? A() : B(),
        ElevatedButton(onPressed: toggleDisabled, child: Text('toggle')),
      ],
    );
  }
}

class A extends StatelessWidget {
  const A({super.key});

  @override
  Widget build(BuildContext context) {
    return Text('Element A');
  }
}

class B extends StatelessWidget {
  const B({super.key});

  @override
  Widget build(BuildContext context) {
    return Text('Element B');
  }
}

Upvotes: 1

Related Questions