Flutter - How to move element to end of List?

Viewed 7222

I have a ListView that displays a List in Flutter. I want the element to move to the end of the list on an onTap() and display that in my List? How do I do that?

Code:

List<String> list = ["A", "B", "C", "D", "E", "F"];

void main() {
  return runApp(
    MaterialApp(
      title: 'Flutter New AppDemo',
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: ListView(children: [
            listItem(list[1]),
            divider,
            listItem(list[2]),
            divider,
            listItem(list[3]),
            divider,
            listItem(list[4]),
            divider,
            listItem(list[5]),
            divider,
            listItem(list[0])
          ]),
        ),
      ),
    ),
  );
}

Widget divider = Container(height: 1, color: Colors.black);

Widget listItem(String text) {
  return Container(
    height: 100,
    padding: EdgeInsets.only(left: 16),
    child: Align(
      alignment: Alignment.centerLeft,
      child: Text(text),
    ),
  );
}

Example: I want to move element 'A' to the end of the List. enter image description here

enter image description here

2 Answers

You can make some modification to the code to achive this:

Send to the listItem widget the index of the elemnt from the list, not the String itself. Wrapt listItem widget in a gesturedetector that can record onTap.

Widget listItem(int index) {
  return GestureDetector(
    onTap: () {
      final String first = list.removeAt(index);
      list.add(first);
    },
    child: Container(
      height: 100,
      padding: EdgeInsets.only(left: 16),
      child: Align(
        alignment: Alignment.centerLeft,
        child: Text(list[index]),
      ),
    ),
  );
}
onTap: () {
   setState((){
       final String first = list.removeAt(0);
       list.add(first);
   });
}

The onTap it can be a button or you can use GestureDetector instead

Related