Skip to content

Instantly share code, notes, and snippets.

@LeBaleiro
Last active October 12, 2022 20:16
Show Gist options
  • Save LeBaleiro/e0a8244d09e788058ed3fd59a1f3ade7 to your computer and use it in GitHub Desktop.
Save LeBaleiro/e0a8244d09e788058ed3fd59a1f3ade7 to your computer and use it in GitHub Desktop.
Dart Lists

For the Dart language when we pass a List to a function as a parameter we pass its reference by default, which means we are passing and editing the original list.

This may cause confusion because it doesn't follow the same pattern in all languages, the Solitity language is an example of how this could be the oposite as default.

In the first test of the following example we can see how this happens and in the second test we see how to avoid it by simply calling .toList() at the end of the original List, creating a new reference by doing this.

To open this example on dartpad, follow dartpad link

The same applies to Maps, here are the examples: dartpad link

import 'package:flutter_test/flutter_test.dart';
void main() {
test('should edit the original list as default', () {
final mockList = ['string1', 'string2', 'string3'];
expect(mockList, ['string1', 'string2', 'string3']);
removeFirstItemFromOriginalList(mockList);
expect(mockList, ['string2', 'string3']);
});
test('should create a new reference and shouldn\'t edit the original list', () {
final mockList = ['string1', 'string2', 'string3'];
expect(mockList, ['string1', 'string2', 'string3']);
dontRemoveFirstItemFromOriginalList(mockList);
expect(mockList, ['string1', 'string2', 'string3']);
});
}
void removeFirstItemFromOriginalList(List<String> listParam) {
listParam.removeAt(0);
}
void dontRemoveFirstItemFromOriginalList(List<String> listParam) {
final newListReference = listParam.toList();
newListReference.removeAt(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment