Skip to content

Commit 7db6313

Browse files
authored
Create safelist-in-flutter-and-dart.dart
1 parent c2cf59d commit 7db6313

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
// 🐦 Twitter https://twitter.com/vandadnp
2+
// 🔵 LinkedIn https://linkedin.com/in/vandadnp
3+
// 🎥 YouTube https://youtube.com/c/vandadnp
4+
// 💙 Free Flutter Course https://linktr.ee/vandadnp
5+
// 📦 11+ Hours Bloc Course https://youtu.be/Mn254cnduOY
6+
// 🔶 7+ Hours MobX Course https://youtu.be/7Od55PBxYkI
7+
// 🦄 8+ Hours RxSwift Coursde https://youtu.be/xBFWMYmm9ro
8+
// 🤝 Want to support my work? https://buymeacoffee.com/vandad
9+
10+
import 'dart:collection';
11+
12+
void testIt() {
13+
const notFound = 'NOT_FOUND';
14+
const defaultString = '';
15+
16+
final myList = SafeList(
17+
defaultValue: defaultString,
18+
absentValue: notFound,
19+
values: ['Bar', 'Baz'],
20+
);
21+
22+
print(myList[0]); // Bar
23+
print(myList[1]); // Baz
24+
print(myList[2]); // NOT_FOUND
25+
26+
myList.length = 4;
27+
print(myList[3]); // ''
28+
29+
myList.length = 0;
30+
print(myList.first); // NOT_FOUND
31+
print(myList.last); // NOT_FOUND
32+
}
33+
34+
class SafeList<T> extends ListBase<T> {
35+
final List<T> _list;
36+
final T defaultValue;
37+
final T absentValue;
38+
39+
SafeList({
40+
required this.defaultValue,
41+
required this.absentValue,
42+
List<T>? values,
43+
}) : _list = values ?? [];
44+
45+
@override
46+
T operator [](int index) => index < _list.length ? _list[index] : absentValue;
47+
48+
@override
49+
void operator []=(int index, T value) => _list[index] = value;
50+
51+
@override
52+
int get length => _list.length;
53+
54+
@override
55+
T get first => _list.isNotEmpty ? _list.first : absentValue;
56+
57+
@override
58+
T get last => _list.isNotEmpty ? _list.last : absentValue;
59+
60+
@override
61+
set length(int newValue) {
62+
if (newValue < _list.length) {
63+
_list.length = newValue;
64+
} else {
65+
_list.addAll(List.filled(newValue - _list.length, defaultValue));
66+
}
67+
}
68+
}

0 commit comments

Comments
 (0)