jauhar_k
jauhar_k

Reputation: 113

swapping elements in list

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)));
 }
}

Upvotes: 11

Views: 10390

Answers (3)

ArthurT
ArthurT

Reputation: 367

Nowadays we can do:

yourList.swap(index0, index1)

This has been added to the 'collection' package as per collection v1.18.0

Here the source location: https://github.com/dart-lang/collection/blob/master/lib/src/list_extensions.dart#L221

Here the commit: https://github.com/dart-lang/collection/commit/7d44763d62f97698b15c08ee360d838dccb63c88

Upvotes: 0

Suragch
Suragch

Reputation: 512206

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]

Upvotes: 12

hola
hola

Reputation: 3500

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 ]

Upvotes: 6

Related Questions