'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;
}
Solution 1:[1]
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);
});
},
)
Solution 2:[2]
The controller TileColorX will hold which tile has been selected (by using the index provided by ListView.builder).
import 'package:flutter/material.dart';
import 'package:get/get.dart';
class ListViewBoxConstraintsPage extends StatelessWidget {
final List<String> _items = ['first', 'second', 'third'];
@override
Widget build(BuildContext context) {
TileColorX tcx = Get.put(TileColorX());
return Scaffold(
appBar: AppBar(
title: Text('ListView Constraints'),
),
body: ListView.builder(itemCount: _items.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Obx(
() => Text('${_items[index]} item',
style: TextStyle(
color: tcx.selectedIndex.value == index ? Colors.green : Colors.red)
)),
onTap: () => tcx.toggle(index),
);
}),
);
}
}
class TileColorX extends GetxController {
RxInt selectedIndex = 0.obs;
void toggle(int index) => selectedIndex.value = index;
}
Solution 3:[3]
Please try to use setState in the onTap as shown below
onTap: () {
setState(() {
controller.toogle();
});
});
Solution 4:[4]
You have to add .value to the isSelected in your controller like this:
bool isSelected = false.obs;
toogle() {
isSelected.value = !isSelected;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Israel Gutierrez Salazar |
| Solution 2 | Baker |
| Solution 3 | Ramesh Guntha |
| Solution 4 | Mister.Perfect |
