0

I want only the item I click on to change color, but all items inherit the new color,
how can I have an isolated behavior per element in a list?

import 'package:flutter/material.dart';


class myClass extends StatefulWidget {
  @override
  State<myClass> createState() => _myClassState();
}

class _myClassState extends State<myClass> {

  Color color =Colors.green  ;
  List ListOfProfils = ["a","b","c"] ;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: ListView.builder(
        itemBuilder: (context, index) => Container(
          key: Key(ListOfProfils[index]),
          height: 100,
          width: 100,
          color : color,
          margin: EdgeInsets.all(10),
          child: TextButton(
              onPressed: () => setState(() {
                print(color);
                color =Colors.red  ;
                print(color);
              }), child: Text("CLICK")),
        ),
        itemCount: 3,
      ),
    );


     ;
  }
}
alireza easazade
  • 3,324
  • 4
  • 27
  • 35

1 Answers1

0

change your code to this.

class _myClassState extends State<myClass> {
  Color color = Colors.green;
  List ListOfProfils = ["a", "b", "c"];
  int selectedIndex = -1;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: ListView.builder(
        itemBuilder: (context, index) => Container(
          key: Key(ListOfProfils[index]),
          height: 100,
          width: 100,
          color: selectedIndex == index ? Colors.red : color,
          margin: EdgeInsets.all(10),
          child: TextButton(
              onPressed: () => setState(() {
                    selectedIndex = index;
                  }),
              child: Text("CLICK")),
        ),
        itemCount: 3,
      ),
    );
  }
}

Hadi
  • 586
  • 3
  • 11
  • it's a great idea and it works well, thank you. ( I only wonder if this is the solution adopted by everyone in this case ) – user18050794 Jan 27 '22 at 19:23