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,
),
);
;
}
}
CodePudding user response:
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,
),
);
}
}
CodePudding user response:
Try this code. Better way to create a custom model with isSelected then change the value in onClick
class myClass extends StatefulWidget {
@override
State<myClass> createState() => _myClassState();
}
class _myClassState extends State<myClass> {
List color =[Colors.green, Colors.green, 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[index],
margin: EdgeInsets.all(10),
child: TextButton(
onPressed: () => setState(() {
print(color);
color.insert(index, Colors.red) ;
print(color);
}), child: Text("CLICK")),
),
itemCount: 3,
),
);
}
}
