交换列表中的元素

jau*_*r_k 9 dart flutter

我有一个包含 2 个具有随机颜色容器的元素的列表。我想交换第一个和第二个元素。代码是

tiles.insert(1, tiles.removeAt(0));
Run Code Online (Sandbox Code Playgroud)

它工作正常,一直在相互交换颜色,但我不知道那里发生了什么。有人可以解释一下发生了什么事吗?

完整代码:(从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)));
 }
}
Run Code Online (Sandbox Code Playgroud)

Sur*_*gch 10

对于那些根据问题标题来到这里的人,以下是如何交换 Dart 列表中的元素:

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]
Run Code Online (Sandbox Code Playgroud)

或者在扩展中实现它:

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

将允许您像这样使用它:

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

// [d, b, c, a, e]
Run Code Online (Sandbox Code Playgroud)


hol*_*ola 5

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

index:       0        1
tiles:     [ tileOne, tileTwo ]
Run Code Online (Sandbox Code Playgroud)
  1. 它删除索引 0 处的图块,并将剩余元素向下移动 1 以填充空间。
index:       0
tiles:     [ tileTwo ]
removed: tileOne
Run Code Online (Sandbox Code Playgroud)
  1. 它在索引 1 处插入图块。
index:       0        1
tiles:     [ tileTwo, tileOne ]
Run Code Online (Sandbox Code Playgroud)