Home > Mobile >  Why does the primary list get sorted -Flutter
Why does the primary list get sorted -Flutter

Time:02-21

I'm trying to create a temporary list to map it, but when I sort the temporary list, the original list gets sorted. I don't know why does it work this way.

final _colors = [
      Colors.green[600],
      Colors.green[600],
      Colors.amber[600],
      Colors.amber[600],
      Colors.amber[600],
      Colors.red[600],
      Colors.red[600]
    ];
    final _temp = _sevenRandomNumbers;
    _temp.sort((a, b) => a.compareTo(b));

    return {for (int i = 0; i < 7; i  ) _temp[i]: _colors[i]};

In this scenario, I create a duplicate list named _temp, but when I sort it as shown in the next line of code, the original list i.e. _sevenRandomNumbers, gets sorted as well.

For instance, if initially, the _sevenRandomNumbers was [4, 7, 3, 8, 1, 2, 5]. I set a final variable _temp which should contain the same list with same order i.e. [4, 7, 3, 8, 1, 2, 5]. When I sort the _temp list, only this list should be sorted like [1, 2, 3, 4, 5, 7, 8], but in my case the original list i.e. _sevenRandomNumbers also gets sorted like this.

I know this is a noob kind of question but I'm very confused. Regards.

CodePudding user response:

Do it like this: final _temp = List.from(_sevenRandomNumbers);

CodePudding user response:

Since you have a list of primitive types, you could use the spread operator (introduced in Dart 2.3) to clone your list:

void main() {
  final List<int> _sevenRandomNumbers = [4, 7, 3, 8, 1, 2, 5];
  final _temp = [..._sevenRandomNumbers];
  _temp.sort((a, b) => a.compareTo(b));
  print('7 random numbers: $_sevenRandomNumbers');
  print('Sorted: $_temp');
}
// 7 random numbers: [4, 7, 3, 8, 1, 2, 5]
// Sorted: [1, 2, 3, 4, 5, 7, 8]

Note: the spread operator also works with a Map or a Set.

  • Related