-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create safelist-in-flutter-and-dart.dart
- Loading branch information
Showing
1 changed file
with
68 additions
and
0 deletions.
There are no files selected for viewing
68 changes: 68 additions & 0 deletions
68
tipsandtricks/safelist-in-flutter-and-dart/safelist-in-flutter-and-dart.dart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
// π¦ Twitter https://twitter.com/vandadnp | ||
// π΅ LinkedIn https://linkedin.com/in/vandadnp | ||
// π₯ YouTube https://youtube.com/c/vandadnp | ||
// π Free Flutter Course https://linktr.ee/vandadnp | ||
// π¦ 11+ Hours Bloc Course https://youtu.be/Mn254cnduOY | ||
// πΆ 7+ Hours MobX Course https://youtu.be/7Od55PBxYkI | ||
// π¦ 8+ Hours RxSwift Coursde https://youtu.be/xBFWMYmm9ro | ||
// π€ Want to support my work? https://buymeacoffee.com/vandad | ||
|
||
import 'dart:collection'; | ||
|
||
void testIt() { | ||
const notFound = 'NOT_FOUND'; | ||
const defaultString = ''; | ||
|
||
final myList = SafeList( | ||
defaultValue: defaultString, | ||
absentValue: notFound, | ||
values: ['Bar', 'Baz'], | ||
); | ||
|
||
print(myList[0]); // Bar | ||
print(myList[1]); // Baz | ||
print(myList[2]); // NOT_FOUND | ||
|
||
myList.length = 4; | ||
print(myList[3]); // '' | ||
|
||
myList.length = 0; | ||
print(myList.first); // NOT_FOUND | ||
print(myList.last); // NOT_FOUND | ||
} | ||
|
||
class SafeList<T> extends ListBase<T> { | ||
final List<T> _list; | ||
final T defaultValue; | ||
final T absentValue; | ||
|
||
SafeList({ | ||
required this.defaultValue, | ||
required this.absentValue, | ||
List<T>? values, | ||
}) : _list = values ?? []; | ||
|
||
@override | ||
T operator [](int index) => index < _list.length ? _list[index] : absentValue; | ||
|
||
@override | ||
void operator []=(int index, T value) => _list[index] = value; | ||
|
||
@override | ||
int get length => _list.length; | ||
|
||
@override | ||
T get first => _list.isNotEmpty ? _list.first : absentValue; | ||
|
||
@override | ||
T get last => _list.isNotEmpty ? _list.last : absentValue; | ||
|
||
@override | ||
set length(int newValue) { | ||
if (newValue < _list.length) { | ||
_list.length = newValue; | ||
} else { | ||
_list.addAll(List.filled(newValue - _list.length, defaultValue)); | ||
} | ||
} | ||
} |