I am creating a demo where I have used listview builder to show all available categories from a list, now when I tap on item, it should be placed at the first place....
I have attached an image to make it more clear...
I tried with swiping but looks like not a proper way as it is affecting original list order;
here is my coding
class _Stack17State extends State<Stack17> {
@override
List<String> names = ['Shoes','Trousers','Jeans','Jacket','Belt','Others'];
int selectedindex = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Container(
height: 50,
color: Colors.white,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: names.length,
itemBuilder: (context, index) {
return InkWell(
onTap: (){
setState(() {
// I applied this logic, but looks like not proper way as it is spoiling or original list's order;
selectedindex=index;
swap(selectedindex);
selected index=0;
});
},
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 4),
child: Container(
padding: EdgeInsets.symmetric(horizontal: 30,vertical: 10),
decoration: BoxDecoration(
color: selectedindex==index?Colors.blue:Colors.blue.shade100,
borderRadius: BorderRadius.circular(20)),
child: Center(child: Text(names[index])),
),
),
);
}),
),
SizedBox(height: 10,),
Center(child: Text('Selected Category : ' names[selectedindex]),)
],
),
);
}
void swapitems(int index)
{
String temp;
temp=names[index];
names[index]=names[0];
names[0]=temp;
}
}
CodePudding user response:
Try this:
onTap: () {
var item = names[index];
names.removeAt(index);
names.insert(0, item);
setState(() {});
},
names[0]=temp;
just replace first Item with selected one. you need to use insert which shift the list and insert the selected item to the first place.