swapping elements in list

Viewed 4386

I have a list of 2 elements having randomly colored containers. I want to swap the first and second element. the code is

tiles.insert(1, tiles.removeAt(0));

It's working fine, swapping colors with each other all the time, but I can't figure out what is happening there. Can someone please explain what is going on?

full code: (obtained from https://medium.com/flutter/keys-what-are-they-good-for-13cb51742e7d)

void main() => runApp(new MaterialApp(home: PositionedTiles()));

class PositionedTiles extends StatefulWidget {
 @override
 State<StatefulWidget> createState() => PositionedTilesState();
}

class PositionedTilesState extends State<PositionedTiles> {
 List<Widget> tiles = [
   StatelessColorfulTile(),
   StatelessColorfulTile(),
 ];

 @override
 Widget build(BuildContext context) {
   return Scaffold(
     body: Row(children: tiles),
     floatingActionButton: FloatingActionButton(
         child: Icon(Icons.sentiment_very_satisfied), onPressed: swapTiles),
   );
 }

 swapTiles() {
   setState(() {
     tiles.insert(1, tiles.removeAt(0));
   });
 }
}

class StatelessColorfulTile extends StatelessWidget {
 Color myColor = UniqueColorGenerator.getColor();
 @override
 Widget build(BuildContext context) {
   return Container(
       color: myColor, child: Padding(padding: EdgeInsets.all(70.0)));
 }
}
2 Answers

For those coming here based on the question title, here is how you could swap elements in a Dart list:

int firstIndex = 0;
int secondIndex = 3;
final myList = ['a', 'b', 'c', 'd', 'e'];
final temp = myList[firstIndex];
myList[firstIndex] = myList[secondIndex];
myList[secondIndex] = temp;

// [d, b, c, a, e]

Or implementing that in an extension:

extension SwappableList<E> on List<E> {
  void swap(int first, int second) {
    final temp = this[first];
    this[first] = this[second];
    this[second] = temp;
  }
}

would allow you to use it like so:

final myList = ['a', 'b', 'c', 'd', 'e'];
myList.swap(0, 3); 

// [d, b, c, a, e]

tiles.insert(1, tiles.removeAt(0));

index:       0        1
tiles:     [ tileOne, tileTwo ]
  1. It removes the tile at index 0 which shifts the remaining elements down 1 to fill the space.
index:       0
tiles:     [ tileTwo ]
removed: tileOne
  1. It inserts the tile at index 1.
index:       0        1
tiles:     [ tileTwo, tileOne ]
Related