Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: How to change text color using getX?

I want to change the color of a ListTile text on clicking on the tile how can I do that also the color should only be changed for a specific selected tile. My approach is as following:

ListView.builder(
        itemCount: _antigen.plantAntigens.length,
        itemBuilder: (BuildContext cntxt, int index) {
          return ListTile(
              title: Text(
                _antigen.plantAntigens[index],
                style: TextStyle(
                    color: controller.isSelected ? Colors.red : Colors.black87),
              ),
              onTap: () {
                controller.toogle();
              });
        },
      ),

The code for controller is as following:

bool isSelected = false.obs;

  toogle() {
    isSelected = !isSelected;
  }
like image 279
Aman Rawat Avatar asked Oct 16 '25 15:10

Aman Rawat


1 Answers

Just create a list in your controller that stores the selected index

  var plantAntigensSelected = [].obs;

  toogle(int index) {
    if (plantAntigensSelected.contains(index)) {
      plantAntigensSelected.remove(index);
    } else {
      plantAntigensSelected.add(index);
    }
  }

And your ListView like this

     ListView.builder(
        itemCount: plantAntigens.length,
        itemBuilder: (BuildContext cntxt, int index) {
          return ListTile(
              title: Obx(
                () => Text(
                  plantAntigens[index],
                  style: TextStyle(
                      color:
                      controller.plantAntigensSelected.contains(index)
                              ? Colors.red
                              : Colors.black87),
                ),
              ),
              onTap: () {
                controller.toogle(index);
              });
        },
      )
like image 147
Israel Gutierrez Salazar Avatar answered Oct 18 '25 07:10

Israel Gutierrez Salazar