Home > OS >  how to select only one item in row, attaching index to bool value?
how to select only one item in row, attaching index to bool value?

Time:09-01

I have a row of containers which I should select and it should change the color, so I created a function hich should change the coor, but the problem is that it change color of every items not one by one. So the question is: how can I attach index to bool value, without using ListView.builder?

function which changes color:

   bool isSelected = true;
int index = 0;
      void changeColor() {
        isSelected = !isSelected;
        notifyListeners();
      }

part in code where I would like to use it:

/// change color
 color: products.isSelected ? Colors.white : Colors.orange,
///pressed the button
child: IconButton(
                      icon: Image.asset('assets/phone.png'),
                      onPressed: () {
                        products.changeColor();
                      },

CodePudding user response:

try this:

class _MyHomePageState extends State<MyHomePage> {
  int selectedContainer = 0;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Center(
        child: Row(
          children: [
            _buildContainer(0),
            _buildContainer(1),
            _buildContainer(2),
          ],
        ),
      ),
    );
  }

  _buildContainer(int index) {
    return Container(
      color: selectedContainer == index ? Colors.white : Colors.orange,
      child: IconButton(
          icon: Image.asset('assets/phone.png'),
          onPressed: () {
            setState(() {
              selectedContainer = index;
            });
          }),
    );
  }
}

CodePudding user response:

int isSelected = 0;
void changeColor(int selectedIndex) {
  isSelected = selectedIndex;
  notifyListeners();
}

//Here you have index inside ListView.builder pass that index to function
/// change color
 color: isSelected == index ? Colors.white : Colors.orange,
///pressed the button
child: IconButton(
  icon: Image.asset('assets/phone.png'),
  onPressed: () {
    products.changeColor(index);
},
  • Related