From efd0c5647933ec5d43489d5d07abb330c3e1d4ec Mon Sep 17 00:00:00 2001 From: gmpassos Date: Sun, 7 Mar 2021 05:59:29 -0300 Subject: [PATCH] v3.0.0 - Dart 2.12.0: - Sound null safety compatibility. - Update CI dart commands. - sdk: '>=2.12.0 <3.0.0' - intl: ^0.17.0 - resource_portable: ^3.0.0 - collection: ^1.15.0 - pedantic: ^1.11.0 - test: ^1.16.5 --- .github/workflows/dart.yml | 16 +- CHANGELOG.md | 12 + lib/src/collections.dart | 796 +++++++++++----------- lib/src/data.dart | 124 ++-- lib/src/date.dart | 121 ++-- lib/src/events.dart | 498 ++++++++------ lib/src/io.dart | 4 +- lib/src/json.dart | 54 +- lib/src/loader.dart | 28 +- lib/src/math.dart | 161 ++--- lib/src/paging.dart | 58 +- lib/src/regexp.dart | 67 +- lib/src/resource.dart | 140 ++-- lib/src/string.dart | 33 +- lib/src/uri.dart | 54 +- lib/src/utils.dart | 44 +- pubspec.yaml | 3 +- test/swiss_knife_resource_test.dart | 8 +- test/swiss_knife_test.dart | 68 +- test/swiss_knife_tree_reference_test.dart | 38 +- 20 files changed, 1175 insertions(+), 1152 deletions(-) diff --git a/.github/workflows/dart.yml b/.github/workflows/dart.yml index 60595dc..78e70f6 100644 --- a/.github/workflows/dart.yml +++ b/.github/workflows/dart.yml @@ -19,13 +19,13 @@ jobs: - name: Dart version run: dart --version - name: Install dependencies - run: pub get - - name: dartfmt - run: dartfmt -n --set-exit-if-changed . - - name: dartanalyzer - run: dartanalyzer --fatal-infos --fatal-warnings . + run: dart pub get + - name: dart format + run: dart format -o none --set-exit-if-changed . + - name: dart analyze + run: dart analyze --fatal-infos --fatal-warnings . - name: Run tests - run: pub run test - - name: publish --dry-run - run: pub publish --dry-run + run: dart test + - name: dart pub publish --dry-run + run: dart pub publish --dry-run diff --git a/CHANGELOG.md b/CHANGELOG.md index c9fd0d6..dbc0266 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,15 @@ +## 3.0.0 + +- Dart 2.12.0: + - Sound null safety compatibility. + - Update CI dart commands. + - sdk: '>=2.12.0 <3.0.0' +- intl: ^0.17.0 +- resource_portable: ^3.0.0 +- collection: ^1.15.0 +- pedantic: ^1.11.0 +- test: ^1.16.5 + ## 2.5.26 - Optimize: `parseInt`, `parseDouble` and `parseNum`. diff --git a/lib/src/collections.dart b/lib/src/collections.dart index 1978e53..2f7c22c 100644 --- a/lib/src/collections.dart +++ b/lib/src/collections.dart @@ -22,7 +22,7 @@ class Pair { /// Returns a [Point] with [a] as [dart_math.Point.x] and [b] as [dart_math.Point.y]. dart_math.Point get asPoint => - dart_math.Point(parseNum(a) /*!*/, parseNum(b) /*!*/); + dart_math.Point(parseNum(a)!, parseNum(b)!); @override bool operator ==(Object other) => @@ -53,7 +53,7 @@ class Pair { } /// Joins [a] and [b] with the [delimiter]. - String join([String /*!*/ delimiter = '']) { + String join([String delimiter = '']) { return '$a$delimiter$b'; } @@ -67,17 +67,17 @@ class Pair { /// Represents a [width] X [height] dimension. class Dimension implements Comparable { /// Extra parsers. - static Set parsers = {}; + static Set parsers = {}; /// Width of the dimension. - final int /*!*/ width; + final int width; /// Height of the dimension. - final int /*!*/ height; + final int height; Dimension(this.width, this.height); - static Dimension /*?*/ from(Object /*?*/ dimension) { + static Dimension? from(Object? dimension) { if (dimension == null) return null; if (dimension is Dimension) return dimension; if (dimension is Pair) { @@ -114,7 +114,7 @@ class Dimension implements Comparable { /// Parsers [wh] String, trying to split with [delimiter] between 2 numbers /// in the string. - static Dimension parse(String /*?*/ wh, [Pattern /*?*/ delimiter]) { + static Dimension? parse(String? wh, [Pattern? delimiter]) { if (wh == null) return null; delimiter ??= RegExp(r'[\sx,;]+'); wh = wh.trim(); @@ -167,7 +167,7 @@ class Dimension implements Comparable { int get hashCode => width.hashCode ^ height.hashCode; /// Area of the dimension. - int get area => (width ?? 1) * (height ?? 1); + int get area => width * height; /// Returns the difference between `this` and [other], using [width] and [height]. /// @@ -176,7 +176,7 @@ class Dimension implements Comparable { int subtract(Dimension other, [bool maximumDifferences = false]) { var dw = width - other.width; var dh = height - other.height; - var d = (maximumDifferences ?? false) ? Math.min(dw, dh) : Math.max(dw, dh); + var d = maximumDifferences ? Math.min(dw, dh) : Math.max(dw, dh); return d; } @@ -193,7 +193,7 @@ class Dimension implements Comparable { /// Returns [true] if [o1] and [o2] are equals. /// /// [deep] If [true] checks the collections deeply. -bool /*!*/ isEquals(Object/*?*/ o1, Object/*?*/ o2, [bool /*!*/ deep = false]) { +bool isEquals(Object? o1, Object? o2, [bool deep = false]) { if (deep) { return isEqualsDeep(o1, o2); } else { @@ -202,7 +202,7 @@ bool /*!*/ isEquals(Object/*?*/ o1, Object/*?*/ o2, [bool /*!*/ deep = false]) { } /// Returns [true] if [o1] and [o2] are equals deeply. -bool /*!*/ isEqualsDeep(Object/*?*/ o1, Object/*?*/ o2) { +bool isEqualsDeep(Object? o1, Object? o2) { if (identical(o1, o2)) return true; if (o1 is List) { @@ -222,7 +222,7 @@ bool /*!*/ isEqualsDeep(Object/*?*/ o1, Object/*?*/ o2) { /// Returns [true] if [o1] and [o2] are equals as [String]. /// Uses [String.toString] to check. -bool /*!*/ isEqualsAsString(Object/*?*/ o1, Object/*?*/ o2) { +bool isEqualsAsString(Object? o1, Object? o2) { if (identical(o1, o2)) return true; if (o1 == o2) return true; if (o1 == null || o2 == null) return false; @@ -236,8 +236,8 @@ bool /*!*/ isEqualsAsString(Object/*?*/ o1, Object/*?*/ o2) { /// /// [sort] If [true] sorts [l1] and [l2] before check. /// [deep] If [true] checks deeply collections elements. -bool /*!*/ isEquivalentList(List/*?*/ l1, List/*?*/ l2, - {bool /*!*/ sort = false, bool /*!*/ deep = false}) { +bool isEquivalentList(List? l1, List? l2, + {bool sort = false, bool deep = false}) { if (l1 == l2) return true; if (l1 == null) return false; @@ -262,8 +262,7 @@ bool /*!*/ isEquivalentList(List/*?*/ l1, List/*?*/ l2, } /// Same as [isEquivalentList] but for [Iterable]. -bool /*!*/ isEquivalentIterator(Iterable/*?*/ it1, Iterable/*?*/ it2, - {bool /*!*/ deep = false}) { +bool isEquivalentIterator(Iterable? it1, Iterable? it2, {bool deep = false}) { if (it1 == it2) return true; if (it1 == null) return false; @@ -285,7 +284,7 @@ bool /*!*/ isEquivalentIterator(Iterable/*?*/ it1, Iterable/*?*/ it2, /// Returns [true] if [m1] and [m2] are equals. /// /// [deep] IF [true] checks deeply collections values. -bool /*!*/ isEquivalentMap(Map/*?*/ m1, Map/*?*/ m2, {bool /*!*/ deep = false}) { +bool isEquivalentMap(Map? m1, Map? m2, {bool deep = false}) { if (m1 == m2) return true; if (m1 == null) return false; @@ -310,7 +309,7 @@ bool /*!*/ isEquivalentMap(Map/*?*/ m1, Map/*?*/ m2, {bool /*!*/ deep = false}) /// Returns [true] if both lists, [l1] and [l2], /// have equals entries in the same order. -bool /*!*/ isEqualsList(List/*?*/ l1, List/*?*/ l2) { +bool isEqualsList(List? l1, List? l2) { if (identical(l1, l2)) return true; if (l1 == null) return false; if (l2 == null) return false; @@ -330,7 +329,7 @@ bool /*!*/ isEqualsList(List/*?*/ l1, List/*?*/ l2) { /// Returns [true] if both sets, [s1] and [s2], /// have equals entries in the same order. -bool /*!*/ isEqualsSet(Set/*?*/ s1, Set/*?*/ s2) { +bool isEqualsSet(Set? s1, Set? s2) { if (identical(s1, s2)) return true; if (s1 == null) return false; if (s2 == null) return false; @@ -357,7 +356,7 @@ bool /*!*/ isEqualsSet(Set/*?*/ s1, Set/*?*/ s2) { /// Returns [true] if both iterable, [i1] and [i2], /// have equals entries in the same order. -bool /*!*/ isEqualsIterable(Iterable/*?*/ i1, Iterable/*?*/ i2) { +bool isEqualsIterable(Iterable? i1, Iterable? i2) { if (identical(i1, i2)) return true; if (i1 == null) return false; if (i2 == null) return false; @@ -384,7 +383,7 @@ bool /*!*/ isEqualsIterable(Iterable/*?*/ i1, Iterable/*?*/ i2) { /// Returns [true] if both maps, [m1] and [m2], /// have equals entries in the same order. -bool /*!*/ isEqualsMap(Map/*?*/ m1, Map/*?*/ m2) { +bool isEqualsMap(Map? m1, Map? m2) { if (identical(m1, m2)) return true; if (m1 == null) return false; if (m2 == null) return false; @@ -400,7 +399,6 @@ bool /*!*/ isEqualsMap(Map/*?*/ m1, Map/*?*/ m2) { var e2 = entries2.elementAt(i); if (e1 == e2) continue; - if (e1 == null || e2 == null) continue; if (e1.key != e2.key) return false; if (e1.value != e2.value) return false; @@ -418,16 +416,15 @@ bool /*!*/ isEqualsMap(Map/*?*/ m1, Map/*?*/ m2) { /// [value]. /// /// [deep] IF [true] checks deeply collections values. -bool /*!*/ isAllEquals(Object/*?*/ element, Object/*?*/ value, - [bool /*!*/ deep = false]) { +bool isAllEquals(Object? element, Object? value, [bool deep = false]) { if (isEquals(element, value, deep)) { return true; } if (element is List) { - return isAllEqualsInList(element, value, deep); + return isAllEqualsInList(element, value!, deep); } else if (element is Map) { - return isAllEqualsInMap(element, value, deep); + return isAllEqualsInMap(element, value!, deep); } return false; @@ -436,8 +433,7 @@ bool /*!*/ isAllEquals(Object/*?*/ element, Object/*?*/ value, /// Returns [true] if [list] elements are all equals to [value]. /// /// [deep] IF [true] checks deeply collections values. -bool /*!*/ isAllEqualsInList(List/*?*/ list, Object/*!*/ value, - [bool /*!*/ deep = false]) { +bool isAllEqualsInList(List? list, Object value, [bool deep = false]) { if (list == null || list.isEmpty) return false; for (var e in list) { @@ -452,7 +448,7 @@ bool /*!*/ isAllEqualsInList(List/*?*/ list, Object/*!*/ value, /// Returns [true] if [map] values are all equals to [value]. /// /// [deep] IF [true] checks deeply collections values. -bool /*!*/ isAllEqualsInMap(Map/*?*/ map, Object/*!*/ value, [bool /*!*/ deep = false]) { +bool isAllEqualsInMap(Map? map, Object value, [bool deep = false]) { if (map == null || map.isEmpty) return false; for (var e in map.values) { @@ -465,8 +461,7 @@ bool /*!*/ isAllEqualsInMap(Map/*?*/ map, Object/*!*/ value, [bool /*!*/ deep = } /// Returns [true] if at least ONE [list] element does NOT matches [matcher]. -bool /*!*/ listNotMatchesAll( - Iterable /*?*/ list, bool Function(T entry) /*!*/ matcher) { +bool listNotMatchesAll(Iterable? list, bool Function(T entry) matcher) { if (list == null || list.isEmpty) return false; for (var e in list) { if (!matcher(e)) return true; @@ -475,8 +470,7 @@ bool /*!*/ listNotMatchesAll( } /// Returns [true] if all [list] elements matches [matcher]. -bool /*!*/ listMatchesAll( - Iterable /*?*/ list, bool Function(T entry) /*!*/ matcher) { +bool listMatchesAll(Iterable? list, bool Function(T entry) matcher) { if (list == null || list.isEmpty) return false; for (var e in list) { if (!matcher(e)) return false; @@ -485,8 +479,7 @@ bool /*!*/ listMatchesAll( } /// Returns [true] if any element of [list] matches [matcher]. -bool /*!*/ listMatchesAny( - Iterable /*?*/ list, bool Function(T entry) /*!*/ matcher) { +bool listMatchesAny(Iterable? list, bool Function(T entry) matcher) { if (list == null || list.isEmpty) return false; for (var e in list) { if (matcher(e)) return true; @@ -495,21 +488,22 @@ bool /*!*/ listMatchesAny( } /// Returns [true] if all [list] elements are of the same type. -bool /*!*/ isListEntriesAllOfSameType(Iterable /*?*/ list) { +bool isListEntriesAllOfSameType(Iterable? list) { if (list == null || list.isEmpty) return false; if (list.length == 1) return true; var t = list.first.runtimeType; - return listMatchesAll(list, (e) => e != null && e.runtimeType == t); + return listMatchesAll(list, (dynamic e) => e != null && e.runtimeType == t); } /// Returns [true] if all [list] elements are of [type]. -bool /*!*/ isListEntriesAllOfType(Iterable /*?*/ list, Type /*!*/ type) { +bool isListEntriesAllOfType(Iterable? list, Type type) { if (list == null || list.isEmpty) return false; - return listMatchesAll(list, (e) => e != null && e.runtimeType == type); + return listMatchesAll( + list, (dynamic e) => e != null && e.runtimeType == type); } /// Returns [true] if all [list] elements are [identical]. -bool /*!*/ isListValuesIdentical(List /*?*/ l1, List /*?*/ l2) { +bool isListValuesIdentical(List? l1, List? l2) { if (l1 == null || l2 == null) return false; if (identical(l1, l2)) return true; @@ -529,8 +523,8 @@ bool /*!*/ isListValuesIdentical(List /*?*/ l1, List /*?*/ l2) { } /// Adds all [values] to [list]. -void addAllToList(List /*!*/ list, Object /*?*/ values) { - if (values == null) return ; +void addAllToList(List list, Object? values) { + if (values == null) return; if (values is List) { list.addAll(values); @@ -540,15 +534,15 @@ void addAllToList(List /*!*/ list, Object /*?*/ values) { } /// Joins all parameters to a single list. -List /*!*/ joinLists(List /*?*/ l1, - [List /*?*/ l2, - List /*?*/ l3, - List /*?*/ l4, - List /*?*/ l5, - List /*?*/ l6, - List /*?*/ l7, - List /*?*/ l8, - List /*?*/ l9]) { +List joinLists(List? l1, + [List? l2, + List? l3, + List? l4, + List? l5, + List? l6, + List? l7, + List? l8, + List? l9]) { var l = []; if (l1 != null) l.addAll(l1); @@ -565,43 +559,41 @@ List /*!*/ joinLists(List /*?*/ l1, } /// Copies [list]. -List /*?*/ copyList(List /*?*/ list) { +List? copyList(List? list) { if (list == null) return null; return List.from(list); } /// Copies [list] as a [List]. -List /*?*/ copyListString(List /*?*/ list) { +List? copyListString(List? list) { if (list == null) return null; return List.from(list); } /// Copies [map]. -Map /*?*/ copyMap(Map /*?*/ map) { +Map? copyMap(Map? map) { if (map == null) return null; return Map.from(map); } /// Copies [map] as a [Map]. -Map /*?*/ copyMapString(Map /*?*/ m) { +Map? copyMapString(Map? m) { if (m == null) return null; return Map.from(m); } /// Gets a [map] entry ignoring key case. -MapEntry /*?*/ getEntryIgnoreCase( - Map /*!*/ map, String /*?*/ key) { +MapEntry? getEntryIgnoreCase(Map map, String? key) { + if (key == null) return null; var val = map[key]; if (val != null) return MapEntry(key, val); - if (key == null) return null; - var keyLC = key.toLowerCase(); for (var k in map.keys) { if (k.toLowerCase() == keyLC) { - var value = map[k]; - return MapEntry(k, value); + V value = map[k]!; + return MapEntry(k, value); } } @@ -609,13 +601,13 @@ MapEntry /*?*/ getEntryIgnoreCase( } /// Gets a [map] value ignoring [key] case. -V /*?*/ getIgnoreCase(Map /*!*/ map, String /*?*/ key) { +V? getIgnoreCase(Map map, String? key) { var entry = getEntryIgnoreCase(map, key); return entry != null ? entry.value : null; } /// Puts a [map] value ignoring [key] case. -V /*?*/ putIgnoreCase(Map /*!*/ map, String /*!*/ key, V value) { +V? putIgnoreCase(Map map, String key, V value) { var entry = getEntryIgnoreCase(map, key); if (entry != null) { map[entry.key] = value; @@ -627,7 +619,7 @@ V /*?*/ putIgnoreCase(Map /*!*/ map, String /*!*/ key, V value) { } /// Returns [o] as [Map]. Converts it if needed. -Map /*?*/ asMap(Object /*?*/ o) { +Map? asMap(Object? o) { if (o == null) return null; if (o is Map) return o; @@ -638,7 +630,7 @@ Map /*?*/ asMap(Object /*?*/ o) { for (var i = 0; i < sz; i += 2) { Object key = o[i]; - Object/*?*/ val = o[i + 1]; + Object? val = o[i + 1]; m[key] = val; } } else { @@ -649,43 +641,40 @@ Map /*?*/ asMap(Object /*?*/ o) { } /// Returns [o] as a [List]. Converts it if needed. -List /*?*/ asListOfMap(Object /*?*/ o) { +List? asListOfMap(Object? o) { if (o == null) return null; - if (o is List) return o ; + if (o is List) return o; if (o is List) { return o.map((e) => asMap(e)).whereType().toList(); - } - else if (o is Map) { + } else if (o is Map) { return [o]; } var s = o.toString(); - var map = parseFromInlineMap(s, _INLINE_PROPERTIES_DELIMITER_PAIRS, _INLINE_PROPERTIES_DELIMITER_KEYS_VALUES); - return [map] ; + var map = parseFromInlineMap(s, _INLINE_PROPERTIES_DELIMITER_PAIRS, + _INLINE_PROPERTIES_DELIMITER_KEYS_VALUES); + return [map!]; } typedef CompareMapEntryFunction = int Function( MapEntry entry1, MapEntry entry2); /// Returns a Map sorted by keys. -Map sortMapEntriesByKey(Map /*!*/ map, - [bool /*!*/ reversed = false]) => +Map sortMapEntriesByKey(Map map, [bool reversed = false]) => sortMapEntries( - map, (a, b) => parseComparable(a.key).compareTo(b.key), reversed); + map, (a, b) => parseComparable(a.key)!.compareTo(b.key), reversed); /// Returns a Map sorted by keys. -Map sortMapEntriesByValue(Map /*!*/ map, - [bool /*!*/ reversed = false]) => +Map sortMapEntriesByValue(Map map, [bool reversed = false]) => sortMapEntries( - map, (a, b) => parseComparable(a.value).compareTo(b.value), reversed); + map, (a, b) => parseComparable(a.value)!.compareTo(b.value), reversed); /// Returns a Map with sorted entries. -Map sortMapEntries(Map /*!*/ map, - [CompareMapEntryFunction /*?*/ compare, - bool /*!*/ reversed = false]) { - compare ??= (a, b) => parseComparable(a.key).compareTo(b.key); +Map sortMapEntries(Map map, + [CompareMapEntryFunction? compare, bool reversed = false]) { + compare ??= (a, b) => parseComparable(a.key)!.compareTo(b.key); - if (reversed ?? false) { + if (reversed) { var compareOriginal = compare; compare = (a, b) => compareOriginal(b, a); } @@ -697,7 +686,7 @@ Map sortMapEntries(Map /*!*/ map, } /// Returns [true] if [list] values are of type [String]. -bool /*!*/ isListOfStrings(Iterable /*?*/ list) { +bool isListOfStrings(Iterable? list) { if (list == null || list.isEmpty) return false; for (var value in list) { @@ -708,14 +697,14 @@ bool /*!*/ isListOfStrings(Iterable /*?*/ list) { } /// Returns [o] as a [List]. Converts it if needed. -List /*?*/ asListOfString(Object /*?*/ o) { +List? asListOfString(Object? o) { if (o == null) return null; var l = o as List; return l.map((e) => e.toString()).toList(); } /// Returns [o] as a [Map]. Converts it if needed. -Map /*?*/ asMapOfString(Object /*?*/ o) { +Map? asMapOfString(Object? o) { if (o == null) return null; var m = o as Map; return m.map((k, v) => MapEntry('$k', '$v')); @@ -724,7 +713,7 @@ Map /*?*/ asMapOfString(Object /*?*/ o) { /// Maps [tree]: /// - If [tree] is a [Map] to a [Map]. -dynamic /*?*/ asTreeOfKeyString(Object /*?*/ tree) { +dynamic /*?*/ asTreeOfKeyString(Object? tree) { if (tree == null) return null; if (tree is Map) { @@ -742,10 +731,8 @@ final RegExp _toListOfStrings_delimiter = RegExp(r'\s+'); /// Converts [s] to a [List]. /// Converts any collection to a flat list of strings. -List /*!*/ toFlatListOfStrings(Object /*?*/ s, - {Pattern /*?*/ delimiter, - bool /*!*/ trim = true, - bool /*!*/ ignoreEmpty = true}) { +List toFlatListOfStrings(Object? s, + {Pattern? delimiter, bool trim = true, bool ignoreEmpty = true}) { if (s == null) return []; delimiter ??= _toListOfStrings_delimiter; @@ -755,10 +742,9 @@ List /*!*/ toFlatListOfStrings(Object /*?*/ s, if (s is String) { list = s.split(delimiter); } else if (s is Iterable) { - var it = s as Iterable; list = []; - for (var e in it) { + for (var e in s) { if (e == null) continue; if (e is String) { @@ -790,60 +776,62 @@ List /*!*/ toFlatListOfStrings(Object /*?*/ s, } } - list.removeWhere((e) => e == null || (ignoreEmpty && e.isEmpty)); + list.removeWhere((e) => (ignoreEmpty && e.isEmpty)); return list; } /// Returns [true] if [list] elements are all of type [String]. -bool /*!*/ isListOfString(Iterable /*?*/ list) { +bool isListOfString(Iterable? list) { if (list == null) return false; if (list is List) return true; if (list.isEmpty) return false; - if (listNotMatchesAll(list, (e) => (e is String))) return false; + if (listNotMatchesAll(list, (dynamic e) => (e is String))) return false; return true; } /// Returns [true] if [list] elements are all of type [num]. -bool /*!*/ isListOfNum(Iterable /*?*/ list) { +bool isListOfNum(Iterable? list) { if (list == null) return false; if (list is List) return true; if (list.isEmpty) return false; - if (listNotMatchesAll(list, (e) => (e is num))) return false; + if (listNotMatchesAll(list, (dynamic e) => (e is num))) return false; return true; } -typedef TypeTester = bool /*!*/ Function(T value); +typedef TypeTester = bool Function(T value); /// Returns [true] if [list] elements are all of type [T]. -bool /*!*/ isListOfType(Iterable /*?*/ list) { +bool isListOfType(Iterable? list) { if (list == null) return false; if (list is List) return true; if (list.isEmpty) return false; - if (listNotMatchesAll(list, (e) => (e is T))) return false; + if (listNotMatchesAll(list, (dynamic e) => (e is T))) return false; return true; } /// Returns [true] if [list] elements are all of type [A] or [B]. -bool /*!*/ isListOfTypes(Iterable /*?*/ list) { +bool isListOfTypes(Iterable? list) { if (list == null) return false; if (list is List) return true; if (list is List) return true; if (list.isEmpty) return false; - if (listNotMatchesAll(list, (e) => (e is A) || (e is B))) return false; + if (listNotMatchesAll(list, (dynamic e) => (e is A) || (e is B))) { + return false; + } return true; } /// Returns [true] if [list] contains elements of type [T]. -bool /*!*/ listContainsType(Iterable /*?*/ list) { +bool listContainsType(Iterable? list) { if (list == null) return false; if (list is List) return true; if (list.isEmpty) return false; @@ -854,7 +842,7 @@ bool /*!*/ listContainsType(Iterable /*?*/ list) { } /// Returns [true] if [list] contains all elements of type [entry]. -bool /*!*/ listContainsAll(Iterable /*?*/ list, Iterable /*?*/ entries) { +bool listContainsAll(Iterable? list, Iterable? entries) { if (entries == null || entries.isEmpty) return false; if (list == null || list.isEmpty) return false; for (var entry in entries) { @@ -864,52 +852,52 @@ bool /*!*/ listContainsAll(Iterable /*?*/ list, Iterable /*?*/ entries) { } /// Returns [true] if [list] elements are all of type [List]. -bool /*!*/ isListOfList(Iterable /*?*/ list) { +bool isListOfList(Iterable? list) { if (list == null) return false; if (list is List) return true; if (list.isEmpty) return false; - if (listNotMatchesAll(list, (e) => (e is List))) return false; + if (listNotMatchesAll(list, (dynamic e) => (e is List))) return false; return true; } /// Returns [true] if [list] elements are all of type [List]. -bool /*!*/ isListOfListOfList(Iterable /*?*/ list) { +bool isListOfListOfList(Iterable? list) { if (list == null) return false; if (list is List>) return true; if (list.isEmpty) return false; - if (listNotMatchesAll(list, (e) => isListOfList(e))) return false; + if (listNotMatchesAll(list, (dynamic e) => isListOfList(e))) return false; return true; } /// Returns [true] if [list] elements are all of type [Map]. -bool /*!*/ isListOfMap(Iterable /*?*/ list) { +bool isListOfMap(Iterable? list) { if (list == null) return false; if (list is List) return true; if (list.isEmpty) return false; - if (listNotMatchesAll(list, (e) => (e is Map))) return false; + if (listNotMatchesAll(list, (dynamic e) => (e is Map))) return false; return true; } /// Returns [true] if [list] elements are all equals to [value]. -bool /*!*/ isListValuesAllEquals(Iterable /*?*/ list, [Object /*?*/ eqValue]) { +bool isListValuesAllEquals(Iterable? list, [Object? eqValue]) { if (list == null) return false; if (list.isEmpty) return false; eqValue ??= list.first; - return listMatchesAll(list, (v) => v == eqValue); + return listMatchesAll(list, (dynamic v) => v == eqValue); } /// Returns [true] if [list] elements are all equals to value /// at index [valueIndex]. -bool /*!*/ isListOfListValuesAllEquals(Iterable /*?*/ list, - {Object /*?*/ eqValue, int /*?*/ eqValueIndex}) { +bool isListOfListValuesAllEquals(Iterable? list, + {Object? eqValue, int? eqValueIndex}) { if (list == null) return false; if (list.isEmpty) return false; @@ -918,31 +906,29 @@ bool /*!*/ isListOfListValuesAllEquals(Iterable /*?*/ list, : list.firstWhere((e) => e.isNotEmpty).first; if (eqValueIndex != null) { - return listMatchesAll(list, (v) => v[eqValueIndex] == eqValue); + return listMatchesAll(list, (dynamic v) => v[eqValueIndex] == eqValue); } else { - return listMatchesAll(list, (v) => v == eqValue); + return listMatchesAll(list, (dynamic v) => v == eqValue); } } -typedef ParserFunction = R /*!*/ Function(T value); +typedef ParserFunction = R Function(T value); /// Parses [s] to a [List], where [R] is the result of [parse]. /// /// [def] The default value if [s] is invalid. -List /*?*/ parseListOf( - Object /*?*/ s, ParserFunction /*!*/ parser, - [List /*?*/ def]) { +List? parseListOf(Object? s, ParserFunction parser, + [List? def]) { if (s == null) return def; if (s is List) return s.map((e) => parser(e)).toList(); - return [parser(s)]; + return [parser(s as T)]; } /// Parses [s] to a [List>], where [R] is the result of [parse]. /// /// [def] The default value if [s] is invalid. -List /*!*/ > /*?*/ parseListOfList( - Object /*?*/ s, ParserFunction /*!*/ parser, - [List> /*?*/ def]) { +List>? parseListOfList(Object? s, ParserFunction parser, + [List>? def]) { if (s == null) return def; if (s is List) { return s @@ -956,31 +942,31 @@ List /*!*/ > /*?*/ parseListOfList( } /// Returns [true] if [map] is [Map]. -bool /*!*/ isMapOfString(Map /*?*/ map) { +bool isMapOfString(Map? map) { if (map == null) return false; if (map is Map) return true; if (map.isEmpty) return false; - if (listNotMatchesAll(map.keys, (k) => (k is String))) return false; - if (listNotMatchesAll(map.values, (k) => (k is String))) return false; + if (listNotMatchesAll(map.keys, (dynamic k) => (k is String))) return false; + if (listNotMatchesAll(map.values, (dynamic k) => (k is String))) return false; return true; } /// Returns [true] if [map] has [String] keys. -bool /*!*/ isMapOfStringKeys(Map /*?*/ map) { +bool isMapOfStringKeys(Map? map) { if (map == null) return false; if (map is Map) return true; if (map is Map) return true; if (map.isEmpty) return false; - if (listNotMatchesAll(map.keys, (k) => (k is String))) return false; + if (listNotMatchesAll(map.keys, (dynamic k) => (k is String))) return false; return true; } /// Returns [true] if [map] has [String] keys and [List] values. -bool /*!*/ isMapOfStringKeysAndListValues(Map /*?*/ map) { +bool isMapOfStringKeysAndListValues(Map? map) { if (map == null) return false; if (map is Map) return true; if (map is Map>) return true; @@ -995,7 +981,7 @@ bool /*!*/ isMapOfStringKeysAndListValues(Map /*?*/ map) { } /// Returns [true] if [map] has [String] keys and [num] values. -bool /*!*/ isMapOfStringKeysAndNumValues(Map /*?*/ map) { +bool isMapOfStringKeysAndNumValues(Map? map) { if (map == null) return false; if (map is Map) return true; if (map.isEmpty) return false; @@ -1009,15 +995,14 @@ bool /*!*/ isMapOfStringKeysAndNumValues(Map /*?*/ map) { /// Finds in [map] a entry that has one of [keys]. /// /// [ignoreCase] If [true] ignores the case of the keys. -MapEntry /*?*/ findKeyEntry( - Map /*?*/ map, List /*?*/ keys, - [bool /*!*/ ignoreCase = false]) { +MapEntry? findKeyEntry(Map? map, List? keys, + [bool ignoreCase = false]) { if (map == null || keys == null) return null; if (ignoreCase) { for (var key in keys) { if (map.containsKey(key)) { - var value = map[key] /*!*/; + V value = map[key]!; return MapEntry(key, value); } @@ -1025,7 +1010,7 @@ MapEntry /*?*/ findKeyEntry( for (var k in map.keys) { if (k.toString().toLowerCase() == keyLC) { - var value = map[k] /*!*/; + V value = map[k]!; return MapEntry(k, value); } } @@ -1033,7 +1018,7 @@ MapEntry /*?*/ findKeyEntry( } else { for (var key in keys) { if (map.containsKey(key)) { - var value = map[key] /*!*/; + V value = map[key]!; return MapEntry(key, value); } } @@ -1045,8 +1030,8 @@ MapEntry /*?*/ findKeyEntry( /// Finds in [map] a value that has one of [keys]. /// /// [ignoreCase] If [true] ignores the case of the keys. -V /*?*/ findKeyValue(Map /*?*/ map, List /*?*/ keys, - [bool /*!*/ ignoreCase = false]) { +V? findKeyValue(Map? map, List? keys, + [bool ignoreCase = false]) { var entry = findKeyEntry(map, keys, ignoreCase); return entry != null ? entry.value : null; } @@ -1055,9 +1040,8 @@ V /*?*/ findKeyValue(Map /*?*/ map, List /*?*/ keys, /// /// [keyDelimiter] The key path delimiter. /// [isValidValue] validates a matching value. -V /*?*/ findKeyPathValue(Map /*?*/ map, String /*?*/ keyPath, - {String /*!*/ keyDelimiter = '/', - bool Function(dynamic value) /*?*/ isValidValue}) { +V? findKeyPathValue(Map? map, String? keyPath, + {String keyDelimiter = '/', bool Function(dynamic value)? isValidValue}) { if (map == null || map.isEmpty || keyPath == null || keyPath.isEmpty) { return null; } @@ -1087,20 +1071,19 @@ V /*?*/ findKeyPathValue(Map /*?*/ map, String /*?*/ keyPath, if (isValidValue != null) { if (isValidValue(value)) { - return value as V; + return value as V?; } else { return null; } } else { - return value as V; + return value as V?; } } /// Finds in [map] a key that has one of [keys]. /// /// [ignoreCase] If [true] ignores the case of the keys. -K /*?*/ findKeyName(Map /*?*/ map, List /*?*/ keys, - [bool /*!*/ ignoreCase = false]) { +K? findKeyName(Map? map, List? keys, [bool ignoreCase = false]) { var entry = findKeyEntry(map, keys, ignoreCase); return entry != null ? entry.key : null; } @@ -1108,7 +1091,7 @@ K /*?*/ findKeyName(Map /*?*/ map, List /*?*/ keys, /// Returns [true] if [s] is empty or null. /// /// [trim] if [true] will trim [s] before check for [String.isEmpty]. -bool /*!*/ isEmptyString(String /*?*/ s, {bool /*!*/ trim = false}) { +bool isEmptyString(String? s, {bool trim = false}) { if (s == null) return true; if (trim) { s = s.trim(); @@ -1117,7 +1100,7 @@ bool /*!*/ isEmptyString(String /*?*/ s, {bool /*!*/ trim = false}) { } /// Returns ![isEmptyString]. -bool /*!*/ isNotEmptyString(String /*?*/ s, {bool /*!*/ trim = false}) { +bool isNotEmptyString(String? s, {bool trim = false}) { return !isEmptyString(s, trim: trim); } @@ -1125,8 +1108,7 @@ bool /*!*/ isNotEmptyString(String /*?*/ s, {bool /*!*/ trim = false}) { /// /// [def] Default value to return if [s] [isEmptyString]. /// [trim] Passed to [isEmptyString]. -String /*?*/ ensureNotEmptyString(String /*?*/ s, - {bool /*!*/ trim = false, String /*?*/ def}) { +String? ensureNotEmptyString(String? s, {bool trim = false, String? def}) { if (isEmptyString(s, trim: trim)) { return def; } @@ -1135,7 +1117,7 @@ String /*?*/ ensureNotEmptyString(String /*?*/ s, /// Returns [true] if [o] is empty. Checks for [String], [List], [Map] /// [Iterable], [Set] or `o.toString()`. -bool /*!*/ isEmptyObject(T /*?*/ o, {bool /*!*/ trim = false}) { +bool isEmptyObject(T? o, {bool trim = false}) { if (o == null) return true; if (o is String) { @@ -1155,24 +1137,24 @@ bool /*!*/ isEmptyObject(T /*?*/ o, {bool /*!*/ trim = false}) { } /// Returns ![isEmptyObject]. -bool /*!*/ isNotEmptyObject(T /*?*/ value, {bool /*!*/ trim = false}) { +bool isNotEmptyObject(T? value, {bool trim = false}) { return !isEmptyObject(value, trim: trim); } /// Remove all entries of [list] that are true for [isEmptyObject]. /// /// Returns true if [list.isNotEmpty]. -bool /*!*/ removeEmptyEntries(List /*?*/ list) { +bool removeEmptyEntries(List? list) { if (list == null || list.isEmpty) return false; list.removeWhere(isEmptyObject); return list.isNotEmpty; } -typedef ValueValidator = bool /*!*/ Function(V /*?*/ value); +typedef ValueValidator = bool Function(V? value); /// Validates [value] and returns [value] or [def]. -T /*?*/ resolveValue(T /*?*/ value, - [T /*?*/ def, ValueValidator /*!*/ valueValidator = isNotEmptyObject]) { +T? resolveValue(T? value, + [T? def, ValueValidator valueValidator = isNotEmptyObject]) { if (value == null) return def; var valid = valueValidator(value); return valid ? value : def; @@ -1186,17 +1168,17 @@ typedef StringMapper = T Function(String s); /// [delimiterKeyValue] The delimiter for keys and values. /// [mapperKey] Maps keys to another type. /// [mapperValue] Maps values to another type. -Map /*?*/ parseFromInlineMap(String /*?*/ s, - Pattern /*!*/ delimiterPairs, Pattern /*!*/ delimiterKeyValue, - [StringMapper /*?*/ mapperKey, - StringMapper /*?*/ mapperValue, - Map /*?*/ def]) { +Map? parseFromInlineMap( + String? s, Pattern delimiterPairs, Pattern delimiterKeyValue, + [StringMapper? mapperKey, + StringMapper? mapperValue, + Map? def]) { if (s == null) return def; s = s.trim(); if (s.isEmpty) return def; - mapperKey ??= (k) => (k ?? '') as K; - mapperValue ??= (v) => (v ?? '') as V; + mapperKey ??= (k) => k as K; + mapperValue ??= (v) => v as V; var pairs = s.split(delimiterPairs); @@ -1205,7 +1187,7 @@ Map /*?*/ parseFromInlineMap(String /*?*/ s, for (var pair in pairs) { var entry = split(pair, delimiterKeyValue, 2); var k = mapperKey(entry[0]); - var v = mapperValue(entry.length > 1 ? entry[1] : null); + var v = mapperValue(entry.length > 1 ? entry[1] : ''); map[k] = v; } @@ -1216,13 +1198,13 @@ Map /*?*/ parseFromInlineMap(String /*?*/ s, /// /// [delimiter] Elements delimiter. /// [mapper] Maps elements to another type. -List /*?*/ parseFromInlineList(String /*?*/ s, Pattern /*!*/ delimiter, - [StringMapper /*?*/ mapper, List /*?*/ def]) { +List? parseFromInlineList(String? s, Pattern delimiter, + [StringMapper? mapper, List? def]) { if (s == null) return def; s = s.trim(); if (s.isEmpty) return def; - mapper ??= (s) => (s ?? '') as T; + mapper ??= (s) => s as T; var parts = s.split(delimiter); @@ -1239,10 +1221,10 @@ final RegExp _INLINE_PROPERTIES_DELIMITER_PAIRS = RegExp(r'\s*;\s*'); final RegExp _INLINE_PROPERTIES_DELIMITER_KEYS_VALUES = RegExp(r'\s*[:=]\s*'); /// Parses an inline properties, like inline CSS, to a [Map]. -Map parseFromInlineProperties(String s, - [StringMapper mapperKey, - StringMapper mapperValue, - Map def]) { +Map? parseFromInlineProperties(String s, + [StringMapper? mapperKey, + StringMapper? mapperValue, + Map? def]) { return parseFromInlineMap(s, _INLINE_PROPERTIES_DELIMITER_PAIRS, _INLINE_PROPERTIES_DELIMITER_KEYS_VALUES, mapperKey, mapperValue, def); } @@ -1250,7 +1232,7 @@ Map parseFromInlineProperties(String s, /// Parses [v] as [String]. /// /// [def] Default value if [v] is invalid. -String /*?*/ parseString(Object /*?*/ v, [String /*?*/ def]) { +String? parseString(Object? v, [String? def]) { if (v == null) return def; if (v is String) return v; @@ -1267,16 +1249,15 @@ String /*?*/ parseString(Object /*?*/ v, [String /*?*/ def]) { /// [delimiterPairs] Delimiter for pairs. /// [delimiterKeyValue] Delimiter for keys and values. /// [def] Default map if [s] is invalid. -Map /*?*/ parseStringFromInlineMap(Object /*?*/ s, - Pattern /*!*/ delimiterPairs, Pattern /*!*/ delimiterKeyValue, - [Map /*?*/ def]) { +Map? parseStringFromInlineMap( + Object? s, Pattern delimiterPairs, Pattern delimiterKeyValue, + [Map? def]) { if (s == null) return def; if (s is Map) { - return s.map( - (k, v) => MapEntry(parseString(k, '') /*!*/, parseString(v, '') /*!*/)); + return s.map((k, v) => MapEntry(parseString(k, '')!, parseString(v, '')!)); } return parseFromInlineMap(s.toString(), delimiterPairs, delimiterKeyValue, - (e) => parseString(e) /*!*/, (e) => parseString(e) /*!*/, def); + (e) => parseString(e)!, (e) => parseString(e)!, def); } /// Parses [s] as inline [List]. @@ -1284,37 +1265,37 @@ Map /*?*/ parseStringFromInlineMap(Object /*?*/ s, /// [delimiter] The delimiter of elements. /// /// [def] The default value if [s] is invalid. -List /*?*/ parseStringFromInlineList(Object /*?*/ s, - [Pattern /*?*/ delimiter, List /*?*/ def]) { +List? parseStringFromInlineList(Object? s, + [Pattern? delimiter, List? def]) { if (s == null) return def; - if (s is List) return s.map((e) => parseString(e, '') /*!*/).toList(); + if (s is List) return s.map((e) => parseString(e, '')!).toList(); delimiter ??= RegExp(r'\s*,\s*'); return parseFromInlineList( - s.toString(), delimiter, (e) => parseString(e, '') /*!*/, def); + s.toString(), delimiter, (e) => parseString(e, '')!, def); } /// Parses [v] as to a [Comparable] type. -Comparable /*?*/ parseComparable(Object /*?*/ v) { +Comparable? parseComparable(Object? v) { if (v == null) return null; if (v is num) return v as Comparable; if (v is String) return v as Comparable; - return parseString(v) as Comparable; + return parseString(v) as Comparable?; } /// Parses [e] as a [MapEntry] -MapEntry /*?*/ parseMapEntryOfStrings(Object /*?*/ e, - [Pattern /*?*/ delimiter, MapEntry /*?*/ def]) { +MapEntry? parseMapEntryOfStrings(Object? e, + [Pattern? delimiter, MapEntry? def]) { if (e == null) return def; if (e is Map) { - if ( e.isNotEmpty ) { - var elem = e.entries.first ; - if (elem.key == null) return def ; /*!!!*/ - return MapEntry( parseString(elem.key,'')/*!*/ , parseString(elem.value,'')/*!*/ ) ; - } - else { + if (e.isNotEmpty) { + var elem = e.entries.first; + if (elem.key == null) return def; /*!!!*/ + return MapEntry( + parseString(elem.key, '')!, parseString(elem.value, '')!); + } else { return def; } } else if (e is List) { @@ -1330,7 +1311,7 @@ MapEntry /*?*/ parseMapEntryOfStrings(Object } } else { delimiter ??= RegExp(r'\s*[,;:]\s*'); - var s = parseString(e); + var s = parseString(e)!; var list = split(s, delimiter, 2); if (list.length == 2) { return MapEntry('${list[0]}', '${list[1]}'); @@ -1347,7 +1328,7 @@ MapEntry /*?*/ parseMapEntryOfStrings(Object /// Calculate a hashcode over [o], /// iterating deeply over sub elements if is a [List] or [Map]. -int /*!*/ deepHashCode(Object /*?*/ o) { +int deepHashCode(Object? o) { if (o == null) return 0; if (o is List) { @@ -1360,7 +1341,7 @@ int /*!*/ deepHashCode(Object /*?*/ o) { } /// Computes a hash code inspecting deeply [list]. -int /*!*/ deepHashCodeList(List /*?*/ list) { +int deepHashCodeList(List? list) { if (list == null) return 0; var h = 1; @@ -1373,7 +1354,7 @@ int /*!*/ deepHashCodeList(List /*?*/ list) { } /// Computes a hash code inspecting deeply [map]. -int /*!*/ deepHashCodeMap(Map /*?*/ map) { +int deepHashCodeMap(Map? map) { if (map == null) return 0; var h = 1; @@ -1385,19 +1366,19 @@ int /*!*/ deepHashCodeMap(Map /*?*/ map) { return h; } -typedef Copier = T/*?*/ Function(T/*?*/ o); +typedef Copier = T? Function(T? o); /// Deeply copies [o]. /// /// [copier] Copy [Function] for non-primitive types. -T /*?*/ deepCopy(T /*?*/ o, {Copier /*?*/ copier}) { +T? deepCopy(T? o, {Copier? copier}) { if (o == null) return null; if (o is String) return o; if (o is num) return o; if (o is bool) return o; - if (o is List) return deepCopyList(o, copier: copier) as T; - if (o is Map) return deepCopyMap(o, copier: copier) as T; + if (o is List) return deepCopyList(o, copier: copier) as T?; + if (o is Map) return deepCopyMap(o, copier: copier) as T?; if (copier != null) { return copier(o); @@ -1409,32 +1390,31 @@ T /*?*/ deepCopy(T /*?*/ o, {Copier /*?*/ copier}) { /// Deeply copies [list]. /// /// [copier] Copy [Function] for non-primitive types. -List /*?*/ deepCopyList(List /*?*/ l, {Copier /*?*/ copier}) { +List? deepCopyList(List? l, {Copier? copier}) { if (l == null) return null; if (l.isEmpty) return []; - return l.map((T e) => deepCopy(e, copier: copier) /*!*/).toList(); + return l.map((T e) => deepCopy(e, copier: copier)!).toList(); } /// Deeply copies [map]. /// /// [copier] Copy [Function] for non-primitive types. -Map /*?*/ deepCopyMap(Map /*?*/ map, - {Copier /*?*/ copier}) { +Map? deepCopyMap(Map? map, {Copier? copier}) { if (map == null) return null; if (map.isEmpty) return {}; - return map.map((K k, V v) => MapEntry( - deepCopy(k, copier: copier) /*!*/, deepCopy(v, copier: copier) /*!*/)); + return map.map((K k, V v) => MapEntry( + deepCopy(k, copier: copier)!, deepCopy(v, copier: copier)!)); } typedef ValueFilter = bool Function( - Object/*?*/ collection, Object/*?*/ key, Object/*?*/ value); + Object? collection, Object? key, Object? value); -typedef ValueReplacer = Object/*?*/ Function( - Object/*?*/ collection, Object/*?*/ key, Object/*?*/ value); +typedef ValueReplacer = Object? Function( + Object? collection, Object? key, Object? value); /// Replaces values applying [replacer] to values that matches [filter]. -Object /*?*/ deepReplaceValues( - Object /*?*/ o, ValueFilter /*!*/ filter, ValueReplacer /*!*/ replacer) { +Object? deepReplaceValues( + Object? o, ValueFilter filter, ValueReplacer replacer) { if (o == null) return null; if (filter(null, null, o)) { @@ -1455,7 +1435,7 @@ Object /*?*/ deepReplaceValues( /// Replaces values applying [replacer] to values that matches [filter]. void deepReplaceListValues( - List /*?*/ list, ValueFilter /*!*/ filter, ValueReplacer /*!*/ replacer) { + List? list, ValueFilter filter, ValueReplacer replacer) { if (list == null || list.isEmpty) return; for (var i = 0; i < list.length; ++i) { @@ -1470,7 +1450,7 @@ void deepReplaceListValues( /// Replaces values applying [replacer] to values that matches [filter]. void deepReplaceMapValues( - Map /*?*/ map, ValueFilter /*!*/ filter, ValueReplacer /*!*/ replacer) { + Map? map, ValueFilter filter, ValueReplacer replacer) { if (map == null || map.isEmpty) return; for (var entry in map.entries) { @@ -1486,7 +1466,7 @@ void deepReplaceMapValues( /// Replaces values applying [replacer] to values that matches [filter]. void deepReplaceSetValues( - Set /*?*/ set, ValueFilter /*!*/ filter, ValueReplacer /*!*/ replacer) { + Set? set, ValueFilter filter, ValueReplacer replacer) { if (set == null || set.isEmpty) return; var entries = set.toList(); @@ -1509,8 +1489,7 @@ void deepReplaceSetValues( /// Catches deeply values that matches [filter]. /// /// Returns a [List] of the matched values -List /*!*/ deepCatchesValues(Object /*?*/ o, ValueFilter /*!*/ filter, - [List /*?*/ result]) { +List deepCatchesValues(Object? o, ValueFilter filter, [List? result]) { result ??= []; if (o == null) return result; @@ -1531,8 +1510,7 @@ List /*!*/ deepCatchesValues(Object /*?*/ o, ValueFilter /*!*/ filter, /// Catches deeply [list] values that matches [filter]. /// /// Returns a [List] of the matched values -List /*!*/ deepCatchesListValues(List /*?*/ list, ValueFilter /*!*/ filter, - [List /*?*/ result]) { +List deepCatchesListValues(List? list, ValueFilter filter, [List? result]) { result ??= []; if (list == null || list.isEmpty) return result; @@ -1552,8 +1530,7 @@ List /*!*/ deepCatchesListValues(List /*?*/ list, ValueFilter /*!*/ filter, /// Catches deeply [map] values that matches [filter]. /// /// Returns a [List] of the matched values -List /*!*/ deepCatchesMapValues(Map /*?*/ map, ValueFilter /*!*/ filter, - [List /*?*/ result]) { +List deepCatchesMapValues(Map? map, ValueFilter filter, [List? result]) { result ??= []; if (map == null || map.isEmpty) return result; @@ -1574,8 +1551,7 @@ List /*!*/ deepCatchesMapValues(Map /*?*/ map, ValueFilter /*!*/ filter, /// Catches deeply [set] values that matches [filter]. /// /// Returns a [List] of the matched values -List /*!*/ deepCatchesSetValues(Set /*?*/ set, ValueFilter /*!*/ filter, - [List /*?*/ result]) { +List deepCatchesSetValues(Set? set, ValueFilter filter, [List? result]) { result ??= []; if (set == null || set.isEmpty) return result; @@ -1591,17 +1567,30 @@ List /*!*/ deepCatchesSetValues(Set /*?*/ set, ValueFilter /*!*/ filter, return result; } +/// Returns the instance that matches [value] in [set]. +T? getSetEntryInstance(Set? set, T? value) { + if (set == null || value == null) return null; + if (!set.contains(value)) return null; + + for (var elem in set) { + if (elem == value) { + return elem; + } + } + return null; +} + /// A [Map] that delegates to another [_map]. /// Useful to extend [Map] features. -class MapDelegate implements Map { - final Map _map; +class MapDelegate implements Map { + final Map _map; MapDelegate(this._map); Map get mainMap => _map; @override - V operator [](Object /*?*/ key) => _map[key as Object /*?*/]; /*!!!*/ + V? operator [](Object? key) => _map[key]; @override void operator []=(K key, value) => _map[key] = value; @@ -1620,10 +1609,10 @@ class MapDelegate implements Map { void clear() => _map.clear(); @override - bool containsKey(Object key) => _map.containsKey(key); + bool containsKey(Object? key) => _map.containsKey(key); @override - bool containsValue(Object value) => _map.containsValue(value); + bool containsValue(Object? value) => _map.containsValue(value); @override Iterable> get entries => _map.entries; @@ -1652,14 +1641,14 @@ class MapDelegate implements Map { _map.putIfAbsent(key, ifAbsent); @override - V remove(Object key) => _map.remove(key); + V? remove(Object? key) => _map.remove(key); @override void removeWhere(bool Function(K key, V value) predicate) => _map.removeWhere(predicate); @override - V update(K key, V Function(V value) update, {V Function() ifAbsent}) => + V update(K key, V Function(V value) update, {V Function()? ifAbsent}) => _map.update(key, update); @override @@ -1670,9 +1659,9 @@ class MapDelegate implements Map { } /// A [Map] of properties. -class MapProperties extends MapDelegate { +class MapProperties extends MapDelegate { /// Parses [value] to a valid property [value]. - static Object/*?*/ parseValue(Object/*?*/ value) { + static Object? parseValue(Object? value) { if (isInt(value)) { return parseInt(value); } else if (isDouble(value)) { @@ -1696,27 +1685,29 @@ class MapProperties extends MapDelegate { /// Parse [stringProperties] to properties values. static Map parseStringProperties( - Map stringProperties) { - if (stringProperties == null || stringProperties.isEmpty) return {}; + Map? stringProperties) { + if (stringProperties == null || stringProperties.isEmpty) { + return {}; + } return stringProperties.map((k, v) => MapEntry(k, parseValue(v))); } MapProperties() : super({}); MapProperties.fromProperties(Map properties) - : super(Map.from((properties ?? {})).cast()); + : super(Map.from(properties)); MapProperties.fromStringProperties(Map stringProperties) : super(parseStringProperties(stringProperties)); MapProperties.fromMap(Map properties) - : super((properties ?? {}) - .map((k, v) => MapEntry(parseString(k), parseString(v)))); + : super(properties + .map((k, v) => MapEntry(parseString(k, '')!, parseString(v, '')!))); /// Gets a property with [key]. /// /// [def] The default value if [key] not found. - T /*?*/ getProperty(String /*!*/ key, [T /*?*/ def]) { + T? getProperty(String key, [T? def]) { var val = findKeyValue(_map, [key], true); return val != null ? val as T : def; } @@ -1724,7 +1715,7 @@ class MapProperties extends MapDelegate { /// Finds a property with [keys]. /// /// [def] The default value if [keys] not found. - T /*?*/ findProperty(List /*!*/ keys, [T /*?*/ def]) { + T? findProperty(List keys, [T? def]) { var val = findKeyValue(_map, keys, true); return val != null ? val as T : def; } @@ -1734,8 +1725,7 @@ class MapProperties extends MapDelegate { /// [mapper] Maps the value to [T]. /// [def] The default value if [key] not found. // ignore: use_function_type_syntax_for_parameters - T /*?*/ getPropertyAs(String /*!*/ key, T /*?*/ mapper(dynamic v), - [T /*?*/ def]) { + T? getPropertyAs(String key, T? mapper(dynamic v), [T? def]) { var val = findKeyValue(_map, [key], true); return val != null ? mapper(val) : def; } @@ -1745,8 +1735,7 @@ class MapProperties extends MapDelegate { /// [mapper] Maps the value to [T]. /// [def] The default value if [key] not found. // ignore: use_function_type_syntax_for_parameters - T /*?*/ findPropertyAs(List keys, T /*?*/ mapper(dynamic v), - [T /*?*/ def]) { + T? findPropertyAs(List keys, T? mapper(dynamic v), [T? def]) { var val = findKeyValue(_map, keys, true); return val != null ? mapper(val) : def; } @@ -1754,7 +1743,7 @@ class MapProperties extends MapDelegate { /// Gets a property with [key]. Returns the value in lower case and trimmed. /// /// [def] The default value if [key] not found. - String getPropertyAsStringTrimLC(String key, [String /*?*/ def]) { + String? getPropertyAsStringTrimLC(String key, [String? def]) { var val = getPropertyAsStringTrim(key, def); return val != null ? val.toLowerCase() : null; } @@ -1762,7 +1751,7 @@ class MapProperties extends MapDelegate { /// Finds a property with [keys]. Returns the value in lower case and trimmed. /// /// [def] The default value if [keys] not found. - String findPropertyAsStringTrimLC(List keys, [String /*?*/ def]) { + String? findPropertyAsStringTrimLC(List keys, [String? def]) { var val = findPropertyAsStringTrim(keys, def); return val != null ? val.toLowerCase() : null; } @@ -1770,7 +1759,7 @@ class MapProperties extends MapDelegate { /// Gets a property with [key]. Returns the value in upper case and trimmed. /// /// [def] The default value if [key] not found. - String getPropertyAsStringTrimUC(String key, [String /*?*/ def]) { + String? getPropertyAsStringTrimUC(String key, [String? def]) { var val = getPropertyAsStringTrim(key, def); return val != null ? val.toUpperCase() : null; } @@ -1778,7 +1767,7 @@ class MapProperties extends MapDelegate { /// Finds a property with [keys]. Returns the value in upper case and trimmed. /// /// [def] The default value if [keys] not found. - String findPropertyAsStringTrimUC(List keys, [String /*?*/ def]) { + String? findPropertyAsStringTrimUC(List keys, [String? def]) { var val = findPropertyAsStringTrim(keys, def); return val != null ? val.toUpperCase() : null; } @@ -1786,7 +1775,7 @@ class MapProperties extends MapDelegate { /// Gets a property with [key]. Returns the value trimmed. /// /// [def] The default value if [key] not found. - String getPropertyAsStringTrim(String key, [String /*?*/ def]) { + String? getPropertyAsStringTrim(String key, [String? def]) { var val = getPropertyAsString(key, def); return val != null ? val.trim() : null; } @@ -1794,7 +1783,7 @@ class MapProperties extends MapDelegate { /// Finds a property with [keys]. Returns the value trimmed. /// /// [def] The default value if [keys] not found. - String findPropertyAsStringTrim(List keys, [String /*?*/ def]) { + String? findPropertyAsStringTrim(List keys, [String? def]) { var val = findPropertyAsString(keys, def); return val != null ? val.trim() : null; } @@ -1802,167 +1791,165 @@ class MapProperties extends MapDelegate { /// Gets a property with [key]. Returns the value as [String]. /// /// [def] The default value if [key] not found. - String getPropertyAsString(String key, [String /*?*/ def]) => + String? getPropertyAsString(String key, [String? def]) => getPropertyAs(key, parseString, def); /// Gets a property with [key]. Returns the value as [int]. /// /// [def] The default value if [key] not found. - int getPropertyAsInt(String key, [int /*?*/ def]) => + int? getPropertyAsInt(String key, [int? def]) => getPropertyAs(key, parseInt, def); /// Gets a property with [key]. Returns the value as [double]. /// /// [def] The default value if [key] not found. - double getPropertyAsDouble(String key, [double /*?*/ def]) => + double? getPropertyAsDouble(String key, [double? def]) => getPropertyAs(key, parseDouble, def); /// Gets a property with [key]. Returns the value as [num]. /// /// [def] The default value if [key] not found. - num getPropertyAsNum(String key, [num /*?*/ def]) => + num? getPropertyAsNum(String key, [num? def]) => getPropertyAs(key, parseNum, def); /// Gets a property with [key]. Returns the value as [bool]. /// /// [def] The default value if [key] not found. - bool getPropertyAsBool(String key, [bool /*?*/ def]) => + bool? getPropertyAsBool(String key, [bool? def]) => getPropertyAs(key, parseBool, def); /// Gets a property with [key]. Returns the value as [DateTime]. /// /// [def] The default value if [key] not found. - DateTime getPropertyAsDateTime(String key, [DateTime /*?*/ def]) => + DateTime? getPropertyAsDateTime(String key, [DateTime? def]) => getPropertyAs(key, parseDateTime, def); /// Finds a property with [keys]. Returns the value as [String]. /// /// [def] The default value if [keys] not found. - String /*?*/ findPropertyAsString(List keys, [String /*?*/ def]) => + String? findPropertyAsString(List keys, [String? def]) => findPropertyAs(keys, (e) => parseString(e), def); /// Finds a property with [keys]. Returns the value as [int]. /// /// [def] The default value if [keys] not found. - int findPropertyAsInt(List keys, [int /*?*/ def]) => + int? findPropertyAsInt(List keys, [int? def]) => findPropertyAs(keys, parseInt, def); /// Finds a property with [keys]. Returns the value as [double]. /// /// [def] The default value if [keys] not found. - double findPropertyAsDouble(List keys, [double /*?*/ def]) => + double? findPropertyAsDouble(List keys, [double? def]) => findPropertyAs(keys, parseDouble, def); /// Finds a property with [keys]. Returns the value as [num]. /// /// [def] The default value if [keys] not found. - num findPropertyAsNum(List keys, [num /*?*/ def]) => + num? findPropertyAsNum(List keys, [num? def]) => findPropertyAs(keys, parseNum, def); /// Finds a property with [keys]. Returns the value as [bool]. /// /// [def] The default value if [keys] not found. - bool findPropertyAsBool(List keys, [bool /*?*/ def]) => + bool? findPropertyAsBool(List keys, [bool? def]) => findPropertyAs(keys, parseBool, def); /// Finds a property with [keys]. Returns the value as [DateTime]. /// /// [def] The default value if [keys] not found. - DateTime findPropertyAsDateTime(List keys, [DateTime /*?*/ def]) => + DateTime? findPropertyAsDateTime(List keys, [DateTime? def]) => findPropertyAs(keys, parseDateTime, def); /// Gets a property with [key] as [List]. /// /// [def] The default value if [key] not found. - List getPropertyAsStringList(String key, [List /*?*/ def]) => + List? getPropertyAsStringList(String key, [List? def]) => getPropertyAs(key, (v) => parseStringFromInlineList(v, ',', def), def); /// Gets a property with [key] as [List]. /// /// [def] The default value if [key] not found. - List getPropertyAsIntList(String key, [List /*?*/ def]) => + List? getPropertyAsIntList(String key, [List? def]) => getPropertyAs(key, (v) => parseIntsFromInlineList(v, ',', def), def); /// Gets a property with [key] as [List]. /// /// [def] The default value if [key] not found. - List getPropertyAsDoubleList(String key, [List /*?*/ def]) => + List? getPropertyAsDoubleList(String key, [List? def]) => getPropertyAs(key, (v) => parseDoublesFromInlineList(v, ',', def), def); /// Gets a property with [key] as [List]. /// /// [def] The default value if [key] not found. - List getPropertyAsNumList(String key, [List /*?*/ def]) => + List? getPropertyAsNumList(String key, [List? def]) => getPropertyAs(key, (v) => parseNumsFromInlineList(v, ',', def), def); /// Gets a property with [key] as [List]. /// /// [def] The default value if [key] not found. - List /*?*/ getPropertyAsBoolList(String key, - [List /*?*/ def]) => + List? getPropertyAsBoolList(String key, [List? def]) => getPropertyAs(key, (v) => parseBoolsFromInlineList(v, ',', def), def); /// Gets a property with [key] as [List]. /// /// [def] The default value if [key] not found. - List /*?*/ getPropertyAsDateTimeList(String key, - [List /*?*/ def]) => + List? getPropertyAsDateTimeList(String key, + [List? def]) => getPropertyAs(key, (v) => parseDateTimeFromInlineList(v, ',', def), def); /// Finds a property with [keys] as [List]. /// /// [def] The default value if [keys] not found. - List findPropertyAsStringList(List keys, - [List /*?*/ def]) => + List? findPropertyAsStringList(List keys, + [List? def]) => findPropertyAs(keys, (v) => parseStringFromInlineList(v, ',', def), def); /// Finds a property with [keys] as [List]. /// /// [def] The default value if [keys] not found. - List findPropertyAsIntList(List keys, [List /*?*/ def]) => + List? findPropertyAsIntList(List keys, [List? def]) => findPropertyAs(keys, (v) => parseIntsFromInlineList(v, ',', def), def); /// Finds a property with [keys] as [List]. /// /// [def] The default value if [keys] not found. - List findPropertyAsDoubleList(List keys, - [List /*?*/ def]) => + List? findPropertyAsDoubleList(List keys, + [List? def]) => findPropertyAs(keys, (v) => parseDoublesFromInlineList(v, ',', def), def); /// Finds a property with [keys] as [List]. /// /// [def] The default value if [keys] not found. - List findPropertyAsNumList(List keys, [List /*?*/ def]) => + List? findPropertyAsNumList(List keys, [List? def]) => findPropertyAs(keys, (v) => parseNumsFromInlineList(v, ',', def), def); /// Finds a property with [keys] as [List]. /// /// [def] The default value if [keys] not found. - List findPropertyAsBoolList(List keys, - [List /*?*/ def]) => + List? findPropertyAsBoolList(List keys, [List? def]) => findPropertyAs(keys, (v) => parseBoolsFromInlineList(v, ',', def), def); /// Finds a property with [keys] as [List]. /// /// [def] The default value if [keys] not found. - List findPropertyAsDateTimeList(List keys, - [List /*?*/ def]) => + List? findPropertyAsDateTimeList(List keys, + [List? def]) => findPropertyAs( keys, (v) => parseDateTimeFromInlineList(v, ',', def), def); /// Gets a property with [key] as [List]. /// /// [def] The default value if [key] not found. - Map getPropertyAsStringMap(String key, - [Map /*?*/ def]) => + Map? getPropertyAsStringMap(String key, + [Map? def]) => getPropertyAs( key, (v) => parseStringFromInlineMap(v, ';', ':', def), def); /// Finds a property with [keys] as [List]. /// /// [def] The default value if [keys] not found. - Map findPropertyAsStringMap(List keys, - [Map /*?*/ def]) => + Map? findPropertyAsStringMap(List keys, + [Map? def]) => findPropertyAs( keys, (v) => parseStringFromInlineMap(v, ';', ':', def), def); @@ -1972,8 +1959,8 @@ class MapProperties extends MapDelegate { } /// Returns this as a [Map]. - Map /*!*/ toStringProperties() { - return _map.map((k, v) => MapEntry(k /*!*/, parseString(v) /*!*/)); + Map toStringProperties() { + return _map.map((k, v) => MapEntry(k, parseString(v)!)); } /// put property [value] to [key]. @@ -1986,7 +1973,7 @@ class MapProperties extends MapDelegate { } /// Returns [value] as a [String]. - static String/*?*/ toStringValue(Object/*?*/ value, [String/*?*/ def]) { + static String? toStringValue(Object? value, [String? def]) { if (value == null) return def; String valueStr; @@ -1994,7 +1981,7 @@ class MapProperties extends MapDelegate { if (value is String) { valueStr = value; } else if (value is List) { - valueStr = value.map( (e) => toStringValue(e) ).join(','); + valueStr = value.map((e) => toStringValue(e)).join(','); } else if (value is Map) { valueStr = value.entries .expand((e) => ['${e.key}:${toStringValue(e.value)}']) @@ -2047,9 +2034,9 @@ class MapProperties extends MapDelegate { /// Groups [interable] entries using [map] to generate a [MapEntry] for /// each entry, than uses [merge] to group entries of the same group (key). Map groupIterableBy( - Iterable /*!*/ iterable, - MapEntry Function(I entry) /*!*/ map, - V Function(K key, V value1, V value2) /*!*/ merge) { + Iterable iterable, + MapEntry Function(I entry) map, + V Function(K key, V value1, V value2) merge) { if (iterable.isEmpty) return {}; var groups = {}; @@ -2075,10 +2062,10 @@ Map groupIterableBy( /// Merges all entries of [iterable] using [merge] function. /// /// [init] The initial value of total. -R /*?*/ mergeIterable( - Iterable /*!*/ iterable, R Function(R /*?*/ total, I value) /*!*/ merge, - [R /*?*/ init]) { - if (iterable == null || iterable.isEmpty) return init; +R? mergeIterable( + Iterable iterable, R Function(R? total, I value) merge, + [R? init]) { + if (iterable.isEmpty) return init; var total = init; @@ -2090,56 +2077,47 @@ R /*?*/ mergeIterable( } /// Uses [mergeIterable] to sum all [iterable] values. -num /*!*/ sumIterable(Iterable /*!*/ iterable, - {num /*!*/ init = 0}) => - mergeIterable( - iterable, (num total, num value) => total + value, init) /*!*/; +num sumIterable(Iterable iterable, {num init = 0}) => + mergeIterable(iterable, (num? total, num value) => total! + value, init)!; /// Uses [mergeIterable] to find maximum value in [iterable]. -num /*?*/ maxInIterable(Iterable /*!*/ iterable) => iterable.isEmpty +num? maxInIterable(Iterable iterable) => iterable.isEmpty ? null : mergeIterable( - iterable, - (num total, num value) => value > total /*!*/ - ? value - : total /*!*/, - 0); + iterable, (num? total, num value) => value > total! ? value : total, 0); /// Uses [mergeIterable] to find minimum value in [iterable]. -num /*?*/ minInIterable(Iterable /*!*/ iterable) => iterable.isEmpty +num? minInIterable(Iterable iterable) => iterable.isEmpty ? null : mergeIterable( iterable, - (num total, num value) => value < total /*!*/ - ? value - : total /*!*/, + (num? total, num value) => value < total! ? value : total, iterable.first); /// Calculate the average value of [iterable]. -num /*?*/ averageIterable(Iterable iterable) => +num? averageIterable(Iterable iterable) => iterable.isEmpty ? null : sumIterable(iterable) / iterable.length; /// A field that can't be null. If a null value is set to it, /// a default value will be used. class NNField { - final T /*!*/ defaultValue; + final T defaultValue; /// If [true], [hashCode] will use [deepHashCode] for calculation. - final bool /*!*/ deepHashcode; + final bool deepHashcode; /// Optional value filter to apply before set. - final T /*!*/ Function(dynamic value) /*?*/ filter; + final T Function(dynamic value)? filter; /// Optional value to apply before get. - final T /*!*/ Function(T value) /*?*/ resolver; + final T Function(T value)? resolver; - T /*!*/ _value; + T _value; NNField(this.defaultValue, - {bool /*!*/ deepHashcode = false, this.filter, this.resolver}) - : deepHashcode = deepHashcode { - _value = defaultValue; - } + {bool deepHashcode = false, this.filter, this.resolver}) + : deepHashcode = deepHashcode, + _value = defaultValue; /// The filed value as [T]. T get value => get(); @@ -2147,9 +2125,9 @@ class NNField { set value(dynamic value) => set(value); /// Returns the current filed [value]. - T /*!*/ get() { + T get() { if (resolver != null) { - return resolver(_value); + return resolver!(_value); } return _value; } @@ -2159,12 +2137,12 @@ class NNField { /// If [value] is null uses [defaultValue]. /// /// Applies [filter] if exists and [value] is not null. - void set(V /*?*/ value) { + void set(V? value) { if (value == null) { _value = defaultValue; } else { if (filter != null) { - _value = filter(value ?? defaultValue) ?? defaultValue; + _value = filter!(value) ?? defaultValue; } else { try { _value = value as T; @@ -2190,7 +2168,7 @@ class NNField { /// Returns [true] if [other] is equals to [this.value]. /// /// If [other] is a [NNField], compares with [other.value]. - bool equals(Object/*?*/ other) { + bool equals(Object? other) { if (other == null) return false; if (other is NNField) { return equals(other._value); @@ -2209,71 +2187,71 @@ class NNField { @override String toString() => asString; - String /*!*/ get asString => parseString(_value, '') /*!*/; + String get asString => parseString(_value, '')!; /// [value] as [num]. - num get asNum => parseNum(_value); + num? get asNum => parseNum(_value); /// [value] as [int]. - int get asInt => parseInt(_value); + int? get asInt => parseInt(_value); /// [value] as [double]. - double get asDouble => parseDouble(_value); + double? get asDouble => parseDouble(_value); /// [value] as [bool]. - bool get asBool => parseBool(_value); + bool? get asBool => parseBool(_value); /// Operator [*], using [asNum] for [this.value] and [parseNum(value)] for parameter. - num operator *(dynamic value) => asNum * parseNum(value); + num operator *(dynamic value) => asNum! * parseNum(value)!; /// Operator [/], using [asNum] for [this.value] and [parseNum(value)] for parameter. - num operator /(dynamic value) => asNum / parseNum(value); + num operator /(dynamic value) => asNum! / parseNum(value)!; /// Operator [+], using [asNum] for [this.value] and [parseNum(value)] for parameter. - num operator +(dynamic value) => asNum + parseNum(value); + num operator +(dynamic value) => asNum! + parseNum(value)!; /// Operator [-], using [asNum] for [this.value] and [parseNum(value)] for parameter. - num operator -(dynamic value) => asNum - parseNum(value); + num operator -(dynamic value) => asNum! - parseNum(value)!; /// Operator [^], using [asInt] for [this.value] and [parseInt(value)] for parameter. - num operator ^(dynamic value) => asInt ^ parseInt(value); + num operator ^(dynamic value) => asInt! ^ parseInt(value)!; /// Operator [>], using [asNum] for [this.value] and [parseNum(value)] for parameter. - bool operator >(num value) => asNum > parseNum(value); + bool operator >(num value) => asNum! > parseNum(value)!; /// Operator [>=], using [asNum] for [this.value] and [parseNum(value)] for parameter. - bool operator >=(num value) => asNum >= parseNum(value); + bool operator >=(num value) => asNum! >= parseNum(value)!; /// Operator [<], using [asNum] for [this.value] and [parseNum(value)] for parameter. - bool operator <(num value) => asNum < parseNum(value); + bool operator <(num value) => asNum! < parseNum(value)!; /// Operator [<=], using [asNum] for [this.value] and [parseNum(value)] for parameter. - bool operator <=(num value) => asNum <= parseNum(value); + bool operator <=(num value) => asNum! <= parseNum(value)!; /// Increments: [this.value] + [value] - num increment(dynamic value) { - var result = parseNum(_value) + parseNum(value); + num? increment(dynamic value) { + var result = parseNum(_value)! + parseNum(value)!; set(result); return asNum; } /// Decrements: [this.value] - [value] - num decrement(dynamic value) { - var result = parseNum(_value) - parseNum(value); + num? decrement(dynamic value) { + var result = parseNum(_value)! - parseNum(value)!; set(result); return asNum; } /// Multiply: [this.value] * [value] - num multiply(dynamic value) { - var result = parseNum(_value) * parseNum(value); + num? multiply(dynamic value) { + var result = parseNum(_value)! * parseNum(value)!; set(result); return asNum; } /// Divide: [this.value] / [value] - num divide(dynamic value) { - var result = parseNum(_value) / parseNum(value); + num? divide(dynamic value) { + var result = parseNum(_value)! / parseNum(value)!; set(result); return asNum; } @@ -2283,26 +2261,26 @@ class NNField { /// instantiators for each key. class ObjectCache { /// Maximum number of cached instances. - int /*?*/ maxInstances; + int? maxInstances; ObjectCache([this.maxInstances]); final Map _cacheInstances = {}; - final Map _cacheInstantiators = {}; - final Map _cacheValidators = {}; + final Map _cacheInstantiators = {}; + final Map _cacheValidators = {}; /// Sets the [instantiator] for [key] - void setInstantiator(String /*!*/ key, O Function() instantiator) => + void setInstantiator(String key, O Function() instantiator) => _cacheInstantiators[key] = instantiator; /// Sets the [cacheValidator] for [key] - void setCacheValidator(String /*!*/ key, bool Function() cacheValidator) => + void setCacheValidator(String key, bool Function() cacheValidator) => _cacheValidators[key] = cacheValidator; /// Defines instantiator and cache-validator for [key]. - void define(String /*!*/ key, O Function() instantiator, - [bool Function() /*?*/ cacheValidator]) { + void define(String key, O Function() instantiator, + [bool Function()? cacheValidator]) { _cacheInstantiators[key] = instantiator; if (cacheValidator != null) { _cacheValidators[key] = cacheValidator; @@ -2310,7 +2288,7 @@ class ObjectCache { } /// Remove instantiator and cache-validator for [key]. - void undefine(String /*!*/ key) { + void undefine(String key) { _cacheInstantiators.remove(key); _cacheValidators.remove(key); } @@ -2326,7 +2304,7 @@ class ObjectCache { bool _define(String key, value) { if (value is Function) { - define(key, value); + define(key, value as Object Function()); return true; } else if (value is List) { if (value.length == 1) { @@ -2345,14 +2323,15 @@ class ObjectCache { /// Uses [instantiator] (or pre-defined) to instantiate. /// /// Uses [cacheValidator] (or pre-defined) to validade already cached instance. - O /*?*/ get(String /*!*/ key, - [O Function() /*?*/ instantiator, bool Function() /*?*/ cacheValidator]) { + O? get(String key, + [O Function()? instantiator, bool Function()? cacheValidator]) { var o = _cacheInstances[key]; if (o != null) { cacheValidator ??= _cacheValidators[key]; - if (cacheValidator != null) { /*!!!*/ + if (cacheValidator != null) { + /*!!!*/ var ok = cacheValidator(); if (ok) { return o; @@ -2364,11 +2343,11 @@ class ObjectCache { } } - instantiator ??= _cacheInstantiators[key]; + instantiator ??= _cacheInstantiators[key] as O Function()?; if (instantiator == null) return null; - if (maxInstances != null && maxInstances > 0) { - var needToRemove = _cacheInstances.length - (maxInstances - 1); + if (maxInstances != null && maxInstances! > 0) { + var needToRemove = _cacheInstances.length - (maxInstances! - 1); disposeInstances(needToRemove); } @@ -2378,7 +2357,7 @@ class ObjectCache { return o; } - int disposeInstances(int amountToRemove) { + int disposeInstances(int? amountToRemove) { if (amountToRemove == null || amountToRemove < 1) return 0; var keys = List.from(_cacheInstances.keys); @@ -2424,7 +2403,7 @@ class ObjectCache { /// and be able to associate values with any [Node] in DOM tree. class TreeReferenceMap implements Map { /// The root of the Tree Reference. - final K /*!*/ root; + final K root; /// If true, each operation performs a purge. final bool autoPurge; @@ -2433,30 +2412,30 @@ class TreeReferenceMap implements Map { final bool keepPurgedEntries; /// Purged entries timeout. - final Duration purgedEntriesTimeout; + final Duration? purgedEntriesTimeout; /// Maximum number of purged entries. - final int maxPurgedEntries; + final int? maxPurgedEntries; /// The [Function] that returns the parent of a key. - final K/*?*/ Function(K key) parentGetter; + final K? Function(K key)? parentGetter; /// The [Function] that returns the children of a key. - final Iterable Function(K key) childrenGetter; + final Iterable Function(K key)? childrenGetter; /// The [Function] that returns true if [parent] has [child]. - final bool Function(K parent, K child, bool deep) childChecker; + final bool Function(K parent, K child, bool deep)? childChecker; TreeReferenceMap(this.root, - {bool /*!*/ autoPurge = false, - bool /*!*/ keepPurgedKeys = false, + {bool autoPurge = false, + bool keepPurgedKeys = false, this.purgedEntriesTimeout, this.maxPurgedEntries, this.parentGetter, this.childrenGetter, this.childChecker}) : autoPurge = autoPurge, - keepPurgedEntries = keepPurgedKeys ; + keepPurgedEntries = keepPurgedKeys; final Map _map = {}; @@ -2466,12 +2445,12 @@ class TreeReferenceMap implements Map { _expireCache(); } - V get(K key) { + V? get(K key) { doAutoPurge(); return _map[key]; } - V getAlsoFromPurgedEntries(K key) { + V? getAlsoFromPurgedEntries(K key) { doAutoPurge(); return _map[key] ?? getFromPurgedEntries(key); } @@ -2499,12 +2478,12 @@ class TreeReferenceMap implements Map { /// Will call [parentGetter]. /// /// Should be overwritten if [parentGetter] is null. - K/*?*/ getParentOf(K key) => parentGetter(key); + K? getParentOf(K key) => parentGetter!(key); /// Return sub values of [key]. List getSubValues(K key, {bool includePurgedEntries = false}) { var subValues = []; - if (includePurgedEntries ?? false) { + if (includePurgedEntries) { _getSubValuesImpl_includePurgedEntries(key, subValues); } else { _getSubValuesImpl(key, subValues); @@ -2514,7 +2493,7 @@ class TreeReferenceMap implements Map { void _getSubValuesImpl(K key, List subValues) { var children = getChildrenOf(key); - if (children == null || children.isEmpty) return; + if (children.isEmpty) return; for (var child in children) { var value = get(child); @@ -2528,7 +2507,7 @@ class TreeReferenceMap implements Map { void _getSubValuesImpl_includePurgedEntries(K key, List subValues) { var children = getChildrenOf(key); - if (children == null || children.isEmpty) return; + if (children.isEmpty) return; for (var child in children) { var value = getAlsoFromPurgedEntries(child); @@ -2541,20 +2520,20 @@ class TreeReferenceMap implements Map { } /// Get 1st parent value of [child]; - V getParentValue(K child, {bool includePurgedEntries = false}) { + V? getParentValue(K child, {bool includePurgedEntries = false}) { var parent = getParentKey(child); return parent != null - ? ((includePurgedEntries ?? false) + ? (includePurgedEntries ? getAlsoFromPurgedEntries(parent) : get(parent)) : null; } /// Get 1st parent key of [child]; - K getParentKey(K child, {bool includePurgedEntries = false}) { + K? getParentKey(K child, {bool includePurgedEntries = false}) { if (child == null || identical(child, root)) return null; - if (includePurgedEntries ?? false) { + if (includePurgedEntries) { var purged = _purged ?? >{}; var cursor = getParentOf(child); while (cursor != null) { @@ -2583,7 +2562,7 @@ class TreeReferenceMap implements Map { /// Will call [childrenGetter]. /// /// Should be overwritten if [childrenGetter] is null. - Iterable getChildrenOf(K key) => childrenGetter(key); + Iterable getChildrenOf(K key) => childrenGetter!(key); /// Returns true if [parent] has [child]. If [deep] is true, will check sub nodes children. /// @@ -2591,15 +2570,16 @@ class TreeReferenceMap implements Map { /// /// Should be overwritten if [childChecker] is null. bool isChildOf(K parent, K child, bool deep) => - childChecker(parent, child, deep); + childChecker!(parent, child, deep); - Map> /*?*/ _purged; + Map>? _purged; /// Returns the purged entries length. Only relevant if [keepPurgedEntries] is true. - int get purgedLength => _purged != null ? _purged.length : 0; + int get purgedLength => _purged != null ? _purged!.length : 0; /// Returns [key] value from purged entries. Only relevant if [keepPurgedEntries] is true. - V getFromPurgedEntries(K key) => _purged != null ? _purged[key]?.value : null; + V? getFromPurgedEntries(K key) => + _purged != null ? _purged![key]?.value : null; /// Disposes purged entries. Only relevant if [keepPurgedEntries] is true. void disposePurgedEntries() { @@ -2657,9 +2637,9 @@ class TreeReferenceMap implements Map { /// Removed purged entries over [maxPurgedEntries] limit. void checkPurgeEntriesLimit() { - if (_purged != null && maxPurgedEntries != null && maxPurgedEntries > 0) { - var purged = _purged /*!*/; - var needToRemove = purged.length - maxPurgedEntries; + if (_purged != null && maxPurgedEntries != null && maxPurgedEntries! > 0) { + var purged = _purged!; + var needToRemove = purged.length - maxPurgedEntries!; if (needToRemove > 0) { var del = []; for (var k in purged.keys) { @@ -2681,9 +2661,9 @@ class TreeReferenceMap implements Map { void checkPurgedEntriesTimeout() { if (_purged != null && purgedEntriesTimeout != null && - purgedEntriesTimeout.inMilliseconds > 0) { - var purged = _purged /*!*/; - var timeoutMs = purgedEntriesTimeout.inMilliseconds; + purgedEntriesTimeout!.inMilliseconds > 0) { + var purged = _purged!; + var timeoutMs = purgedEntriesTimeout!.inMilliseconds; var now = DateTime.now().millisecondsSinceEpoch; var expired = purged.entries .where((e) => (now - e.value.key.millisecondsSinceEpoch) > timeoutMs) @@ -2706,7 +2686,7 @@ class TreeReferenceMap implements Map { /// Restore purged entries that are currently valid. Only relevant if [keepPurgedEntries] is true. int revalidatePurgedEntries() { if (_purged != null) { - var purged = _purged /*!*/; + var purged = _purged!; var validPurged = purged.entries .where((e) => isValidEntry(e.key, e.value.value)) .toList(); @@ -2735,11 +2715,11 @@ class TreeReferenceMap implements Map { /// Returns the purged entries. Only relevant if [keepPurgedEntries] is true. List> get purgedEntries => _purged != null - ? _purged.entries.map((e) => MapEntry(e.key, e.value.value)).toList() + ? _purged!.entries.map((e) => MapEntry(e.key, e.value.value)).toList() : >[]; /// Returns the purged keys. Only relevant if [keepPurgedEntries] is true. - List get purgedKeys => _purged != null ? _purged.keys.toList() : []; + List get purgedKeys => _purged != null ? _purged!.keys.toList() : []; /// Returns the valid keys. List get validKeys => _map.entries @@ -2754,17 +2734,17 @@ class TreeReferenceMap implements Map { .toList(); /// Walks tree from [root] and stops when [walker] returns some [R] object. - R walkTree(R Function(K node) walker, {K root}) { + R? walkTree(R Function(K node) walker, {K? root}) { root ??= this.root; - return _walkTreeImpl(root, walker); + return _walkTreeImpl(root!, walker); } - R _walkTreeImpl(K node, R Function(K node) walker) { + R? _walkTreeImpl(K node, R Function(K node) walker) { var children = getChildrenOf(node); - if (children == null || children.isEmpty) return null; + if (children.isEmpty) return null; for (var child in children) { - var ret = walker(child); + R? ret = walker(child); if (ret != null) { return ret; } @@ -2798,19 +2778,19 @@ class TreeReferenceMap implements Map { } @override - bool containsKey(Object key) { + bool containsKey(Object? key) { doAutoPurge(); return _map.containsKey(key); } @override - bool containsValue(Object value) { + bool containsValue(Object? value) { doAutoPurge(); return _map.containsValue(value); } @override - V remove(Object key) { + V? remove(Object? key) { var rm = _map.remove(key); doAutoPurge(); _expireCache(); @@ -2829,21 +2809,21 @@ class TreeReferenceMap implements Map { _expireCache(); } - List _keysReversedList; + List? _keysReversedList; /// Returns [keys] reversed (unmodifiable); List get keysReversed { _keysReversedList ??= _map.keys.toList().reversed.toList(); - return UnmodifiableListView(_keysReversedList); + return UnmodifiableListView(_keysReversedList!); } - List _purgedKeysReversedList; + List? _purgedKeysReversedList; /// Returns [purgedKeys] reversed (unmodifiable); List get purgedKeysReversed { _purgedKeysReversedList ??= - _purged != null ? _purged.keys.toList().reversed.toList() : []; - return UnmodifiableListView(_purgedKeysReversedList); + _purged != null ? _purged!.keys.toList().reversed.toList() : []; + return UnmodifiableListView(_purgedKeysReversedList!); } void _expireCache() { @@ -2864,7 +2844,7 @@ class TreeReferenceMap implements Map { } @override - V operator [](Object key) => key is K ? get(key) : null; + V? operator [](Object? key) => key is K ? get(key) : null; @override void operator []=(K key, V value) => put(key, value); @@ -2919,7 +2899,7 @@ class TreeReferenceMap implements Map { } @override - V update(K key, V Function(V value) update, {V Function() ifAbsent}) { + V update(K key, V Function(V value) update, {V Function()? ifAbsent}) { doAutoPurge(); var val = _map.update(key, update, ifAbsent: ifAbsent); _expireCache(); diff --git a/lib/src/data.dart b/lib/src/data.dart index f70d8cc..b0106be 100644 --- a/lib/src/data.dart +++ b/lib/src/data.dart @@ -93,7 +93,7 @@ class MimeType { /// Note that this can resolve aliases like `JSON`. /// /// [defaultMimeType] if [mimeType] is invalid. - static String/*?*/ parseAsString(String/*?*/ mimeType, [String/*?*/ defaultMimeType]) { + static String? parseAsString(String? mimeType, [String? defaultMimeType]) { var m = MimeType.parse(mimeType, defaultMimeType); return m != null ? m.toString() : null; } @@ -101,10 +101,10 @@ class MimeType { /// Constructor that parses a [mimeType] string. /// /// [defaultMimeType] if [mimeType] is invalid. - static MimeType/*?*/ parse(String/*?*/ mimeType, [String/*?*/ defaultMimeType]) { + static MimeType? parse(String? mimeType, [String? defaultMimeType]) { mimeType ??= defaultMimeType; - if (mimeType == null) return null; /*!!!*/ + if (mimeType == null) return null; /*!!!*/ mimeType = mimeType.trim(); if (mimeType.isEmpty) mimeType = defaultMimeType; if (mimeType == null) return null; @@ -117,7 +117,7 @@ class MimeType { mimeType = parts[0]; - var charset = (parts.length == 2 ? parts[1] : '').trim(); + String? charset = (parts.length == 2 ? parts[1] : '').trim(); charset = normalizeCharset(charset); if (mimeType == 'json' || mimeType.endsWith('/json')) { @@ -210,9 +210,10 @@ class MimeType { /// Creates an instance by file [extension]. /// /// [defaultAsApplication] if true returns 'application/[extension]'. - static MimeType/*?*/ byExtension(String extension, + static MimeType? byExtension(String? extension, {bool defaultAsApplication = true}) { if (extension == null) return null; + var idx = extension.lastIndexOf('.'); if (idx >= 0) { extension = extension.substring(idx + 1); @@ -262,7 +263,7 @@ class MimeType { return MimeType.parse(SVG); default: { - if (defaultAsApplication ?? true) { + if (defaultAsApplication) { return MimeType.parse('application/$extension'); } return null; @@ -270,7 +271,7 @@ class MimeType { } } - static String/*?*/ normalizeCharset(String/*?*/ charset) { + static String? normalizeCharset(String? charset) { if (charset == null) return null; charset = charset.trim(); if (charset.isEmpty) return null; @@ -280,17 +281,17 @@ class MimeType { return charset; } - final String/*!*/ type; + final String type; - final String/*!*/ subType; + final String subType; - final String/*?*/ charset; + final String? charset; - MimeType(this.type, this.subType, [String charSet]) + MimeType(this.type, this.subType, [String? charSet]) : charset = charSet != null ? charSet.trim() : null; /// Returns [true] if [charset] is defined. - bool get hasCharset => charset != null && charset.isNotEmpty; + bool get hasCharset => charset != null && charset!.isNotEmpty; /// Returns [true] if [charset] is UTF-8. bool get isCharsetUTF8 => charset == 'utf8' || charset == 'utf-8'; @@ -315,7 +316,7 @@ class MimeType { bool get isAudio => type == 'audio'; /// Returns the HTML tag name for this MIME-Type. - String get htmlTag { + String? get htmlTag { if (isImage) { return 'img'; } else if (isVideo) { @@ -390,13 +391,13 @@ class MimeType { } /// Generates a file name for the type, using [timeMillis] as name and the corresponding [fileExtension]. - String fileNameTimeMillis([int timeMillis]) { + String fileNameTimeMillis([int? timeMillis]) { timeMillis ??= DateTime.now().millisecondsSinceEpoch; return fileName(timeMillis.toString()); } /// Generates a file name for the type, using [identifier] as name and the corresponding [fileExtension]. - String fileName([String identifier, String delimiter = '-']) { + String fileName([String? identifier, String delimiter = '-']) { if (identifier != null) identifier = identifier.trim(); if (identifier != null && identifier.isNotEmpty) { @@ -404,8 +405,7 @@ class MimeType { } if (identifier != null && identifier.isNotEmpty) { - if (delimiter != null) delimiter = delimiter.trim(); - delimiter ??= '-'; + delimiter = delimiter.trim(); return '$type$delimiter$identifier.$fileExtension'; } else { @@ -428,7 +428,7 @@ class MimeType { String get fullType => '$type/$subType'; @override - String toString([bool withCharset]) { + String toString([bool? withCharset]) { if (hasCharset && (withCharset ?? true)) { return '$fullType; charset=$charset'; } else { @@ -437,7 +437,7 @@ class MimeType { } /// Parses a [mimeType] to a MIME-Type string. - static String asString(dynamic mimeType, [String defaultMimeType]) { + static String? asString(dynamic mimeType, [String? defaultMimeType]) { if (mimeType == null) return defaultMimeType; if (mimeType is String) { @@ -466,7 +466,7 @@ class Base64 { /// Represent a Data URL in Base-64 class DataURLBase64 { /// Parses the Data URL to a Base-64 string. - static String parsePayloadAsBase64(String dataURL) { + static String? parsePayloadAsBase64(String? dataURL) { if (dataURL == null || dataURL.length < 5 || !dataURL.startsWith('data:')) { return null; } @@ -475,13 +475,13 @@ class DataURLBase64 { } /// Parses the Data URL to am array buffer. - static Uint8List parsePayloadAsArrayBuffer(String dataURL) { + static Uint8List? parsePayloadAsArrayBuffer(String dataURL) { var payload = parsePayloadAsBase64(dataURL); return payload != null ? base64.decode(payload) : null; } /// Parses the Data URL to decoded string. - static String parsePayloadAsString(String dataURL) { + static String? parsePayloadAsString(String dataURL) { var data = parsePayloadAsArrayBuffer(dataURL); return data != null ? latin1.decode(data) : null; } @@ -492,7 +492,7 @@ class DataURLBase64 { } /// The MIME-Type of parsed Data URL. - final MimeType mimeType; + final MimeType? mimeType; /// Returns [mimeType] as [String]. Returns '' if null. String get mimeTypeAsString => mimeType != null ? mimeType.toString() : ''; @@ -500,36 +500,36 @@ class DataURLBase64 { /// The Base-64 paylod/content of the parsed Data URL. final String payloadBase64; - String _payload; + String? _payload; /// The decoded payload as [String]. - String get payload { + String? get payload { _payload ??= Base64.decode(payloadBase64); return _payload; } - Uint8List _payloadArrayBuffer; + Uint8List? _payloadArrayBuffer; /// The decoded payload as array buffer. - Uint8List get payloadArrayBuffer { + Uint8List? get payloadArrayBuffer { _payloadArrayBuffer ??= Base64.decodeAsArrayBuffer(payloadBase64); return _payloadArrayBuffer; } - DataURLBase64(this.payloadBase64, [String mimeType]) + DataURLBase64(this.payloadBase64, [String? mimeType]) : mimeType = MimeType.parse(mimeType); /// Parses only the [MimeType] of the Data URL [s]. /// /// [defaultMimeType] if [s] is invalid. - static MimeType parseMimeType(String s, {String defaultMimeType}) { + static MimeType? parseMimeType(String s, {String? defaultMimeType}) { return MimeType.parse( parseMimeTypeAsString(s, defaultMimeType: defaultMimeType), defaultMimeType); } /// Parses only the MIME-Type of the Data URL [s] as string. - static String parseMimeTypeAsString(String s, {String defaultMimeType}) { + static String? parseMimeTypeAsString(String? s, {String? defaultMimeType}) { if (s == null) return defaultMimeType; s = s.trim(); if (s.isEmpty) return defaultMimeType; @@ -548,7 +548,7 @@ class DataURLBase64 { /// Constructor that parses a Data URL [s] /// /// [defaultMimeType] if [s] is invalid. - static DataURLBase64/*?*/ parse(String/*?*/ s, {String/*?*/ defaultMimeType}) { + static DataURLBase64? parse(String? s, {String? defaultMimeType}) { if (s == null) return null; s = s.trim(); if (s.isEmpty) return null; @@ -558,7 +558,7 @@ class DataURLBase64 { var idx = s.indexOf(';'); if (idx < 5) return null; - var mimeType = s.substring(5, idx); + String? mimeType = s.substring(5, idx); var idx2 = s.indexOf(','); if (idx2 < idx + 1) return null; @@ -574,20 +574,20 @@ class DataURLBase64 { return DataURLBase64(payload, mimeType); } - String _dataURLString; + String? _dataURLString; /// Returns a Data URL string. /// /// Example: `data:text/plain;base64,SGVsbG8=` /// that encodes `Hello` with MIME-Type `text/plain`. - String asDataURLString() { + String? asDataURLString() { _dataURLString ??= 'data:$mimeTypeAsString;base64,$payloadBase64'; return _dataURLString; } @override String toString() { - return asDataURLString(); + return asDataURLString()!; } } @@ -604,8 +604,8 @@ class Geolocation { static final RegExp GEOLOCATION_FORMAT = RegExp(r'([-=]?)(\d+[,.]?\d*)\s*[°o]?\s*(\w)'); - static num/*?*/ parseLatitudeOrLongitudeValue(String/*?*/ s, - [bool/*!*/ onlyWithCardinals = false]) { + static num? parseLatitudeOrLongitudeValue(String? s, + [bool onlyWithCardinals = false]) { if (s == null) return null; var match = GEOLOCATION_FORMAT.firstMatch(s); @@ -649,20 +649,17 @@ class Geolocation { return formatLatitude(geo.x) + ' ' + formatLongitude(geo.y); } - num/*!*/ _latitude; + final num _latitude; - num/*!*/ _longitude; + final num _longitude; - Geolocation(this._latitude, this._longitude) { - if (_latitude == null || _longitude == null) { - throw ArgumentError('Invalid coords: $_latitude $longitude'); - } - } + Geolocation(this._latitude, this._longitude); - static Geolocation/*?*/ fromCoords(String/*?*/ coords, [bool onlyWithCardinals = false]) { - if (coords == null) return null ; + static Geolocation? fromCoords(String? coords, + [bool onlyWithCardinals = false]) { + if (coords == null) return null; coords = coords.trim(); - if (coords.isEmpty) return null ; + if (coords.isEmpty) return null; var parts = coords.split(RegExp(r'\s+')); if (parts.length < 2) return null; @@ -698,14 +695,13 @@ class Geolocation { } /// Generates a Google Maps Directions URL with coordinates. - Future googleMapsDirectionsURL(Geolocation currentGeo) async { - if (currentGeo == null) return null; - return 'https://www.google.com/maps/dir/?api=1&origin=${currentGeo.latitude},${currentGeo.longitude}&destination=$_latitude,$longitude'; + String googleMapsDirectionsURL(Geolocation destinationGeo) { + return 'https://www.google.com/maps/dir/?api=1&origin=$_latitude,$longitude&destination=${destinationGeo.latitude},${destinationGeo.longitude}'; } } /// Parses [value] as a [Rectangle]. -Rectangle/*?*/ parseRectangle(dynamic value) { +Rectangle? parseRectangle(dynamic value) { if (value is List) return parseRectangleFromList(value); if (value is Map) return parseRectangleFromMap(value); if (value is String) return parseRectangleFromString(value); @@ -713,7 +709,7 @@ Rectangle/*?*/ parseRectangle(dynamic value) { } /// Parses [list] as a [Rectangle]. -Rectangle/*?*/ parseRectangleFromList(List list) { +Rectangle? parseRectangleFromList(List list) { if (list.length < 4) return null; list = list.map((e) => parseNum(e)).whereType().toList(); if (list.length < 4) return null; @@ -721,7 +717,7 @@ Rectangle/*?*/ parseRectangleFromList(List list) { } /// Parses [map] as a [Rectangle]. -Rectangle/*?*/ parseRectangleFromMap(Map map) { +Rectangle? parseRectangleFromMap(Map? map) { if (map == null || map.isEmpty) return null; var x = parseNum(findKeyValue(map, ['x', 'left'], true)); @@ -735,7 +731,7 @@ Rectangle/*?*/ parseRectangleFromMap(Map map) { } /// Parses [s] as a [Rectangle]. -Rectangle/*?*/ parseRectangleFromString(String s) { +Rectangle? parseRectangleFromString(String? s) { if (s == null) return null; s = s.trim(); if (s.isEmpty) return null; @@ -750,7 +746,7 @@ Rectangle/*?*/ parseRectangleFromString(String s) { } /// Parses [value] as a [Point]. -Point/*?*/ parsePoint(dynamic value) { +Point? parsePoint(dynamic value) { if (value is List) return parsePointFromList(value); if (value is Map) return parsePointFromMap(value); if (value is String) return parsePointFromString(value); @@ -758,15 +754,15 @@ Point/*?*/ parsePoint(dynamic value) { } /// Parses [list] as a [Point]. -Point/*?*/ parsePointFromList(List list) { +Point? parsePointFromList(List? list) { if (list == null || list.length < 2) return null; var x = parseNum(list[0]); var y = parseNum(list[1]); - return x != null && y != null ? Point(x, y) : null ; + return x != null && y != null ? Point(x, y) : null; } /// Parses [map] as a [Point]. -Point/*?*/ parsePointFromMap(Map map) { +Point? parsePointFromMap(Map map) { var x = parseNum(findKeyValue(map, ['x', 'left'], true)); var y = parseNum(findKeyValue(map, ['y', 'top'], true)); if (x == null || y == null) return null; @@ -774,7 +770,7 @@ Point/*?*/ parsePointFromMap(Map map) { } /// Parses [s] as a [Point]. -Point/*?*/ parsePointFromString(String/*?*/ s) { +Point? parsePointFromString(String? s) { if (s == null) return null; s = s.trim(); if (s.isEmpty) return null; @@ -796,7 +792,7 @@ Point/*?*/ parsePointFromString(String/*?*/ s) { /// /// [binaryBase] Default [false]. If [true] uses a binary base, if false uses /// decimal base. -String/*?*/ dataSizeFormat(int/*?*/ size, {bool/*?*/ decimalBase, bool/*?*/ binaryBase}) { +String? dataSizeFormat(int? size, {bool? decimalBase, bool? binaryBase}) { if (size == null) return null; var baseDecimal; @@ -824,9 +820,9 @@ String/*?*/ dataSizeFormat(int/*?*/ size, {bool/*?*/ decimalBase, bool/*?*/ bina var s = '${size ~/ 1000} KB'; return s; } else if (size < 1000 * 1000 * 1000) { - return formatDecimal(size / (1000 * 1000)) + ' MB'; + return formatDecimal(size / (1000 * 1000))! + ' MB'; } else { - return formatDecimal(size / (1000 * 1000 * 1000)) + ' GB'; + return formatDecimal(size / (1000 * 1000 * 1000))! + ' GB'; } } else { if (size < 1024) { @@ -835,9 +831,9 @@ String/*?*/ dataSizeFormat(int/*?*/ size, {bool/*?*/ decimalBase, bool/*?*/ bina var s = '${size ~/ 1024} KiB'; return s; } else if (size < 1024 * 1024 * 1024) { - return formatDecimal(size / (1024 * 1024)) + ' MiB'; + return formatDecimal(size / (1024 * 1024))! + ' MiB'; } else { - return formatDecimal(size / (1024 * 1024 * 1024)) + ' GiB'; + return formatDecimal(size / (1024 * 1024 * 1024))! + ' GiB'; } } } diff --git a/lib/src/date.dart b/lib/src/date.dart index 29ceb6d..bfceed6 100644 --- a/lib/src/date.dart +++ b/lib/src/date.dart @@ -32,43 +32,39 @@ void _initializeDateFormatting() { } String dateFormat_YYYY_MM_dd_HH_mm_ss( - [int time, - String /*!*/ delimiter = '-', - String /*!*/ hourDelimiter = ':']) { + [int? time, String delimiter = '-', String hourDelimiter = ':']) { return _dateFormat( 'yyyy${delimiter}MM${delimiter}dd HH${hourDelimiter}mm${hourDelimiter}ss', time); } String dateFormat_YYYY_MM_dd_HH_mm( - [int time, - String /*!*/ delimiter = '-', - String /*!*/ hourDelimiter = ':']) { + [int? time, String delimiter = '-', String hourDelimiter = ':']) { return _dateFormat( 'yyyy${delimiter}MM${delimiter}dd HH${hourDelimiter}mm', time); } -String dateFormat_YYYY_MM_dd_HH([int time, String /*!*/ delimiter = '-']) { +String dateFormat_YYYY_MM_dd_HH([int? time, String delimiter = '-']) { return _dateFormat('yyyy${delimiter}MM-dd HH', time); } -String dateFormat_YYYY_MM_dd([int time, String /*!*/ delimiter = '-']) { +String dateFormat_YYYY_MM_dd([int? time, String delimiter = '-']) { return _dateFormat('yyyy${delimiter}MM${delimiter}dd', time); } -String dateFormat_YY_MM_dd([int time, String /*!*/ delimiter = '-']) { +String dateFormat_YY_MM_dd([int? time, String delimiter = '-']) { return _dateFormat('yy${delimiter}MM${delimiter}dd', time); } -String dateFormat_YY_MM([int time, String /*!*/ delimiter = '-']) { +String dateFormat_YY_MM([int? time, String delimiter = '-']) { return _dateFormat('yy${delimiter}MM', time); } -String dateFormat_YYYY_MM([int time, String /*!*/ delimiter = '-']) { +String dateFormat_YYYY_MM([int? time, String delimiter = '-']) { return _dateFormat('yyyy${delimiter}MM', time); } -String _dateFormat(String format, [int time]) { +String _dateFormat(String format, [int? time]) { time ??= getCurrentTimeMillis(); _initializeDateFormatting(); @@ -81,7 +77,7 @@ String _dateFormat(String format, [int time]) { /// Parses [date] as [DateTime]. /// /// Can be a [num] (Milliseconds since Epoch). -DateTime parseDateTime(dynamic /*?*/ date, [DateTime /*?*/ def]) { +DateTime? parseDateTime(dynamic /*?*/ date, [DateTime? def]) { if (date == null) return def; if (date is DateTime) { @@ -108,17 +104,19 @@ DateTime parseDateTime(dynamic /*?*/ date, [DateTime /*?*/ def]) { } /// Converts [o] to a [List]. -List/*?*/ parseDateTimeFromInlineList(dynamic /*?*/ o, - [Pattern /*!*/ delimiter = ',', List /*?*/ def]) { +List? parseDateTimeFromInlineList(dynamic /*?*/ o, + [Pattern delimiter = ',', List? def]) { if (o == null) return def; if (o is DateTime) return [o]; - if (o is List) return o.map((e) => parseDateTime(e)).toList(); - return parseFromInlineList(o.toString(), delimiter, parseDateTime, def); + if (o is List) { + return o.map((e) => parseDateTime(e)).toList() as List?; + } + return parseFromInlineList(o.toString(), delimiter, + parseDateTime as DateTime Function(String)?, def); } /// Parses [unit] and [amount] to [Duration]. -Duration/*?*/ parseDuration(String /*?*/ unit, - [int amount = 0, Duration /*?*/ def]) { +Duration? parseDuration(String? unit, [int amount = 0, Duration? def]) { if (unit == null) return def; unit = unit.toLowerCase().trim(); if (unit.isEmpty) return def; @@ -191,12 +189,12 @@ enum Unit { Years, } -Unit getUnitByIndex(int /*?*/ index, [Unit /*?*/ def]) { +Unit? getUnitByIndex(int? index, [Unit? def]) { if (index == null || index < 0 || index >= Unit.values.length) return def; return Unit.values[index]; } -Unit getUnitByName(String /*?*/ name, [Unit /*?*/ def]) { +Unit? getUnitByName(String? name, [Unit? def]) { if (name == null) return def; name = name.toLowerCase().trim(); if (name.isEmpty) return def; @@ -267,7 +265,7 @@ Unit getUnitByName(String /*?*/ name, [Unit /*?*/ def]) { } } -Unit parseUnit(dynamic /*?*/ unit, [Unit /*?*/ def]) { +Unit? parseUnit(dynamic /*?*/ unit, [Unit? def]) { if (unit == null) { return def; } else if (unit is Unit) { @@ -281,7 +279,7 @@ Unit parseUnit(dynamic /*?*/ unit, [Unit /*?*/ def]) { } } -int _getUnitMilliseconds(dynamic /*?*/ unit) { +int? _getUnitMilliseconds(dynamic /*?*/ unit) { if (unit == null) return null; var unitParsed = parseUnit(unit); @@ -310,13 +308,12 @@ int _getUnitMilliseconds(dynamic /*?*/ unit) { } } -int getUnitAsMilliseconds(dynamic unit, [int /*!*/ amount = 1]) { - var ms = _getUnitMilliseconds(unit); +int getUnitAsMilliseconds(dynamic unit, [int amount = 1]) { + var ms = _getUnitMilliseconds(unit)!; return ms * amount; } -double getMillisecondsAsUnit(int /*?*/ ms, dynamic /*?*/ unit, - [double /*?*/ def]) { +double? getMillisecondsAsUnit(int? ms, dynamic /*?*/ unit, [double? def]) { if (ms == null) return def; if (ms == 0) return 0; @@ -325,13 +322,13 @@ double getMillisecondsAsUnit(int /*?*/ ms, dynamic /*?*/ unit, var unitParsed = parseUnit(unit); if (unitParsed == null) return def; - var unitMs = _getUnitMilliseconds(unitParsed); + var unitMs = _getUnitMilliseconds(unitParsed)!; var res = ms / unitMs; return res; } -String getDateAmPm([int /*?*/ time]) { +String getDateAmPm([int? time]) { time ??= getCurrentTimeMillis(); _initializeDateFormatting(); @@ -342,7 +339,7 @@ String getDateAmPm([int /*?*/ time]) { return s.contains('PM') ? 'PM' : 'AM'; } -int getDateHour([int /*?*/ time]) { +int getDateHour([int? time]) { time ??= getCurrentTimeMillis(); _initializeDateFormatting(); @@ -361,7 +358,7 @@ const int ONE_HOUR = ONE_MINUTE * 60; const int ONE_DAY = ONE_HOUR * 24; -String formatTimeMillis(int time) { +String formatTimeMillis(int? time) { if (time == null || time == 0) return '0'; var sig = ''; @@ -413,7 +410,7 @@ enum DateTimeWeekDay { } /// Gets index of DateTimeWeekDay, starting from 1 (Monday) to 7 (Sunday), same range as [ DateTime.wednesday ]. -int getDateTimeWeekDayIndex(DateTimeWeekDay /*?*/ weekDay) { +int? getDateTimeWeekDayIndex(DateTimeWeekDay? weekDay) { if (weekDay == null) return null; switch (weekDay) { @@ -437,7 +434,7 @@ int getDateTimeWeekDayIndex(DateTimeWeekDay /*?*/ weekDay) { } /// Returns enum [DateTimeWeekDay] by [weekDayIndex] (from 1 to 7). See [getDateTimeWeekDayIndex]. -DateTimeWeekDay getDateTimeWeekDay(int /*?*/ weekDayIndex) { +DateTimeWeekDay? getDateTimeWeekDay(int? weekDayIndex) { if (weekDayIndex == null) return null; switch (weekDayIndex) { @@ -464,7 +461,7 @@ DateTimeWeekDay getDateTimeWeekDay(int /*?*/ weekDayIndex) { /// Returns enum [DateTimeWeekDay] using [weekDayIndex] compliant with ISO 8601. /// /// [weekDayIndex] From 0 (Monday) to 6 (Sunday). -DateTimeWeekDay getDateTimeWeekDay_from_ISO_8601_index(int /*?*/ weekDayIndex) { +DateTimeWeekDay? getDateTimeWeekDay_from_ISO_8601_index(int? weekDayIndex) { if (weekDayIndex == null) return null; switch (weekDayIndex) { @@ -489,7 +486,7 @@ DateTimeWeekDay getDateTimeWeekDay_from_ISO_8601_index(int /*?*/ weekDayIndex) { } /// Returns enum [DateTimeWeekDay] by week day name in english -DateTimeWeekDay getDateTimeWeekDayByName(String /*?*/ weekDayName) { +DateTimeWeekDay? getDateTimeWeekDayByName(String? weekDayName) { if (weekDayName == null) return null; weekDayName = weekDayName.toLowerCase().trim(); if (weekDayName.isEmpty) return null; @@ -522,7 +519,7 @@ DateTime getDateTimeNow() { /// Returns the start of the day for [time]. /// /// [time] if null uses [ DateTime.now ]. -DateTime getDateTimeDayStart([DateTime /*?*/ time]) { +DateTime getDateTimeDayStart([DateTime? time]) { time ??= DateTime.now(); return DateTime(time.year, time.month, time.day, 0, 0, 0, 0, 0); } @@ -530,7 +527,7 @@ DateTime getDateTimeDayStart([DateTime /*?*/ time]) { /// Returns the end of the day for [time]. /// /// [time] if null uses [ DateTime.now ]. -DateTime getDateTimeDayEnd([DateTime /*?*/ time]) { +DateTime getDateTimeDayEnd([DateTime? time]) { time ??= DateTime.now(); return DateTime(time.year, time.month, time.day, 23, 59, 59, 999, 0); } @@ -538,7 +535,7 @@ DateTime getDateTimeDayEnd([DateTime /*?*/ time]) { /// Returns the start of yesterday from [time]. /// /// [time] if null uses [ DateTime.now ]. -DateTime getDateTimeYesterday([DateTime /*?*/ time]) { +DateTime getDateTimeYesterday([DateTime? time]) { time ??= DateTime.now(); return getDateTimeDayStart(time.subtract(Duration(days: 1))); } @@ -546,7 +543,7 @@ DateTime getDateTimeYesterday([DateTime /*?*/ time]) { /// Returns start and end of last [nDays] counting from [time]. /// /// [time] if null uses [ DateTime.now ]. -Pair getDateTimeLastNDays(int /*!*/ nDays, [DateTime /*?*/ time]) { +Pair getDateTimeLastNDays(int nDays, [DateTime? time]) { time ??= DateTime.now(); return Pair(getDateTimeDayStart(time.subtract(Duration(days: nDays))), getDateTimeDayEnd(time)); @@ -556,7 +553,7 @@ Pair getDateTimeLastNDays(int /*!*/ nDays, [DateTime /*?*/ time]) { /// /// [time] if null uses [ DateTime.now ]. Pair getDateTimeThisWeek( - [DateTimeWeekDay /*?*/ weekFirstDay, DateTime /*?*/ now]) { + [DateTimeWeekDay? weekFirstDay, DateTime? now]) { now ??= DateTime.now(); var weekStart = getDateTimeWeekStart(weekFirstDay, now); @@ -570,7 +567,7 @@ Pair getDateTimeThisWeek( /// [weekFirstDay] the desired first day of week for computation behavior. /// [time] if null uses [ DateTime.now ]. Pair getDateTimeLastWeek( - [DateTimeWeekDay /*?*/ weekFirstDay, DateTime /*?*/ time]) { + [DateTimeWeekDay? weekFirstDay, DateTime? time]) { time ??= DateTime.now(); var weekStart = @@ -583,7 +580,7 @@ Pair getDateTimeLastWeek( /// Returns start and end of this month, using [time] as reference. /// /// [time] if null uses [ DateTime.now ]. -Pair getDateTimeThisMonth([DateTime /*?*/ time]) { +Pair getDateTimeThisMonth([DateTime? time]) { time ??= DateTime.now(); var y = time.year; @@ -597,7 +594,7 @@ Pair getDateTimeThisMonth([DateTime /*?*/ time]) { /// Returns start and end of last month, before current month, using [time] as reference. /// /// [time] if null uses [ DateTime.now ]. -Pair getDateTimeLastMonth([DateTime /*?*/ time]) { +Pair getDateTimeLastMonth([DateTime? time]) { time ??= DateTime.now(); var prevMonth = getDateTimePreviousMonth(time.month, year: time.year); @@ -615,7 +612,7 @@ Pair getDateTimeLastMonth([DateTime /*?*/ time]) { /// /// [month] from 1 to 12. /// [year] if null uses year from [ DateTime.now ]. -DateTime getDateTimePreviousMonth(int month, {int /*?*/ year}) { +DateTime getDateTimePreviousMonth(int month, {int? year}) { year ??= DateTime.now().year; var cursor = DateTime(year, month, 1, 0, 0, 0, 0, 0); var prev = cursor.subtract(Duration(days: 1)); @@ -626,7 +623,7 @@ DateTime getDateTimePreviousMonth(int month, {int /*?*/ year}) { /// /// [month] from 1 to 12. /// [year] if null uses year from [ DateTime.now ]. -int getLastDayOfMonth(int month, {int /*?*/ year}) { +int getLastDayOfMonth(int month, {int? year}) { year ??= DateTime.now().year; var cursor = DateTime(year, month, 28, 12, 0, 0); @@ -644,14 +641,13 @@ int getLastDayOfMonth(int month, {int /*?*/ year}) { /// /// [weekFirstDay] the desired first day of week for computation behavior. /// [time] if null uses [ DateTime.now ]. -DateTime getDateTimeWeekStart( - [DateTimeWeekDay /*?*/ weekFirstDay, DateTime /*?*/ time]) { +DateTime getDateTimeWeekStart([DateTimeWeekDay? weekFirstDay, DateTime? time]) { weekFirstDay ??= DateTimeWeekDay.Monday; time ??= DateTime.now(); var weekFirstDayIndex = getDateTimeWeekDayIndex(weekFirstDay); - while (time.weekday != weekFirstDayIndex) { + while (time!.weekday != weekFirstDayIndex) { time = time.subtract(Duration(days: 1)); } @@ -662,8 +658,7 @@ DateTime getDateTimeWeekStart( /// /// [weekFirstDay] the desired first day of week for computation behavior. /// [time] if null uses [ DateTime.now ]. -DateTime getDateTimeWeekEnd( - [DateTimeWeekDay /*?*/ weekFirstDay, DateTime /*?*/ now]) { +DateTime getDateTimeWeekEnd([DateTimeWeekDay? weekFirstDay, DateTime? now]) { weekFirstDay ??= DateTimeWeekDay.Monday; now ??= DateTime.now(); @@ -711,8 +706,8 @@ enum DateRangeType { /// /// [weekFirstDay] the desired first day of week for computation behavior. /// [time] if null uses [ DateTime.now ]. -Pair /*!*/ getDateTimeRange(DateRangeType /*!*/ rangeType, - [DateTime /*?*/ time, DateTimeWeekDay /*?*/ weekFirstDay]) { +Pair getDateTimeRange(DateRangeType rangeType, + [DateTime? time, DateTimeWeekDay? weekFirstDay]) { time ??= getDateTimeNow(); var nowStart = getDateTimeDayStart(time); @@ -753,8 +748,8 @@ Pair /*!*/ getDateTimeRange(DateRangeType /*!*/ rangeType, /// /// [weekFirstDay] the desired first day of week for computation behavior. /// [locale] Locale code to use if [weekFirstDay] is null and need to be defined. -DateTime getDateTimeStartOf(DateTime time, dynamic unit, - {DateTimeWeekDay /*?*/ weekFirstDay, String /*?*/ locale}) { +DateTime? getDateTimeStartOf(DateTime time, dynamic unit, + {DateTimeWeekDay? weekFirstDay, String? locale}) { var unitParsed = parseUnit(unit); if (unitParsed == null) return null; @@ -796,8 +791,8 @@ DateTime getDateTimeStartOf(DateTime time, dynamic unit, /// /// [weekFirstDay] the desired first day of week for computation behavior. /// [locale] Locale code to use if [weekFirstDay] is null and need to be defined. -DateTime getDateTimeEndOf(DateTime time, dynamic unit, - {DateTimeWeekDay /*?*/ weekFirstDay, String /*?*/ locale}) { +DateTime? getDateTimeEndOf(DateTime time, dynamic unit, + {DateTimeWeekDay? weekFirstDay, String? locale}) { var unitParsed = parseUnit(unit); if (unitParsed == null) return null; @@ -830,7 +825,7 @@ DateTime getDateTimeEndOf(DateTime time, dynamic unit, } if ('$unit'.toLowerCase().trim() == 'date') { - var startOf = getDateTimeStartOf(time, unit) /*!*/; + var startOf = getDateTimeStartOf(time, unit)!; return startOf .add(Duration(hours: 23, minutes: 59, seconds: 59, milliseconds: 999)); } @@ -841,21 +836,19 @@ DateTime getDateTimeEndOf(DateTime time, dynamic unit, /// Returns the first day of a week as enum [DateTimeWeekDay] for [locale]. /// /// [locale] if null uses system default. -DateTimeWeekDay getWeekFirstDay([String /*?*/ locale]) { +DateTimeWeekDay getWeekFirstDay([String? locale]) { var dateSymbols = _getLocaleDateSymbols(locale); - if (dateSymbols == null) return DateTimeWeekDay.Monday; var firstdayofweek = dateSymbols.FIRSTDAYOFWEEK; - var dateTimeWeekDay = - getDateTimeWeekDay_from_ISO_8601_index(firstdayofweek) /*!*/; + var dateTimeWeekDay = getDateTimeWeekDay_from_ISO_8601_index(firstdayofweek)!; return dateTimeWeekDay; } -DateSymbols /*!*/ _getLocaleDateSymbols([String /*?*/ locale]) { +DateSymbols _getLocaleDateSymbols([String? locale]) { locale ??= Intl.defaultLocale ?? 'en_ISO'; var language = locale.split('_')[0]; var map = dateTimeSymbolMap(); - DateSymbols dateSymbols = map[locale]; + DateSymbols? dateSymbols = map[locale]; dateSymbols ??= map[language]; if (dateSymbols != null) return dateSymbols; @@ -866,5 +859,5 @@ DateSymbols /*!*/ _getLocaleDateSymbols([String /*?*/ locale]) { } } - return map['en_ISO'] /*!*/; + return map['en_ISO']!; } diff --git a/lib/src/events.dart b/lib/src/events.dart index 0f35c31..11522d0 100644 --- a/lib/src/events.dart +++ b/lib/src/events.dart @@ -5,7 +5,7 @@ import 'package:swiss_knife/src/collections.dart'; class _ListenSignature { final dynamic /*!*/ _identifier; - final bool /*!*/ _identifyByInstance; + final bool _identifyByInstance; final bool _cancelOnError; @@ -30,12 +30,11 @@ class _ListenSignature { @override int get hashCode => _identifier.hashCode; - /*late final*/ - StreamSubscription /*?*/ subscription; + late StreamSubscription? subscription; bool _canceled = false; - bool get isCanceled => _canceled != null && _canceled; + bool get isCanceled => _canceled; void cancel() { _cancel(true); @@ -47,7 +46,7 @@ class _ListenSignature { if (subscription != null) { if (cancelSubscription) { try { - subscription.cancel(); + subscription!.cancel(); } catch (e, s) { print(e); print(s); @@ -65,65 +64,63 @@ typedef EventValidatorFunction = bool Function( /// /// See [Stream] for more documentation of delegated methods. class EventStream implements Stream { - final StreamController /*!*/ _controller = StreamController(); + final StreamController _controller = StreamController(); - /*late final*/ - Stream /*!*/ _s; + late final Stream _s; EventStream() { _s = _controller.stream.asBroadcastStream(); } - bool /*!*/ _used = false; + bool _used = false; - bool /*!*/ get isUsed => _used; + bool get isUsed => _used; void _markUsed() => _used = true; - Stream /*!*/ get _stream { + Stream get _stream { _markUsed(); return _s; } /// Adds an event and notify it to listeners. - void add(T /*!*/ value) { + void add(T value) { if (!_used) return; _controller.add(value); } /// Adds an error event and notify it to listeners. - void addError(Object /*!*/ error, [StackTrace /*?*/ stackTrace]) { + void addError(Object error, [StackTrace? stackTrace]) { if (!_used) return; _controller.addError(error, stackTrace); } - Future /*!*/ addStream(Stream /*!*/ source, {bool /*?*/ cancelOnError}) => + Future addStream(Stream source, {bool? cancelOnError}) => _controller.addStream(source, cancelOnError: cancelOnError); /// Closes this stream. - Future /*!*/ close() => _controller.close(); + Future close() => _controller.close(); /// Returns [true] if this stream is closed. - bool /*!*/ get isClosed => _controller.isClosed; + bool get isClosed => _controller.isClosed; /// Returns [true] if this stream is paused. - bool /*!*/ get isPaused => _controller.isPaused; + bool get isPaused => _controller.isPaused; @override - Future /*!*/ any(bool Function(T element) /*!*/ test) { + Future any(bool Function(T element) test) { return _stream.any(test); } @override Stream asBroadcastStream( - {void Function(StreamSubscription subscription) /*?*/ onListen, - void Function(StreamSubscription subscription) /*?*/ onCancel}) { + {void Function(StreamSubscription subscription)? onListen, + void Function(StreamSubscription subscription)? onCancel}) { return _stream.asBroadcastStream(onListen: onListen, onCancel: onCancel); } @override - Stream /*!*/ asyncExpand( - Stream /*?*/ Function(T event) /*!*/ convert) { + Stream asyncExpand(Stream? Function(T event) convert) { return _stream.asyncExpand(convert); } @@ -138,83 +135,80 @@ class EventStream implements Stream { } @override - Future contains(Object /*?*/ needle) { + Future contains(Object? needle) { return _stream.contains(needle); } @override - Stream distinct([bool Function(T previous, T next) /*?*/ equals]) { + Stream distinct([bool Function(T previous, T next)? equals]) { return _stream.distinct(equals); } @override - Future drain([E /*?*/ futureValue]) { + Future drain([E? futureValue]) { return _stream.drain(futureValue); } @override - Future elementAt(int /*!*/ updateMetadata) { + Future elementAt(int updateMetadata) { return _stream.elementAt(updateMetadata); } @override - Future every(bool Function(T element) /*!*/ test) { + Future every(bool Function(T element) test) { return _stream.every(test); } @override - Stream expand(Iterable Function(T element) /*!*/ convert) { + Stream expand(Iterable Function(T element) convert) { return _stream.expand(convert); } @override - Future /*!*/ get first => _stream.first; + Future get first => _stream.first; @override - Future firstWhere(bool Function(T element) /*!*/ test, - {T Function() /*?*/ orElse}) { + Future firstWhere(bool Function(T element) test, {T Function()? orElse}) { return _stream.firstWhere(test, orElse: orElse); } @override - Future fold( - S /*!*/ initialValue, S Function(S previous, T element) /*!*/ combine) { + Future fold(S initialValue, S Function(S previous, T element) combine) { return _stream.fold(initialValue, combine); } @override - Future forEach(void Function(T element) /*!*/ action) { + Future forEach(void Function(T element) action) { return _stream.forEach(action); } @override - Stream handleError(Function /*!*/ onError, - {bool Function(dynamic error) /*?*/ test}) { + Stream handleError(Function onError, + {bool Function(dynamic error)? test}) { return _stream.handleError(onError, test: test); } @override - bool /*!*/ get isBroadcast => _stream.isBroadcast; + bool get isBroadcast => _stream.isBroadcast; @override - Future /*!*/ get isEmpty => _stream.isEmpty; + Future get isEmpty => _stream.isEmpty; @override - Future /*!*/ join([String /*!*/ separator = '']) { + Future join([String separator = '']) { return _stream.join(separator); } @override - Future /*!*/ get last => _stream.last; + Future get last => _stream.last; @override - Future lastWhere(bool Function(T element) /*!*/ test, - {T Function() /*?*/ orElse}) { + Future lastWhere(bool Function(T element) test, {T Function()? orElse}) { return _stream.lastWhere(test, orElse: orElse); } @override - Future /*!*/ get length => _stream.length; + Future get length => _stream.length; final Set<_ListenSignature> _listenSignatures = {}; @@ -227,8 +221,8 @@ class EventStream implements Stream { } /// Cancels [StreamSubscription] associated with [singletonIdentifier]. - bool /*!*/ cancelSingletonSubscription(dynamic /*!*/ singletonIdentifier, - [bool /*!*/ singletonIdentifyByInstance = true]) { + bool cancelSingletonSubscription(dynamic /*!*/ singletonIdentifier, + [bool singletonIdentifyByInstance = true]) { var signature = _getListenSignature(singletonIdentifier, singletonIdentifyByInstance); @@ -241,15 +235,15 @@ class EventStream implements Stream { } /// Returns a [StreamSubscription] associated with [singletonIdentifier]. - StreamSubscription /*?*/ getSingletonSubscription( + StreamSubscription? getSingletonSubscription( dynamic /*!*/ singletonIdentifier, [bool singletonIdentifyByInstance = true]) { var signature = _getListenSignature(singletonIdentifier, singletonIdentifyByInstance); - return signature?.subscription; + return signature?.subscription as StreamSubscription?; } - _ListenSignature /*?*/ _getListenSignature(dynamic /*!*/ singletonIdentifier, + _ListenSignature? _getListenSignature(dynamic /*!*/ singletonIdentifier, [bool singletonIdentifyByInstance /*!*/ = true]) { var listenSignature = _ListenSignature( singletonIdentifier, singletonIdentifyByInstance, false); @@ -263,7 +257,7 @@ class EventStream implements Stream { return null; } - EventValidatorFunction /*?*/ eventValidator; + EventValidatorFunction? eventValidator; /// Listen for events. /// @@ -272,17 +266,17 @@ class EventStream implements Stream { /// [singletonIdentifier] identifier to avoid multiple listeners with the same identifier. This will register a singleton [StreamSubscription] associated with [singletonIdentifier]. /// [singletonIdentifyByInstance] if true uses `identical(...)` to compare the [singletonIdentifier]. @override - StreamSubscription /*?*/ listen(void Function(T event) /*!*/ onData, - {Function /*?*/ onError, - void Function() /*?*/ onDone, - bool /*!*/ cancelOnError = false, - dynamic /*?*/ singletonIdentifier, - bool /*!*/ singletonIdentifyByInstance = true, - EventValidatorFunction /*?*/ eventValidator}) { + StreamSubscription listen(void Function(T event)? onData, + {Function? onError, + void Function()? onDone, + bool? cancelOnError = false, + Object? singletonIdentifier, + bool singletonIdentifyByInstance = true, + EventValidatorFunction? eventValidator}) { try { eventValidator ??= this.eventValidator; - if (eventValidator != null) { + if (eventValidator != null && onData != null) { var eventValidatorOriginal = eventValidator; var onDataOriginal = onData; onData = (event) { @@ -294,11 +288,14 @@ class EventStream implements Stream { } if (singletonIdentifier != null) { - var listenSignature = _ListenSignature( - singletonIdentifier, singletonIdentifyByInstance, cancelOnError); + var listenSignature = _ListenSignature(singletonIdentifier, + singletonIdentifyByInstance, cancelOnError ?? false); + + var prevSubscription = + getSetEntryInstance(_listenSignatures, listenSignature); - if (_listenSignatures.contains(listenSignature)) { - return null; + if (prevSubscription != null) { + return prevSubscription.subscription! as StreamSubscription; } _listenSignatures.add(listenSignature); @@ -318,19 +315,17 @@ class EventStream implements Stream { return _stream.listen(onData, onError: onError, onDone: onDone, cancelOnError: cancelOnError); } - } catch (e, s) { - print(e); - print(s); - return null; + } catch (e) { + rethrow; } } - ListenerWrapper listenOneShot(void Function(T event) /*!*/ onData, - {Function /*?*/ onError, - void Function() /*?*/ onDone, - bool cancelOnError, + ListenerWrapper? listenOneShot(void Function(T event) onData, + {Function? onError, + void Function()? onDone, + required bool cancelOnError, dynamic singletonIdentifier, - bool singletonIdentifyByInstance = true}) { + bool? singletonIdentifyByInstance = true}) { var listenerWrapper = ListenerWrapper(this, onData, onError: onError, onDone: onDone, @@ -341,7 +336,7 @@ class EventStream implements Stream { } /// Returns a future that completes when receives at least 1 event. - Future /*!*/ listenAsFuture() { + Future listenAsFuture() { var completer = Completer(); listen((e) { if (!completer.isCompleted) { @@ -370,7 +365,7 @@ class EventStream implements Stream { Future get single => _stream.single; @override - Future singleWhere(bool Function(T element) test, {T Function() orElse}) { + Future singleWhere(bool Function(T element) test, {T Function()? orElse}) { return _stream.singleWhere(test, orElse: orElse); } @@ -396,7 +391,7 @@ class EventStream implements Stream { @override Stream timeout(Duration timeLimit, - {void Function(EventSink sink) onTimeout}) { + {void Function(EventSink sink)? onTimeout}) { return _stream.timeout(timeLimit, onTimeout: onTimeout); } @@ -425,30 +420,31 @@ class EventStream implements Stream { /// /// Useful to point to `EventStream` instances that are not instantiated yet. class EventStreamDelegator implements EventStream { - EventStream /*?*/ _eventStream; + EventStream? _eventStream; - final EventStream Function() /*?*/ _eventStreamProvider; + final EventStream Function()? _eventStreamProvider; - EventStreamDelegator(EventStream /*!*/ eventStream) + EventStreamDelegator(EventStream eventStream) : _eventStream = eventStream, _eventStreamProvider = null; - EventStreamDelegator.provider( - EventStream Function() /*!*/ eventStreamProvider) + EventStreamDelegator.provider(EventStream Function() eventStreamProvider) : _eventStream = null, _eventStreamProvider = eventStreamProvider; /// Returns the main [EventStream]. - EventStream /*!*/ get eventStream { + EventStream? get eventStream { if (_eventStream == null) { - _eventStream = _eventStreamProvider /*!*/ (); - flush(); + _eventStream = _eventStreamProvider!(); + if (_eventStream != null) { + flush(); + } } return _eventStream; } /// Sets the main [EventStream]. - set eventStream(EventStream /*!*/ value) { + set eventStream(EventStream? value) { if (_eventStream != value) { _eventStream = value; if (_eventStream != null) { @@ -459,7 +455,7 @@ class EventStreamDelegator implements EventStream { /// Flushes any event in buffer. void flush() { - _eventStream ??= _eventStreamProvider(); + _eventStream ??= _eventStreamProvider!(); var es = _eventStream; if (es == null) return; @@ -503,13 +499,13 @@ class EventStreamDelegator implements EventStream { } @override - StreamController _controller; + late StreamController _controller; @override - Stream _s; + late Stream _s; @override - bool _used; + late bool _used; @override _ListenSignature _getListenSignature(singletonIdentifier, @@ -529,7 +525,7 @@ class EventStreamDelegator implements EventStream { final List _addBuffer = []; @override - void add(T /*!*/ value) { + void add(T value) { var es = eventStream; if (es == null) { _addBuffer.add(value); @@ -541,7 +537,7 @@ class EventStreamDelegator implements EventStream { final List _addErrorBuffer = []; @override - void addError(Object error, [StackTrace /*?*/ stackTrace]) { + void addError(Object error, [StackTrace? stackTrace]) { var es = eventStream; if (es == null) { _addErrorBuffer.add([error, stackTrace]); @@ -553,13 +549,13 @@ class EventStreamDelegator implements EventStream { final List _listenBuffer = []; @override - StreamSubscription /*?*/ listen(void Function(T event) /*!*/ onData, - {Function onError, - void Function() onDone, - bool cancelOnError = false, + StreamSubscription listen(void Function(T event)? onData, + {Function? onError, + void Function()? onDone, + bool? cancelOnError = false, singletonIdentifier, bool singletonIdentifyByInstance = true, - EventValidatorFunction eventValidator}) { + EventValidatorFunction? eventValidator}) { var es = eventStream; if (es == null) { _listenBuffer.add([ @@ -571,7 +567,17 @@ class EventStreamDelegator implements EventStream { singletonIdentifyByInstance, eventValidator ]); - return null; + + return _StreamSubscriptionProvider(() { + var es2 = eventStream; + return es2?.listen(onData, + onError: onError, + onDone: onDone, + cancelOnError: cancelOnError, + singletonIdentifier: singletonIdentifier, + singletonIdentifyByInstance: singletonIdentifyByInstance, + eventValidator: eventValidator); + }); } else { return es.listen(onData, onError: onError, @@ -586,12 +592,12 @@ class EventStreamDelegator implements EventStream { final List _listenOneShotBuffer = []; @override - ListenerWrapper listenOneShot(void Function(T event) /*!*/ onData, - {Function onError, - void Function() onDone, - bool cancelOnError, + ListenerWrapper? listenOneShot(void Function(T event) onData, + {Function? onError, + void Function()? onDone, + bool? cancelOnError, singletonIdentifier, - bool singletonIdentifyByInstance = true}) { + bool? singletonIdentifyByInstance = true}) { var es = eventStream; if (es == null) { _listenOneShotBuffer.add([ @@ -607,186 +613,233 @@ class EventStreamDelegator implements EventStream { return es.listenOneShot(onData, onError: onError, onDone: onDone, - cancelOnError: cancelOnError, + cancelOnError: cancelOnError!, singletonIdentifier: singletonIdentifier, singletonIdentifyByInstance: singletonIdentifyByInstance); } } @override - Future addStream(Stream source, {bool cancelOnError}) => - eventStream?.addStream(source, cancelOnError: cancelOnError); + Future addStream(Stream source, {bool? cancelOnError}) => + eventStream!.addStream(source, cancelOnError: cancelOnError); @override - Future any(bool Function(T element) test) => eventStream?.any(test); + Future any(bool Function(T element) test) => eventStream!.any(test); @override Stream asBroadcastStream( - {void Function(StreamSubscription subscription) onListen, - void Function(StreamSubscription subscription) onCancel}) => - eventStream?.asBroadcastStream(onListen: onListen, onCancel: onCancel); + {void Function(StreamSubscription subscription)? onListen, + void Function(StreamSubscription subscription)? onCancel}) => + eventStream!.asBroadcastStream(onListen: onListen, onCancel: onCancel); @override - Stream asyncExpand(Stream Function(T event) convert) => - eventStream?.asyncExpand(convert); + Stream asyncExpand(Stream? Function(T event) convert) => + eventStream!.asyncExpand(convert); @override Stream asyncMap(FutureOr Function(T event) convert) => - eventStream?.asyncMap(convert); + eventStream!.asyncMap(convert); @override void cancelAllSingletonSubscriptions() => - eventStream?.cancelAllSingletonSubscriptions(); + eventStream!.cancelAllSingletonSubscriptions(); @override bool cancelSingletonSubscription(singletonIdentifier, [bool singletonIdentifyByInstance = true]) => - eventStream?.cancelSingletonSubscription( + eventStream!.cancelSingletonSubscription( singletonIdentifier, singletonIdentifyByInstance); @override - Stream cast() => eventStream?.cast(); + Stream cast() => eventStream!.cast(); @override - Future close() => eventStream?.close(); + Future close() => eventStream!.close(); @override - Future contains(Object needle) => eventStream?.contains(needle); + Future contains(Object? needle) => eventStream!.contains(needle); @override - Stream distinct([bool Function(T previous, T next) equals]) => - eventStream?.distinct(equals); + Stream distinct([bool Function(T previous, T next)? equals]) => + eventStream!.distinct(equals); @override - Future drain([E futureValue]) => eventStream?.drain(futureValue); + Future drain([E? futureValue]) => eventStream!.drain(futureValue); @override Future elementAt(int updateMetadata) => - eventStream?.elementAt(updateMetadata); + eventStream!.elementAt(updateMetadata); @override - Future every(bool Function(T element) test) => eventStream?.every(test); + Future every(bool Function(T element) test) => eventStream!.every(test); @override Stream expand(Iterable Function(T element) convert) => - eventStream?.expand(convert); + eventStream!.expand(convert); @override - Future get first => eventStream?.first; + Future get first => eventStream!.first; @override - Future firstWhere(bool Function(T element) test, {T Function() orElse}) => - eventStream?.firstWhere(test, orElse: orElse); + Future firstWhere(bool Function(T element) test, {T Function()? orElse}) => + eventStream!.firstWhere(test, orElse: orElse); @override Future fold( S initialValue, S Function(S previous, T element) combine) => - eventStream?.fold(initialValue, combine); + eventStream!.fold(initialValue, combine); @override Future forEach(void Function(T element) action) => - eventStream?.forEach(action); + eventStream!.forEach(action); @override - StreamSubscription getSingletonSubscription(singletonIdentifier, + StreamSubscription? getSingletonSubscription(singletonIdentifier, [bool singletonIdentifyByInstance = true]) => eventStream?.getSingletonSubscription( singletonIdentifier, singletonIdentifyByInstance); @override Stream handleError(Function onError, - {bool Function(dynamic error) test}) => - eventStream?.handleError(onError, test: test); + {bool Function(dynamic error)? test}) => + eventStream!.handleError(onError, test: test); @override - bool get isBroadcast => eventStream?.isBroadcast; + bool get isBroadcast => eventStream!.isBroadcast; @override - bool get isClosed => eventStream?.isClosed; + bool get isClosed => eventStream!.isClosed; @override - Future get isEmpty => eventStream?.isEmpty; + Future get isEmpty => eventStream!.isEmpty; @override - bool get isPaused => eventStream?.isPaused; + bool get isPaused => eventStream!.isPaused; @override - bool get isUsed => eventStream?.isUsed; + bool get isUsed => eventStream!.isUsed; @override - Future join([String separator = '']) => eventStream?.join(separator); + Future join([String separator = '']) => eventStream!.join(separator); @override - Future get last => eventStream?.last; + Future get last => eventStream!.last; @override - Future lastWhere(bool Function(T element) test, {T Function() orElse}) => - eventStream?.lastWhere(test, orElse: orElse); + Future lastWhere(bool Function(T element) test, {T Function()? orElse}) => + eventStream!.lastWhere(test, orElse: orElse); @override - Future get length => eventStream?.length; + Future get length => eventStream!.length; @override - Future listenAsFuture() => eventStream?.listenAsFuture(); + Future listenAsFuture() => eventStream!.listenAsFuture(); @override - Stream map(S Function(T event) convert) => eventStream?.map(convert); + Stream map(S Function(T event) convert) => eventStream!.map(convert); @override Future pipe(StreamConsumer streamConsumer) => - eventStream?.pipe(streamConsumer); + eventStream!.pipe(streamConsumer); @override Future reduce(T Function(T previous, T element) combine) => - eventStream?.reduce(combine); + eventStream!.reduce(combine); @override - Future get single => eventStream?.single; + Future get single => eventStream!.single; @override - Future singleWhere(bool Function(T element) test, {T Function() orElse}) => - eventStream?.singleWhere(test, orElse: orElse); + Future singleWhere(bool Function(T element) test, + {T Function()? orElse}) => + eventStream!.singleWhere(test, orElse: orElse); @override - Stream skip(int count) => eventStream?.skip(count); + Stream skip(int count) => eventStream!.skip(count); @override Stream skipWhile(bool Function(T element) test) => - eventStream?.skipWhile(test); + eventStream!.skipWhile(test); @override - Stream take(int count) => eventStream?.take(count); + Stream take(int count) => eventStream!.take(count); @override Stream takeWhile(bool Function(T element) test) => - eventStream?.takeWhile(test); + eventStream!.takeWhile(test); @override Stream timeout(Duration timeLimit, - {void Function(EventSink sink) onTimeout}) => - eventStream?.timeout(timeLimit, onTimeout: onTimeout); + {void Function(EventSink sink)? onTimeout}) => + eventStream!.timeout(timeLimit, onTimeout: onTimeout); @override - Future> toList() => eventStream?.toList(); + Future> toList() => eventStream!.toList(); @override - Future> toSet() => eventStream?.toSet(); + Future> toSet() => eventStream!.toSet(); @override Stream transform(StreamTransformer streamTransformer) => - eventStream?.transform(streamTransformer); + eventStream!.transform(streamTransformer); @override - Stream where(bool Function(T event) test) => eventStream?.where(test); + Stream where(bool Function(T event) test) => eventStream!.where(test); @override - EventValidatorFunction get eventValidator => eventStream?.eventValidator; + EventValidatorFunction? get eventValidator => eventStream?.eventValidator; @override - set eventValidator(EventValidatorFunction eventValidator) => + set eventValidator(EventValidatorFunction? eventValidator) => eventStream?.eventValidator = eventValidator; } +class _StreamSubscriptionProvider extends StreamSubscription { + final StreamSubscription? Function() _provider; + StreamSubscription? _s; + + StreamSubscription get _source { + _s ??= _provider(); + return _s!; + } + + _StreamSubscriptionProvider(this._provider); + + @override + void onData(void Function(T)? handleData) { + _source.onData(handleData); + } + + @override + void onError(Function? handleError) { + _source.onError(handleError); + } + + @override + void onDone(void Function()? handleDone) { + _source.onDone(handleDone); + } + + @override + void pause([Future? resumeFuture]) { + _source.pause(resumeFuture); + } + + @override + void resume() { + _source.resume(); + } + + @override + Future cancel() => _source.cancel(); + + @override + Future asFuture([E? futureValue]) => _source.asFuture(futureValue); + + @override + bool get isPaused => _source.isPaused; +} + /// Tracks interactions and after a delay, without interaction, triggers /// [onComplete]. class InteractionCompleter { @@ -801,14 +854,13 @@ class InteractionCompleter { /// Delay starts in the 1st call to [interact] and is zeroed when the trigger is called. /// /// * NOTE: After the trigger is called, the next call to [interact] is considered a 1st call. - final Duration triggerDelayLimit; + final Duration? triggerDelayLimit; - Function functionToTrigger; + Function? functionToTrigger; - InteractionCompleter(String name, - {Duration triggerDelay, this.functionToTrigger, this.triggerDelayLimit}) - : name = name ?? '', - triggerDelay = triggerDelay ?? Duration(milliseconds: 500); + InteractionCompleter(this.name, + {Duration? triggerDelay, this.functionToTrigger, this.triggerDelayLimit}) + : triggerDelay = triggerDelay ?? Duration(milliseconds: 500); int get now { return DateTime.now().millisecondsSinceEpoch; @@ -817,20 +869,20 @@ class InteractionCompleter { int get triggerDelayMs => triggerDelay.inMilliseconds; bool get hasTriggerDelayLimit => - triggerDelayLimit != null && triggerDelayLimit.inMilliseconds > 0; + triggerDelayLimit != null && triggerDelayLimit!.inMilliseconds > 0; - int _initInteractionTime; - int _lastInteractionTime; + int? _initInteractionTime; + int? _lastInteractionTime; - int get lastInteractionTime => _lastInteractionTime; + int? get lastInteractionTime => _lastInteractionTime; bool _interactionNotTriggered = false; bool get hasInteractionNotTriggered => _interactionNotTriggered; - List _lastInteractionParameters; + List? _lastInteractionParameters; - List get lastInteractionParameters => _lastInteractionParameters; + List? get lastInteractionParameters => _lastInteractionParameters; void disposeLastInteractionParameters() { _lastInteractionParameters = null; @@ -842,12 +894,12 @@ class InteractionCompleter { /// [interactionParameters] Stores parameters that can be used while triggering, using [lastInteractionParameters]. void interact( {noTriggering = false, - List interactionParameters, + List? interactionParameters, bool ignoreConsecutiveEqualsParameters = false}) { noTriggering ??= false; if (interactionParameters != null) { - if (ignoreConsecutiveEqualsParameters ?? false) { + if (ignoreConsecutiveEqualsParameters) { if (_lastInteractionParameters != null && isEqualsDeep(_lastInteractionParameters, interactionParameters)) { log('ignore interact', [noTriggering, interactionParameters]); @@ -871,11 +923,11 @@ class InteractionCompleter { } } - int get interactionElapsedTime => - _lastInteractionTime != null ? now - _lastInteractionTime : null; + int? get interactionElapsedTime => + _lastInteractionTime != null ? now - _lastInteractionTime! : null; - int get fullInteractionElapsedTime => - _initInteractionTime != null ? now - _initInteractionTime : null; + int? get fullInteractionElapsedTime => + _initInteractionTime != null ? now - _initInteractionTime! : null; bool _triggerScheduled = false; @@ -893,13 +945,13 @@ class InteractionCompleter { void _callTrigger() { if (!_triggerScheduled) return; - var timeUntilNextTrigger = triggerDelayMs - interactionElapsedTime; + var timeUntilNextTrigger = triggerDelayMs - interactionElapsedTime!; log('_callTrigger', [timeUntilNextTrigger]); if (timeUntilNextTrigger > 0) { if (hasTriggerDelayLimit && - fullInteractionElapsedTime > triggerDelayLimit.inMilliseconds) { + fullInteractionElapsedTime! > triggerDelayLimit!.inMilliseconds) { triggerNow(); } else { Future.delayed( @@ -911,7 +963,7 @@ class InteractionCompleter { } /// Triggers only if already has some interaction. - void triggerIfHasInteraction({List interactionParameters}) { + void triggerIfHasInteraction({List? interactionParameters}) { if (hasInteractionNotTriggered) { triggerNow(interactionParameters: interactionParameters); } @@ -920,7 +972,7 @@ class InteractionCompleter { final EventStream onComplete = EventStream(); /// Triggers immediately. - void triggerNow({List interactionParameters}) { + void triggerNow({List? interactionParameters}) { log('triggerNow'); if (interactionParameters != null) { @@ -933,7 +985,7 @@ class InteractionCompleter { if (functionToTrigger != null) { try { - functionToTrigger(); + functionToTrigger!(); } catch (e, s) { print(e); print(s); @@ -959,7 +1011,7 @@ class InteractionCompleter { _lastInteractionParameters = null; } - void log(String method, [List parameters]) { + void log(String method, [List? parameters]) { //print('InteractionCompleter[$name] $method> ${parameters ?? ''}'); } } @@ -971,14 +1023,14 @@ class InteractionCompleterDummy extends InteractionCompleter { @override void interact( {noTriggering = false, - List interactionParameters, + List? interactionParameters, bool ignoreConsecutiveEqualsParameters = false}) {} @override - void triggerIfHasInteraction({List interactionParameters}) {} + void triggerIfHasInteraction({List? interactionParameters}) {} @override - void triggerNow({List interactionParameters}) {} + void triggerNow({List? interactionParameters}) {} } /// Listen [stream], calling [onData] only after [triggerDelay] duration. @@ -986,9 +1038,7 @@ class InteractionCompleterDummy extends InteractionCompleter { /// [onData] is only called when [stream] event is triggered and stays /// without any new event for [triggerDelay] duration. InteractionCompleter listenStreamWithInteractionCompleter( - Stream /*!*/ stream, - Duration /*!*/ triggerDelay, - void Function(T event) /*!*/ onData) { + Stream stream, Duration triggerDelay, void Function(T? event) onData) { var lastEvent = []; var interactionCompleter = InteractionCompleter( @@ -1009,21 +1059,21 @@ InteractionCompleter listenStreamWithInteractionCompleter( /// A wrapper and handler for a value that is asynchronous (from a [Future]). class AsyncValue { - Future /*!*/ _future; + late final Future _future; - AsyncValue(Future /*!*/ future) { - _future = future.then((v) => _onLoad(v), onError: _onError); + AsyncValue(Future future) { + _future = future.then((v) => _onLoad(v)!, onError: _onError); } factory AsyncValue.from(dynamic /*!*/ value) { if (value is Future) { - return AsyncValue(value); + return AsyncValue(value as Future); } else if (value is Future Function()) { var future = value(); return AsyncValue(future); } else if (value is Future Function()) { var future = value(); - return AsyncValue(future); + return AsyncValue(future as Future); } else if (value is T Function()) { var future = Future.microtask(() => value()); return AsyncValue(future); @@ -1037,7 +1087,7 @@ class AsyncValue { return result; } }); - return AsyncValue(future); + return AsyncValue(future as Future); } else { throw ArgumentError('Not an async value: $value'); } @@ -1046,9 +1096,9 @@ class AsyncValue { Future get future => _future; /// Handles `load` events. - final EventStream /*!*/ onLoad = EventStream(); + final EventStream onLoad = EventStream(); - bool /*!*/ _loaded = false; + bool _loaded = false; /// Returns [true] if value is loaded. bool get isLoaded => _loaded; @@ -1066,9 +1116,9 @@ class AsyncValue { /// Returns [true] if the value has an execution [error]. bool get hasError => _error != null; - T /*?*/ _value; + T? _value; - T _onLoad(value) { + T? _onLoad(value) { _loaded = true; _value = value; onLoad.add(value); @@ -1084,16 +1134,16 @@ class AsyncValue { /// Returns the value (only if already loaded). /// /// [StateError] in case the value is not loaded yet. - T get() { + T? get() { if (!isLoaded) throw StateError('Not loaded yet!'); return _value; } /// Returns the value if loaded. - T getIfLoaded() => _value; + T? getIfLoaded() => _value; /// Returns a [Future] with the value. - Future getAsync() async { + Future getAsync() async { if (isLoaded) return _value; await _future; return _value; @@ -1112,19 +1162,19 @@ class AsyncValue { /// Useful to create a one shot listener or extend and introduce different behaviors. class ListenerWrapper { /// [Stream] to wrap [listen] calls. - final Stream /*!*/ stream; + final Stream stream; - final void Function(T event) /*!*/ onData; + final void Function(T event) onData; - final Function /*?*/ onError; + final Function? onError; - final void Function() /*?*/ onDone; + final void Function()? onDone; - final bool /*!*/ cancelOnError; + final bool cancelOnError; final dynamic /*?*/ singletonIdentifier; - final bool /*!*/ singletonIdentifyByInstance; + final bool singletonIdentifyByInstance; /// See [Stream.listen]. ListenerWrapper(this.stream, this.onData, @@ -1136,14 +1186,14 @@ class ListenerWrapper { this.singletonIdentifyByInstance = true}); /// If [true] will wait for 1 event and call [cancel]. - bool /*!*/ oneShot = false; + bool oneShot = false; - int /*!*/ _eventCount = 0; + int _eventCount = 0; int get eventCount => _eventCount; /// Wrapper for any [event] or [error]. - void onEvent(T event, Object error, StackTrace stackTrace) { + void onEvent(T? event, Object? error, StackTrace? stackTrace) { ++_eventCount; if (oneShot) { cancel(); @@ -1167,13 +1217,13 @@ class ListenerWrapper { onEvent(null, error, stackTrace); if (onError is void Function(Object error, StackTrace stackTrace)) { - onError(error, stackTrace); + onError!(error, stackTrace); } else if (onError is void Function(Object error)) { - onError(error); + onError!(error); } else if (onError is void Function()) { - onError(); + onError!(); } else if (onError != null) { - onError.call(); + onError!.call(); } } @@ -1181,14 +1231,14 @@ class ListenerWrapper { void onDoneWrapper() { onEvent(null, null, null); if (onDone != null) { - onDone(); + onDone!(); } } - StreamSubscription _subscription; + StreamSubscription? _subscription; /// The last [stream.listen] [StreamSubscription]. - StreamSubscription get subscription => _subscription; + StreamSubscription? get subscription => _subscription; /// Returns [true] if listening. bool get isListening => _subscription != null; @@ -1196,17 +1246,19 @@ class ListenerWrapper { /// Calls [stream.listen] and sets [subscription]. /// /// Returns [false] if already listening. - bool /*!*/ listen() { + bool listen() { if (isListening) return false; if (stream is EventStream) { var eventStream = stream as EventStream; - _subscription = eventStream.listen(onDataWrapper, - onError: onErrorWrapper, - onDone: onDoneWrapper, - cancelOnError: cancelOnError, - singletonIdentifier: singletonIdentifier, - singletonIdentifyByInstance: singletonIdentifyByInstance); + _subscription = eventStream.listen( + onDataWrapper as void Function(dynamic), + onError: onErrorWrapper, + onDone: onDoneWrapper, + cancelOnError: cancelOnError, + singletonIdentifier: singletonIdentifier, + singletonIdentifyByInstance: singletonIdentifyByInstance) + as StreamSubscription?; } else { _subscription = stream.listen(onDataWrapper, onError: onErrorWrapper, diff --git a/lib/src/io.dart b/lib/src/io.dart index 0a74cc8..3c4e75c 100644 --- a/lib/src/io.dart +++ b/lib/src/io.dart @@ -5,7 +5,7 @@ import 'dart:typed_data'; /// Loads a file as String using [encoding]. /// /// [encoding] If null uses UTF-8. -Future catFile(File file, [Encoding /*!*/ encoding = utf8]) async { +Future catFile(File file, [Encoding encoding = utf8]) async { return file.readAsString(encoding: encoding); } @@ -18,7 +18,7 @@ Future catFileBytes(File file) async { /// /// [encoding] If null uses UTF-8. Future saveFile(File file, String data, - [Encoding /*!*/ encoding = utf8]) async { + [Encoding encoding = utf8]) async { return file.writeAsString(data, encoding: encoding, flush: true); } diff --git a/lib/src/json.dart b/lib/src/json.dart index e8e6b37..4b9534e 100644 --- a/lib/src/json.dart +++ b/lib/src/json.dart @@ -25,11 +25,11 @@ dynamic /*?*/ parseJSON(dynamic /*?*/ json, [dynamic /*?*/ def]) { /// [indent] By default uses 2 spaces: ` `. /// [clearNullEntries] If true will apply [removeNullEntries] and remove any null entry in tree. /// [toEncodable] Function to transform an object to JSON. -String /*!*/ encodeJSON(dynamic /*?*/ json, - {String /*?*/ indent, - bool /*!*/ withIndent = false, - bool /*!*/ clearNullEntries = false, - Object Function(dynamic object) /*!*/ toEncodable = toEncodableJSON}) { +String encodeJSON(dynamic /*?*/ json, + {String? indent, + bool withIndent = false, + bool clearNullEntries = false, + Object? Function(dynamic object) toEncodable = toEncodableJSON}) { if (clearNullEntries) { removeNullEntries(json); } @@ -50,7 +50,7 @@ String /*!*/ encodeJSON(dynamic /*?*/ json, } /// Remove null entries from [json] tree. -T /*?*/ removeNullEntries(T /*?*/ json) { +T? removeNullEntries(T? json) { if (json == null) return null; if (json is List) { @@ -65,17 +65,17 @@ T /*?*/ removeNullEntries(T /*?*/ json) { } /// Returns [true] if [value] is a JSON. -bool /*!*/ isJSON(dynamic /*?*/ value) { +bool isJSON(dynamic /*?*/ value) { return isJSONPrimitive(value) || isJSONList(value) || isJSONMap(value); } /// Returns [true] if [value] is a JSON primitive (String, bool, num, int, double, or null). -bool /*!*/ isJSONPrimitive(dynamic /*?*/ value) { +bool isJSONPrimitive(dynamic /*?*/ value) { return value == null || value is String || value is num || value is bool; } /// Returns [true] if [value] is a JSON List. -bool /*!*/ isJSONList(dynamic /*?*/ json) { +bool isJSONList(dynamic /*?*/ json) { if (json == null) return false; if (json is List) return true; @@ -92,7 +92,7 @@ bool /*!*/ isJSONList(dynamic /*?*/ json) { } /// Returns [true] if [value] is a JSON Map. -bool /*!*/ isJSONMap(dynamic /*?*/ json) { +bool isJSONMap(dynamic /*?*/ json) { if (json == null) return false; if (json is Map) return true; @@ -136,7 +136,7 @@ dynamic /*?*/ toEncodableJSON(dynamic /*?*/ o) { } /// Ensures that [list] is an encodable JSON tree. -List /*!*/ toEncodableJSONList(List /*?*/ list) { +List toEncodableJSONList(List? list) { if (list == null) return []; if (list is List) return list; @@ -169,7 +169,7 @@ List /*!*/ toEncodableJSONList(List /*?*/ list) { } /// Ensures that [map] is an encodable JSON tree. -Map /*!*/ toEncodableJSONMap(Map /*?*/ map) { +Map toEncodableJSONMap(Map? map) { if (map == null) return {}; if (map is Map) return map; @@ -206,7 +206,7 @@ Map /*!*/ toEncodableJSONMap(Map /*?*/ map) { } /// Returns [true] if [s] is a encoded JSON String of a primitive value. -bool /*!*/ isEncodedJSON(String /*?*/ s) { +bool isEncodedJSON(String? s) { if (s == null) return false; s = s.trim(); if (s.isEmpty) return false; @@ -217,7 +217,7 @@ bool /*!*/ isEncodedJSON(String /*?*/ s) { } /// Returns [true] if [s] is a encoded JSON String of a primitive value. -bool /*!*/ isEncodedJSONPrimitive(String /*?*/ s) { +bool isEncodedJSONPrimitive(String? s) { if (s == null) return false; s = s.trim(); if (s.isEmpty) return false; @@ -225,7 +225,7 @@ bool /*!*/ isEncodedJSONPrimitive(String /*?*/ s) { return _isEncodedJSONPrimitive(s); } -bool /*!*/ _isEncodedJSONPrimitive(String /*!*/ s) { +bool _isEncodedJSONPrimitive(String s) { return _isEncodedJSONString(s) || _isEncodedJSONBoolean(s) || _isEncodedJSONNumber(s) || @@ -233,41 +233,41 @@ bool /*!*/ _isEncodedJSONPrimitive(String /*!*/ s) { } /// Returns [true] if [s] is a encoded JSON `null`. -bool /*!*/ isEncodedJSONNull(String /*?*/ s) { +bool isEncodedJSONNull(String? s) { if (s == null) return false; s = s.trim(); return _isEncodedJSONNull(s); } -bool /*!*/ _isEncodedJSONNull(String /*!*/ s) => s == 'null'; +bool _isEncodedJSONNull(String s) => s == 'null'; /// Returns [true] if [s] is a encoded JSON [bool]. -bool /*!*/ isEncodedJSONBoolean(String /*?*/ s) { +bool isEncodedJSONBoolean(String? s) { if (s == null) return false; s = s.trim(); return _isEncodedJSONBoolean(s); } -bool /*!*/ _isEncodedJSONBoolean(String /*!*/ s) => s == 'true' || s == 'false'; +bool _isEncodedJSONBoolean(String s) => s == 'true' || s == 'false'; /// Returns [true] if [s] is a encoded JSON [num]. -bool /*!*/ isEncodedJSONNumber(String /*?*/ s) { +bool isEncodedJSONNumber(String? s) { if (s == null) return false; s = s.trim(); if (s.isEmpty) return false; return _isEncodedJSONNumber(s); } -bool /*!*/ _isEncodedJSONNumber(String /*!*/ s) => isNum(s); +bool _isEncodedJSONNumber(String s) => isNum(s); /// Returns [true] if [s] is a encoded JSON [String]. -bool /*!*/ isEncodedJSONString(String /*?*/ s) { +bool isEncodedJSONString(String? s) { if (s == null) return false; s = s.trim(); return _isEncodedJSONString(s); } -bool /*!*/ _isEncodedJSONString(String /*!*/ s) { +bool _isEncodedJSONString(String s) { if (s == '""') return true; if (s.startsWith('"') && s.endsWith('"')) { @@ -283,14 +283,14 @@ bool /*!*/ _isEncodedJSONString(String /*!*/ s) { } /// Returns [true] if [s] is a encoded JSON [List]. -bool /*!*/ isEncodedJSONList(String /*?*/ s) { +bool isEncodedJSONList(String? s) { if (s == null) return false; s = s.trim(); if (s.isEmpty) return false; return _isEncodedJSONList(s); } -bool /*!*/ _isEncodedJSONList(String /*!*/ s) { +bool _isEncodedJSONList(String s) { if (!s.startsWith('[') || !s.endsWith(']')) return false; try { @@ -302,13 +302,13 @@ bool /*!*/ _isEncodedJSONList(String /*!*/ s) { } /// Returns [true] if [s] is a encoded JSON [Map]. -bool /*!*/ isEncodedJSONMap(String /*?*/ s) { +bool isEncodedJSONMap(String? s) { if (s == null) return false; s = s.trim(); return _isEncodedJSONMap(s); } -bool /*!*/ _isEncodedJSONMap(String /*!*/ s) { +bool _isEncodedJSONMap(String s) { if (!s.startsWith('{') || !s.endsWith('}')) return false; try { diff --git a/lib/src/loader.dart b/lib/src/loader.dart index 397609d..9dd226b 100644 --- a/lib/src/loader.dart +++ b/lib/src/loader.dart @@ -1,6 +1,6 @@ import 'events.dart'; -typedef LoaderFunction = Future /*!*/ Function(); +typedef LoaderFunction = Future Function(); /// Controls a load process. class LoadController { @@ -12,43 +12,43 @@ class LoadController { String id = (++_idCounter).toString(); /// The actual loading function that is handled by this [LoadController]. - LoaderFunction /*?*/ loader; + LoaderFunction? loader; final EventStream onLoad = EventStream(); - LoadController([String /*?*/ id]) { + LoadController([String? id]) { this.id = id ?? _newID(); } - LoadController.function(this.loader, [String /*?*/ id]) { + LoadController.function(this.loader, [String? id]) { if (loader == null) throw ArgumentError('Null LoaderFunction'); this.id = id ?? _newID(); } - Future /*?*/ _loadFuture; + Future? _loadFuture; - bool /*!*/ _loaded = false; + bool _loaded = false; /// Returns [true] if is loaded. - bool /*!*/ get isLoaded => _loaded; + bool get isLoaded => _loaded; /// Returns [false] if is not loaded. - bool /*!*/ get isNotLoaded => !isLoaded; + bool get isNotLoaded => !isLoaded; /// [true] if is loaded and successful. - bool /*?*/ _loadSuccessful; + bool? _loadSuccessful; /// Returns [true] if load was successful. /// /// If load is not completed yet will return null. - bool /*?*/ get loadSuccessful => _loadSuccessful; + bool? get loadSuccessful => _loadSuccessful; /// Does the load process. /// /// - [actualLoader]: the function to use in the load process. /// Will throw a [StateError] if [loader] is already set by the constructor. - Future /*!*/ load([LoaderFunction /*?*/ actualLoader]) async { - if (_loadFuture != null) return _loadFuture; + Future load([LoaderFunction? actualLoader]) async { + if (_loadFuture != null) return _loadFuture!; if (actualLoader != null) { if (loader != null) { @@ -63,7 +63,7 @@ class LoadController { 'LoadController[$id] without LoaderFunction: required as parameter when calling load().'); } - _loadFuture = loader(); + _loadFuture = loader!(); _loadSuccessful = await _loadFuture; _loaded = true; @@ -72,7 +72,7 @@ class LoadController { print(this); - return _loadSuccessful; + return _loadSuccessful!; } @override diff --git a/lib/src/math.dart b/lib/src/math.dart index 0d53cdc..81acaf2 100644 --- a/lib/src/math.dart +++ b/lib/src/math.dart @@ -124,7 +124,7 @@ class Math { } /// Subtract in sequence [ns] entries. - static double /*!*/ subtract(Iterable ns) { + static double subtract(Iterable ns) { if (ns.length <= 1) return 0; var total; @@ -140,7 +140,7 @@ class Math { } /// Multiply in sequence [ns] entries. - static double /*!*/ multiply(Iterable ns) { + static double multiply(Iterable ns) { if (ns.length <= 1) return 0; var total; @@ -156,7 +156,7 @@ class Math { } /// Divide in sequence [ns] entries. - static double /*!*/ divide(Iterable ns) { + static double divide(Iterable ns) { if (ns.length <= 1) return 0; var total; @@ -172,7 +172,7 @@ class Math { } /// Mean value of [ns] entries. - static double /*!*/ mean(Iterable ns) { + static double mean(Iterable ns) { if (ns.isEmpty) return 0; return sum(ns) / ns.length; } @@ -180,7 +180,7 @@ class Math { /// Standard deviation of [ns] entries. /// /// [mean] an already calculated mean for [ns]. - static double standardDeviation(Iterable ns, [num /*?*/ mean]) { + static double standardDeviation(Iterable ns, [num? mean]) { if (ns.length == 1) { return 0.0; } else { @@ -188,7 +188,7 @@ class Math { var sum = 0.0; for (var n in ns) { - double v = (n - meanD); + var v = (n - meanD); v *= v; sum += v; } @@ -203,8 +203,7 @@ class Math { /// A pair with minimum and maximum value of [ns] entries. /// /// [comparator] is optional and useful for non [num] [T]. - static Pair /*?*/ minMax(Iterable /*?*/ ns, - [Comparator comparator]) { + static Pair? minMax(Iterable? ns, [Comparator? comparator]) { if (ns == null || ns.isEmpty) return null; if (comparator != null) { @@ -233,8 +232,7 @@ class Math { /// Minimal value of [ns] entries. /// /// [comparator] is optional and useful for non [num] [T]. - static T /*?*/ minInList(Iterable /*?*/ ns, - [Comparator comparator]) { + static T? minInList(Iterable? ns, [Comparator? comparator]) { if (ns == null || ns.isEmpty) return null; if (comparator != null) { @@ -259,8 +257,7 @@ class Math { /// Maximum value in [ns] entries. /// /// [comparator] is optional and useful for non [num] [T]. - static T /*?*/ maxInList(Iterable /*?*/ ns, - [Comparator comparator]) { + static T? maxInList(Iterable? ns, [Comparator? comparator]) { if (ns == null || ns.isEmpty) return null; if (comparator != null) { @@ -286,7 +283,7 @@ class Math { /// Parses [v] to [int]. /// /// [def] The default value if [v] is invalid. -int /*?*/ parseInt(dynamic /*?*/ v, [int /*?*/ def]) { +int? parseInt(dynamic /*?*/ v, [int? def]) { if (v == null) return def; if (v is int) return v; @@ -305,7 +302,7 @@ int /*?*/ parseInt(dynamic /*?*/ v, [int /*?*/ def]) { if (s.isEmpty) return def; - num n = int.tryParse(s); + num? n = int.tryParse(s); if (n == null) { var d = double.tryParse(s); @@ -314,13 +311,13 @@ int /*?*/ parseInt(dynamic /*?*/ v, [int /*?*/ def]) { } } - return n ?? def; + return n as int? ?? def; } /// Parses [v] to [double]. /// /// [def] The default value if [v] is invalid. -double /*?*/ parseDouble(dynamic /*?*/ v, [double /*?*/ def]) { +double? parseDouble(dynamic /*?*/ v, [double? def]) { if (v == null) return def; if (v is double) return v; @@ -344,7 +341,7 @@ double /*?*/ parseDouble(dynamic /*?*/ v, [double /*?*/ def]) { /// Parses [v] to [num]. /// /// [def] The default value if [v] is invalid. -num /*?*/ parseNum(dynamic /*?*/ v, [num /*?*/ def]) { +num? parseNum(dynamic /*?*/ v, [num? def]) { if (v == null) return def; if (v is num) return v; @@ -373,7 +370,7 @@ num /*?*/ parseNum(dynamic /*?*/ v, [num /*?*/ def]) { /// if [v] is [String]: true when [v == "true"|"yes"|"ok"|"1"|"y"|"s"|"t"|"+" /// /// [def] The default value if [v] is invalid. -bool /*?*/ parseBool(dynamic /*?*/ v, [bool /*?*/ def]) { +bool? parseBool(dynamic /*?*/ v, [bool? def]) { if (v == null) return def; if (v is bool) return v; @@ -405,8 +402,8 @@ bool /*?*/ parseBool(dynamic /*?*/ v, [bool /*?*/ def]) { /// /// [delimiter] pattern for delimiter if [s] is a [String]. /// [def] the default value if [s] is invalid. -List /*?*/ parseIntsFromInlineList(dynamic s, - [Pattern /*!*/ delimiter = ',', List /*?*/ def]) { +List? parseIntsFromInlineList(dynamic s, + [Pattern delimiter = ',', List? def]) { if (s == null) return def; if (s is int) return [s]; if (s is List) { @@ -416,49 +413,52 @@ List /*?*/ parseIntsFromInlineList(dynamic s, .cast() .toList(); } - return parseFromInlineList(s.toString(), delimiter, parseInt, def); + return parseFromInlineList(s.toString(), delimiter, (v) => parseInt(v)!, def); } /// Parses [s] to a [List]. /// /// [delimiter] pattern for delimiter if [s] is a [String]. /// [def] the default value if [s] is invalid. -List/*?*/ parseNumsFromInlineList(dynamic s, - [Pattern/*!*/ delimiter = ',', List/*?*/ def]) { +List? parseNumsFromInlineList(dynamic s, + [Pattern delimiter = ',', List? def]) { if (s == null) return def; if (s is num) return [s]; - if (s is List) return s.map((e) => parseNum(e)).toList(); - return parseFromInlineList(s.toString(), delimiter, parseNum, def); + if (s is List) return s.map((e) => parseNum(e)).toList() as List?; + return parseFromInlineList( + s.toString(), delimiter, parseNum as num Function(String)?, def); } /// Parses [s] to a [List]. /// /// [delimiter] pattern for delimiter if [s] is a [String]. /// [def] the default value if [s] is invalid. -List/*?*/ parseDoublesFromInlineList(dynamic s, - [Pattern delimiter/*!*/ = ',', List/*?*/ def]) { +List? parseDoublesFromInlineList(dynamic s, + [Pattern delimiter /*!*/ = ',', List? def]) { if (s == null) return def; if (s is double) return [s]; - if (s is List) return s.map((e) => parseDouble(e)).toList(); - return parseFromInlineList(s.toString(), delimiter, parseDouble, def); + if (s is List) return s.map((e) => parseDouble(e)).toList() as List?; + return parseFromInlineList( + s.toString(), delimiter, parseDouble as double Function(String)?, def); } /// Parses [s] to a [List]. /// /// [delimiter] pattern for delimiter if [s] is a [String]. /// [def] the default value if [s] is invalid. -List/*?*/ parseBoolsFromInlineList(dynamic s, Pattern/*!*/ delimiter, - [List/*?*/ def]) { +List? parseBoolsFromInlineList(dynamic s, Pattern delimiter, + [List? def]) { if (s == null) return def; if (s is bool) return [s]; - if (s is List) return s.map((e) => parseBool(e)).toList(); - return parseFromInlineList(s.toString(), delimiter, parseBool, def); + if (s is List) return s.map((e) => parseBool(e)).toList() as List?; + return parseFromInlineList( + s.toString(), delimiter, parseBool as bool Function(String)?, def); } RegExp _REGEXP_SPLIT_COMMA = RegExp(r'\s*,\s*'); /// Parses a generic [list] to a [List]. -List parseNumsFromList(List/*!*/ list) { +List parseNumsFromList(List list) { return list .map((e) { if (e is dart_math.Point) { @@ -480,7 +480,7 @@ List parseNumsFromList(List/*!*/ list) { /// Parses [v] as a percentage from 0..100. /// /// [def] the default value if [v] is invalid. -num/*?*/ parsePercent(dynamic v, [double/*?*/ def]) { +num? parsePercent(dynamic v, [double? def]) { if (v == null) return null; if (v is num) { @@ -509,8 +509,8 @@ num/*?*/ parsePercent(dynamic v, [double/*?*/ def]) { /// /// [precision] amount of decimal places. /// [decimalSeparator] decimal separator, usually `.` or `,`. -String/*?*/ formatDecimal(dynamic value, - {int/*!*/ precision = 2, String/*!*/ decimalSeparator = '.'}) { +String? formatDecimal(dynamic value, + {int precision = 2, String decimalSeparator = '.'}) { if (value == null) return null; var p = parseNum(value); @@ -537,7 +537,7 @@ String/*?*/ formatDecimal(dynamic value, decimal = decimal.substring(0, precision); } - if (decimalSeparator == null || decimalSeparator.isEmpty) { + if (decimalSeparator.isEmpty) { decimalSeparator = '.'; } @@ -548,7 +548,8 @@ String/*?*/ formatDecimal(dynamic value, /// /// [precision] amount of decimal places. /// [isRatio] if true the [percent] parameter is in the range 0..1. -String formatPercent(dynamic percent, {int/*!*/ precision = 2, bool/*!*/ isRatio = false}) { +String formatPercent(dynamic percent, + {int precision = 2, bool isRatio = false}) { if (percent == null) return '0%'; var p = parseNum(percent); @@ -583,7 +584,7 @@ String formatPercent(dynamic percent, {int/*!*/ precision = 2, bool/*!*/ isRatio } /// Returns true if [value] is [int]. Can be a int as string too. -bool/*!*/ isInt(dynamic value) { +bool isInt(dynamic value) { if (value == null) return false; if (value is int) return true; if (value is num) return value.toInt() == value; @@ -593,13 +594,13 @@ bool/*!*/ isInt(dynamic value) { } /// Returns [true] if is a list of [int]. Can be a string of int too. -bool/*!*/ isIntList(dynamic value, [String delimiter = ',']) { +bool isIntList(dynamic value, [String delimiter = ',']) { if (value == null) return false; if (value is List) return true; if (value is Iterable) { - return listMatchesAll(value, (e) => e is int); + return listMatchesAll(value, (dynamic e) => e is int); } var s = value.toString(); @@ -607,7 +608,7 @@ bool/*!*/ isIntList(dynamic value, [String delimiter = ',']) { } /// Returns true if [value] is [num]. Can be a num as string too. -bool/*!*/ isNum(dynamic value) { +bool isNum(dynamic value) { if (value == null) return false; if (value is num) return true; @@ -616,7 +617,7 @@ bool/*!*/ isNum(dynamic value) { } /// Returns [true] if is a list of [num]. Can be a string of num too. -bool/*!*/ isNumList(dynamic value, [String delimiter = ',']) { +bool isNumList(dynamic value, [String delimiter = ',']) { if (value == null) return false; if (value is List) return true; @@ -624,7 +625,7 @@ bool/*!*/ isNumList(dynamic value, [String delimiter = ',']) { if (value is List) return true; if (value is Iterable) { - return listMatchesAll(value, (e) => e is num); + return listMatchesAll(value, (dynamic e) => e is num); } var s = value.toString(); @@ -633,7 +634,7 @@ bool/*!*/ isNumList(dynamic value, [String delimiter = ',']) { } /// Returns true if [value] is [double]. Can be a double as string too. -bool/*!*/ isDouble(dynamic value) { +bool isDouble(dynamic value) { if (value == null) return false; if (value is double) return true; if (value is num) return value.toDouble() == value; @@ -643,13 +644,13 @@ bool/*!*/ isDouble(dynamic value) { } /// Returns [true] if is a list of [double]. Can be a string of double too. -bool/*!*/ isDoubleList(dynamic value, [String delimiter = ',']) { +bool isDoubleList(dynamic value, [String delimiter = ',']) { if (value == null) return false; if (value is List) return true; if (value is Iterable) { - return listMatchesAll(value, (e) => e is double); + return listMatchesAll(value, (dynamic e) => e is double); } var s = value.toString(); @@ -660,7 +661,7 @@ bool/*!*/ isDoubleList(dynamic value, [String delimiter = ',']) { final RegExp _REGEXP_bool = RegExp(r'^(?:true|false|yes|no)$'); /// Returns true if [value] is [bool]. Can be a bool as string too. -bool/*!*/ isBool(dynamic value) { +bool isBool(dynamic value) { if (value == null) return false; if (value is bool) return true; @@ -669,13 +670,13 @@ bool/*!*/ isBool(dynamic value) { } /// Returns [true] if is a list of [bool]. Can be a string of bool too. -bool/*!*/ isBoolList(dynamic value, [String delimiter = ',']) { +bool isBoolList(dynamic value, [String delimiter = ',']) { if (value == null) return false; if (value is List) return true; if (value is Iterable) { - return listMatchesAll(value, (e) => e is bool); + return listMatchesAll(value, (dynamic e) => e is bool); } var s = value.toString().toLowerCase(); @@ -688,27 +689,27 @@ bool/*!*/ isBoolList(dynamic value, [String delimiter = ',']) { /// Represents a scale with [minimum], [maximum] and [length]. class Scale { /// The minimum value of the scale. - final T/*!*/ minimum; + final T minimum; /// The maximum value of the scale. - final T/*!*/ maximum; + final T maximum; - T/*!*/ _length; + late T _length; /// The length of the scale: [maximum] - [minimum]. T get length => _length; - Scale(this.minimum, this.maximum, [T/*?*/ length]) { + Scale(this.minimum, this.maximum, [T? length]) { try { length ??= computeLength(maximum, minimum); } // ignore: empty_catches catch (ignore) {} - _length = length; + _length = length!; } - factory Scale.from(Iterable list) { + static Scale? from(Iterable? list) { if (list == null || list.isEmpty) return null; var sorted = list.toList(); @@ -716,7 +717,7 @@ class Scale { return Scale(sorted[0], sorted[sorted.length - 1]); } - Type/*!*/ valuesType() { + Type valuesType() { var t = minimum.runtimeType; if (maximum.runtimeType != t) { if (minimum is num && maximum is num) { @@ -731,7 +732,7 @@ class Scale { } /// Converts a [value] to [num]. - num/*?*/ toNum(T value) { + num? toNum(T value) { if (value == null) return null; if (value is num) { @@ -746,7 +747,7 @@ class Scale { } /// Converts a [value] to [T]. - T/*!*/ toValue(dynamic value) { + T toValue(dynamic value) { if (value is T) { return value; } else if (T == num) { @@ -757,7 +758,7 @@ class Scale { return parseDouble(value) as T; } else if (T == DateTime) { if (value is DateTime) return value as T; - var ms = parseInt(value); + var ms = parseInt(value)!; return DateTime.fromMillisecondsSinceEpoch(ms) as T; } else { throw StateError("Can't convert type to $T: $value"); @@ -765,55 +766,55 @@ class Scale { } /// Computes the length: [maximum] - [minimum]. - T/*!*/ computeLength(T/*!*/ maximum, T/*!*/ minimum) { - var max = toNum(maximum); - var min = toNum(minimum); + T computeLength(T maximum, T minimum) { + var max = toNum(maximum)!; + var min = toNum(minimum)!; var length = max - min; return toValue(length); } /// Normalizes a [value] to range 0..1. - double/*!*/ normalize(T/*!*/ value) { + double normalize(T value) { throw UnimplementedError(); } /// Denormalizes a [value] from range 0..1 to this scale. - T/*!*/ denormalize(double/*!*/ value) { + T denormalize(double value) { throw UnimplementedError(); } /// Clips [value] in this scale. - T/*!*/ clip(T/*!*/ value) { + T clip(T value) { throw UnimplementedError(); } /// Normalizes a list. - List/*!*/ normalizeList(Iterable/*!*/ list) { + List normalizeList(Iterable list) { return list.map(normalize).toList(); } /// Denormalizes a list. - List/*!*/ denormalizeList(Iterable/*!*/ list) { + List denormalizeList(Iterable list) { return list.map(denormalize).toList(); } /// Clips a list. - List/*!*/ clipList(Iterable/*!*/ list) { + List clipList(Iterable list) { return list.map(clip).toList(); } /// Same as [minimum] but as a nice number. - T/*!*/ get minimumNice => minimum; + T get minimumNice => minimum; /// Same as [maximum] but as a nice number. - T/*!*/ get maximumNice => maximum; + T get maximumNice => maximum; } /// Version of [Scale] but for [num] values. class ScaleNum extends Scale { - ScaleNum(num minimum, num maximum) : super(minimum, maximum); + ScaleNum(num minimum, num maximum) : super(minimum as N, maximum as N); - factory ScaleNum.from(Iterable list) { + static ScaleNum? from(Iterable? list) { if (list == null || list.isEmpty) return null; num min = list.first; @@ -834,7 +835,7 @@ class ScaleNum extends Scale { @override N computeLength(N maximum, N minimum) { - return maximum - minimum; + return maximum - minimum as N; } @override @@ -898,7 +899,7 @@ class ScaleNum extends Scale { var tolerance = niceTolerance(); if (tolerance == 0) return minimum; - return minimum - tolerance; + return minimum - tolerance as N; } @override @@ -908,14 +909,14 @@ class ScaleNum extends Scale { var tolerance = niceTolerance(); if (tolerance == 0) return maximum; - return maximum + tolerance; + return maximum + tolerance as N; } } /// Clips a number [n] into it's limits, [min] and [max]. /// /// [def] The default value if [n] is null. -N clipNumber(N n, N min, N max, [N def]) { +N? clipNumber(N? n, N min, N max, [N? def]) { n ??= def; if (n == null) return null; if (n < min) return min; @@ -924,7 +925,7 @@ N clipNumber(N n, N min, N max, [N def]) { } /// Returns [true] if [n > 0]. If [n] is null returns false. -bool isPositiveNumber(num n) => n != null && n > 0; +bool isPositiveNumber(num? n) => n != null && n > 0; /// Returns [true] if [n < 0]. If [n] is null returns false. -bool isNegativeNumber(num n) => n != null && n < 0; +bool isNegativeNumber(num? n) => n != null && n < 0; diff --git a/lib/src/paging.dart b/lib/src/paging.dart index 51e3d91..d18697e 100644 --- a/lib/src/paging.dart +++ b/lib/src/paging.dart @@ -6,8 +6,7 @@ typedef PagingFormatInstantiator = JSONPaging Function(dynamic json); /// A Function that performs a paging request. /// /// [page] the page of the request. -typedef PagingRequester = Future /*!*/ Function( - int /*!*/ page); +typedef PagingRequester = Future Function(int page); /// Generic representation of a paging result in JSON. abstract class JSONPaging extends MapDelegate { @@ -26,7 +25,7 @@ abstract class JSONPaging extends MapDelegate { _pagingFormats[matcher] = instantiator; } - factory JSONPaging.from(dynamic json) { + static JSONPaging? from(Object? json) { if (json == null) return null; _registerPagingFormats(); @@ -50,28 +49,28 @@ abstract class JSONPaging extends MapDelegate { Map get json => mainMap; /// Total number of pages. - int get totalPages; + int? get totalPages; /// Total elements of request. - int get totalElements; + int? get totalElements; /// Current page index, starting from 0. - int /*!*/ get currentPage; + int get currentPage; /// Elements in this page. - List/*!*/ get elements; + List get elements; /// The json key for elements. - String/*!*/ get elementsEntryKey; + String get elementsEntryKey; /// The offset of elements for the request. - int /*!*/ get elementsOffset; + int get elementsOffset; /// Current page elements length. - int /*!*/ get elementsLength; + int get elementsLength; /// Number of elements used for paging. - int/*!*/ get elementsPerPage; + int get elementsPerPage; /// Returns [true] if this is the last page. bool get isLastPage { @@ -95,11 +94,10 @@ abstract class JSONPaging extends MapDelegate { /// If this is the last page returns the last page index (the current page index). int get nextPage { var page = currentPage; - var totalPages = this.totalPages ; + var totalPages = this.totalPages; if (totalPages == null) { - return page + 1 ; - } - else { + return page + 1; + } else { var lastPageIndex = totalPages - 1; return page < lastPageIndex ? page + 1 : lastPageIndex; } @@ -109,15 +107,15 @@ abstract class JSONPaging extends MapDelegate { /// /// If [totalPages] is 1, returns false. bool get needsPaging { - var totalPages = this.totalPages ; + var totalPages = this.totalPages; return totalPages != null && totalPages != 1; } /// Paging implementation format/name. - String/*!*/ get pagingFormat; + String get pagingFormat; /// Returns [true] if [format] is the same of current [pagingFormat]. - bool isOfPagingFormat(String format) { + bool isOfPagingFormat(String? format) { if (format == null || format.isEmpty) return false; var myFormat = pagingFormat; return myFormat.trim().toLowerCase() == format.trim().toLowerCase(); @@ -125,26 +123,26 @@ abstract class JSONPaging extends MapDelegate { /// Requesting Function that is able to make new requests to a specific page. /// See [PagingRequester]. - PagingRequester pagingRequester; + PagingRequester? pagingRequester; /// The url for a request using [url] and [page] to build. String pagingRequestURL(String url, int page); - Future /*!*/ requestPage(int page) { + Future requestPage(int page) async { if (pagingRequester == null) return null; - return pagingRequester(page); + return pagingRequester!(page); } /// Requests next page. /// If [isLastPage] returns [this]. - Future /*!*/ requestNextPage() async { + Future requestNextPage() async { if (isLastPage) return this; return requestPage(nextPage); } /// Requests the previous page. /// If [isFirstPage] returns [this]. - Future /*!*/ requestPreviousPage() async { + Future requestPreviousPage() async { if (isFirstPage) return this; return requestPage(previousPage); } @@ -191,10 +189,10 @@ class ColossusPaging extends JSONPaging { int get elementsPerPage => json['ELEMENTS_PER_PAGE']; @override - int get totalElements => json['TOTAL_ELEMENTS']; + int? get totalElements => json['TOTAL_ELEMENTS']; @override - int get totalPages => json['TOTAL_PAGES']; + int? get totalPages => json['TOTAL_PAGES']; @override String get pagingFormat => 'Colossus'; @@ -204,8 +202,7 @@ class ColossusPaging extends JSONPaging { var uri = Uri.parse(url); var queryParameters = - (Map.from(uri.queryParametersAll) ?? {}) - .cast(); + Map.from(uri.queryParametersAll).cast(); var pageEntry = findKeyEntry(queryParameters, ['-PAGE', '--PAGE']); @@ -272,10 +269,10 @@ class SpringBootPaging extends JSONPaging { int get elementsPerPage => json['pageable']['pageSize']; @override - int get totalElements => json['totalElements']; + int? get totalElements => json['totalElements']; @override - int get totalPages => json['totalPages']; + int? get totalPages => json['totalPages']; @override String get pagingFormat => 'SpringBoot'; @@ -284,8 +281,7 @@ class SpringBootPaging extends JSONPaging { String pagingRequestURL(String url, int page) { var uri = Uri.parse(url); - var queryParameters = - (uri.queryParametersAll ?? {}).cast(); + var queryParameters = uri.queryParametersAll.cast(); var pageEntry = findKeyEntry(queryParameters, ['page']); diff --git a/lib/src/regexp.dart b/lib/src/regexp.dart index 84d8109..fe7d0f2 100644 --- a/lib/src/regexp.dart +++ b/lib/src/regexp.dart @@ -3,13 +3,13 @@ import 'package:swiss_knife/src/collections.dart'; /// Returns [true] if [regExp] has any match at [s]. /// /// [regExp] Uses [parseRegExp] to parse. -bool regExpHasMatch(Object/*?*/ regExp, String s) { +bool regExpHasMatch(Object? regExp, String s) { var theRegExp = parseRegExp(regExp); return theRegExp != null && theRegExp.hasMatch(s); } /// Parses [regExp] parameter to [RegExp]. -RegExp parseRegExp(Object/*?*/ regExp) { +RegExp? parseRegExp(Object? regExp) { if (regExp == null) return null; return regExp is RegExp ? regExp : RegExp(regExp.toString()); } @@ -20,7 +20,7 @@ RegExp parseRegExp(Object/*?*/ regExp) { /// /// Used by [regExpReplaceAll]. class _RegExpReplacer { - List _parts; + late List _parts; _RegExpReplacer(String replace) { var matches = RegExp(r'(?:\$(\d+)|\${(\d+)})').allMatches(replace); @@ -37,7 +37,7 @@ class _RegExpReplacer { var g1 = match.group(1); var g2 = match.group(2); - var id = g1 ?? g2; + var id = g1 ?? g2!; var groupID = int.parse(id); @@ -69,7 +69,7 @@ class _RegExpReplacer { return s; } - String replaceAll(Object/*?*/ regExp, String s) { + String replaceAll(Object? regExp, String s) { var theRegExp = parseRegExp(regExp); return theRegExp != null ? s.replaceAllMapped(theRegExp, replaceMatch) : s; } @@ -78,16 +78,16 @@ class _RegExpReplacer { /// Uses [regExp] to replace matches at [s], substituting with [replace]. /// /// [replace] accepts use of `$1`, `$2` or `${1}`, `${2}` as group place holders. -String regExpReplaceAll(Object/*?*/ regExp, String s, String replace) { +String regExpReplaceAll(Object? regExp, String s, String replace) { var theRegExp = parseRegExp(regExp); return theRegExp != null ? _RegExpReplacer(replace).replaceAll(regExp, s) : s; } /// Uses [regExp] to replace matches at [s], substituting with [replace] Function results. String regExpReplaceAllMapped( - Object/*?*/ regExp, String s, String Function(Match match) replace) { + Object? regExp, String s, String Function(Match match) replace) { var theRegExp = parseRegExp(regExp); - return theRegExp != null ? s.replaceAllMapped(theRegExp, replace) : s ; + return theRegExp != null ? s.replaceAllMapped(theRegExp, replace) : s; } /// Builds a [RegExp] using a dialect of words ([Map] parameter [dialectWords]). @@ -109,17 +109,16 @@ RegExp regExpDialect(Map dialectWords, String pattern, /// Represents a dialect. Compiles it on construction. class RegExpDialect { - Map/*!*/ _dialect; + late final Map _dialect; - final bool/*!*/ multiLine; + final bool multiLine; - final bool/*!*/ caseSensitive; + final bool caseSensitive; RegExpDialect(Map dialect, {this.multiLine = false, this.caseSensitive = true, - bool/*!*/ throwCompilationErrors = true}) - { + bool throwCompilationErrors = true}) { _dialect = _compile(dialect, throwCompilationErrors); } @@ -128,9 +127,9 @@ class RegExpDialect { /// Returns a copy of this instance with parameters [multiLine] and [caseSensitive]. /// If this instance already have the same parameters returns this instance. RegExpDialect withParameters( - {bool/*?*/ multiLine = false, - bool/*?*/ caseSensitive = true, - bool/*!*/ throwCompilationErrors = true}) { + {bool? multiLine = false, + bool? caseSensitive = true, + bool throwCompilationErrors = true}) { multiLine ??= this.multiLine; caseSensitive ??= this.caseSensitive; @@ -146,8 +145,10 @@ class RegExpDialect { return RegExpDialect._(_dialect, multiLine, caseSensitive); } - static RegExpDialect/*?*/ from(Object/*?*/ dialect, - {bool/*?*/ multiLine, bool/*?*/ caseSensitive, bool/*?*/ throwCompilationErrors}) { + static RegExpDialect? from(Object? dialect, + {bool multiLine = false, + bool caseSensitive = true, + bool throwCompilationErrors = true}) { if (dialect == null) return null; if (dialect is RegExpDialect) { @@ -158,7 +159,7 @@ class RegExpDialect { } if (dialect is Map) { - var map = asMapOfString(dialect); + var map = asMapOfString(dialect)!; return RegExpDialect(map, multiLine: multiLine, caseSensitive: caseSensitive, @@ -168,10 +169,8 @@ class RegExpDialect { return null; } - Map/*!*/ _compile( - Map/*!*/ dialect, bool/*!*/ throwCompilationErrors) { - throwCompilationErrors ??= true; - + Map _compile( + Map dialect, bool throwCompilationErrors) { for (var i = 0; i < 20; i++) { var words2 = dialect.map((k, v) => MapEntry( k, _compileWordPatternAndSaveErrors(dialect, k, v)?.pattern ?? '')); @@ -197,11 +196,11 @@ class RegExpDialect { List get errorWords => _errors.keys.toList(); - String getWordErrorMessage(String word) => _errors[word]?.first; + String? getWordErrorMessage(String word) => _errors[word]?.first; - String getWordErrorPattern(String word) => _errors[word]?.last; + String? getWordErrorPattern(String word) => _errors[word]?.last; - RegExp _compileWordPatternAndSaveErrors( + RegExp? _compileWordPatternAndSaveErrors( Map dialect, String word, String pattern) { try { return _compileWordPattern(dialect, pattern); @@ -220,7 +219,7 @@ class RegExpDialect { if (mark == r'\$') return '$mark$key'; - var value = words[key]; + var value = words[key!]; return value ?? '$mark$key'; }); return RegExp(translated, @@ -232,7 +231,7 @@ class RegExpDialect { final Map _wordsPatterns = {}; /// Returns [RegExp] pattern for [word]. Will cache [RegExp] instances. - RegExp getWordPattern(String word) { + RegExp? getWordPattern(String? word) { if (word == null) return null; var regexp = _wordsPatterns[word]; if (regexp != null) return regexp; @@ -284,8 +283,8 @@ final RegExp STRING_PLACEHOLDER_PATTERN = RegExp(r'{{(/?\w+(?:/\w+)*/?)}}'); /// Builds a string using as place holders in the format `{{key}}` /// from [parameters] and [extraParameters]. -String/*?*/ buildStringPattern(String/*?*/ pattern, Map/*?*/ parameters, - [List/*?*/ extraParameters]) { +String? buildStringPattern(String? pattern, Map? parameters, + [List? extraParameters]) { if (pattern == null) return null; return replaceStringMarks(pattern, STRING_PLACEHOLDER_PATTERN, (varName) { @@ -301,7 +300,7 @@ String/*?*/ buildStringPattern(String/*?*/ pattern, Map/*?*/ parameters, if (val == null && extraParameters != null) { for (var parameters2 in extraParameters) { - if (parameters2 != null && parameters2.isNotEmpty) { + if (parameters2.isNotEmpty) { val = findKeyPathValue(parameters2, varName); if (val != null) break; } @@ -316,8 +315,8 @@ String/*?*/ buildStringPattern(String/*?*/ pattern, Map/*?*/ parameters, /// /// [marksPattern] A [RegExp] with the mark pattern and a 1 group with the mark name. /// [markResolver] Resolves mark name (from [marksPattern] group(1)) to a value to replace the [marksPattern] match. -String replaceStringMarks(String/*?*/ s, RegExp/*!*/ marksPattern, - String/*!*/ Function(String/*!*/ markName)/*!*/ markResolver) { +String? replaceStringMarks(String? s, RegExp marksPattern, + String Function(String markName) markResolver) { if (s == null) return null; var matches = marksPattern.allMatches(s); @@ -329,7 +328,7 @@ String replaceStringMarks(String/*?*/ s, RegExp/*!*/ marksPattern, var prev = s.substring(pos, match.start); strFilled += prev; - var markName = match.group(1); + var markName = match.group(1)!; var val = markResolver(markName); diff --git a/lib/src/resource.dart b/lib/src/resource.dart index 273f0f0..a7bd63a 100644 --- a/lib/src/resource.dart +++ b/lib/src/resource.dart @@ -9,7 +9,7 @@ class ResourceContentCache { int get size => _resources.length; - bool contains(Object/*?*/ resource) { + bool contains(Object? resource) { return get(resource) != null; } @@ -19,10 +19,10 @@ class ResourceContentCache { /// prioritize it and return it. /// /// [resource] can be of type [Resource], [ResourceContent], [Uri] or Uri string. - ResourceContent/*?*/ get(Object/*?*/ resource) { + ResourceContent? get(Object? resource) { if (resource == null) return null; - var resourceContent = ResourceContent.from(resource); + var resourceContent = ResourceContent.from(resource)!; var cacheKey = _cacheKey(resourceContent); if (cacheKey == null) return resourceContent; @@ -48,10 +48,10 @@ class ResourceContentCache { /// Remove a [ResourceContent] associated with [resource]. /// See [get] for [resource] description. - ResourceContent remove(Object/*?*/ resource) { + ResourceContent? remove(Object? resource) { if (resource == null) return null; - var resourceContent = ResourceContent.from(resource); + var resourceContent = ResourceContent.from(resource)!; var cacheKey = _cacheKey(resourceContent); if (cacheKey == null) return resourceContent; @@ -60,12 +60,12 @@ class ResourceContentCache { return cached; } - String _cacheKey(ResourceContent resourceContent) { + String? _cacheKey(ResourceContent resourceContent) { var uri = resourceContent.uri; if (uri != null) return uri.toString(); if (resourceContent.hasContent) { - var content = resourceContent.getContentIfLoaded()/*!*/; + var content = resourceContent.getContentIfLoaded()!; String init; String end; @@ -99,10 +99,10 @@ class ResourceContentCache { /// Represents a Resource Content class ResourceContent { /// The resource (with [Uri]). - final Resource/*?*/ resource; + final Resource? resource; /// The resolved content/body. - String/*?*/ _content; + String? _content; ResourceContent(this.resource, [this._content]) { if (resource == null && _content == null) { @@ -113,7 +113,7 @@ class ResourceContent { /// Constructor with [Resource] from [uri]. /// /// [content] in case of content/body is already resolved. - static ResourceContent/*?*/ fromURI(Object/*?*/ uri, [String/*?*/ content]) { + static ResourceContent? fromURI(Object? uri, [String? content]) { if (uri == null && content == null) return null; if (uri is Uri) { @@ -128,22 +128,22 @@ class ResourceContent { } } - static ResourceContent/*?*/ from(Object/*?*/ rsc) { + static ResourceContent? from(Object? rsc) { if (rsc is ResourceContent) return rsc; if (rsc is Resource) return ResourceContent(rsc); return ResourceContent.fromURI(rsc); } /// Resolved [url] before instantiate [fromURI]. - static ResourceContent/*?*/ fromResolvedUrl(String/*?*/ url, - {String/*?*/ baseURL, String/*?*/ content}) { + static ResourceContent? fromResolvedUrl(String? url, + {String? baseURL, String? content}) { if (url == null) { if (content != null) return ResourceContent(null, content); return null; } var resolvedURL = resolveUri(url, baseURL: baseURL); - if (resolvedURL == null && content == null) return null; + if (content == null) return null; return ResourceContent.fromURI(resolvedURL, content); } @@ -158,10 +158,10 @@ class ResourceContent { _loadError = false; } - Future/*?*/ _readFuture; + Future? _readFuture; /// Notifies events when load is completed. - final EventStream onLoad = EventStream(); + final EventStream onLoad = EventStream(); /// Triggers content load. Future load() async { @@ -169,12 +169,12 @@ class ResourceContent { } /// Returns the content after resolve it. - Future/*!*/ getContent() async { + Future getContent() async { if (hasContent) return _content; if (resource == null) return null; - _readFuture ??= resource.readAsString().then((c) { + _readFuture ??= resource!.readAsString().then((c) { _onLoad(c, false); return c; }, onError: (e) { @@ -186,13 +186,13 @@ class ResourceContent { } /// Returns the content if [isLoaded]. - String/*?*/ getContentIfLoaded() => isLoaded ? _content : null; + String? getContentIfLoaded() => isLoaded ? _content : null; - bool/*!*/ _loaded = false; + bool _loaded = false; - bool/*!*/ _loadError = false; + bool _loadError = false; - void _onLoad(String content, bool/*!*/ loadError) { + void _onLoad(String? content, bool loadError) { _content = content; _loaded = true; _loadError = loadError; @@ -209,24 +209,24 @@ class ResourceContent { bool get hasContent => _content != null; /// The [Resource.uri]. - Uri/*?*/ get uri => resource?.uri; + Uri? get uri => resource?.uri; /// Returns [uri] file extension. - String/*?*/ get uriFileExtension { + String? get uriFileExtension { var uri = this.uri; if (uri == null) return null; return getPathExtension(uri.toString()); } /// Returns a [MimeType] based into the [uri] file name extension. - MimeType/*?*/ get uriMimeType { + MimeType? get uriMimeType { var uri = this.uri; if (uri == null) return null; return MimeType.byExtension(uri.toString()); } /// Return resolved [Uri] from [Resource.uriResolved]. - Future/*!*/ get uriResolved => resource?.uriResolved; + Future get uriResolved => resource!.uriResolved; @override bool operator ==(Object other) => @@ -244,15 +244,15 @@ class ResourceContent { } /// Resolves [url] using this [ResourceContent] as reference (base [Uri]). - Future resolveURL(String url) async { + Future resolveURL(String url) async { return resolveURLFromReference(this, url); } static final RegExp PATTERN_URL_INIT = RegExp(r'\w+://'); /// Resolves an [url] using another [ResourceContent] as [reference] (base [Uri]). - static Future resolveURLFromReference( - ResourceContent/*?*/ reference, String/*?*/ url) async { + static Future resolveURLFromReference( + ResourceContent? reference, String? url) async { if (url == null) return null; url = url.trim(); @@ -266,9 +266,9 @@ class ResourceContent { if (url.startsWith('./')) { var uri = reference != null ? await reference.uriResolved : null; - uri ??= await ResourceContent.fromURI('./').uriResolved; + uri ??= await ResourceContent.fromURI('./')!.uriResolved; - var uriPath = Uri.decodeComponent(uri.path) + '/'; + var uriPath = Uri.decodeComponent(uri!.path) + '/'; var uriPathParts = uriPath.split('/'); if (uriPath.endsWith('/')) uriPathParts.removeLast(); @@ -290,10 +290,10 @@ class ResourceContent { path: resolvedPath); } else if (url.startsWith('/')) { var uri = reference != null ? await reference.uriResolved : null; - uri ??= await ResourceContent.fromURI('./').uriResolved; + uri ??= await ResourceContent.fromURI('./')!.uriResolved; return Uri( - scheme: uri.scheme, + scheme: uri!.scheme, userInfo: uri.userInfo, host: uri.host, port: uri.port, @@ -305,15 +305,15 @@ class ResourceContent { } /// Wraps a resource and the related context. -class ContextualResource> +class ContextualResource> implements Comparable> { /// The resource associated with [context]. final T resource; /// The contexts, that implements [Comparable]. - final C/*?*/ context; + final C? context; - static S/*?*/ _resolveContext(T resource, dynamic context) { + static S? _resolveContext(T resource, dynamic context) { if (context == null) return null; if (context is S) { @@ -350,31 +350,23 @@ class ContextualResource> var c1 = context; var c2 = other.context; if (c1 != null && c2 == null) { - return -1 ; - } - else if (c1 == null && c2 != null) { - return 1 ; - } - else if (c1 == null && c2 == null) { - return 0 ; - } - else { - return c1.compareTo(c2); + return -1; + } else if (c1 == null && c2 != null) { + return 1; + } else if (c1 == null && c2 == null) { + return 0; + } else { + return c1!.compareTo(c2!); } } int compareContext(C c2) { var c1 = context; - if (c1 != null && c2 == null) { - return -1 ; - } - else if (c1 == null && c2 != null) { - return 1 ; - } - else if (c1 == null && c2 == null) { - return 0 ; - } - else { + if (c1 != null) { + return -1; + } else if (c1 == null) { + return 1; + } else { return c1.compareTo(c2); } } @@ -385,12 +377,12 @@ class ContextualResource> } /// Resolves a resource based into a context, like screen dimension or OS. -class ContextualResourceResolver> { +class ContextualResourceResolver> { /// The context comparator, to overwrite default comparator of [C]. - final Comparator/*?*/ contextComparator; + final Comparator? contextComparator; ContextualResourceResolver( - {Map resources, + {Map? resources, this.contextComparator, this.defaultContext, this.defaultResource}) { @@ -400,9 +392,9 @@ class ContextualResourceResolver> { var v = entry.value; if (v is ContextualResource) { - add(k, [v]); + add(k, [v as ContextualResource]); } else if (v is Iterable) { - add(k, v); + add(k, v as Iterable>); } else if (v is Function) { var val = v(); addDynamic(k, val); @@ -424,13 +416,13 @@ class ContextualResourceResolver> { } /// Adds a resources with a dynamic [value]. - void addDynamic(String key, Object value, - [ContextualResource Function(Object value)/*?*/ mapper]) { + void addDynamic(String key, Object? value, + [ContextualResource Function(Object? value)? mapper]) { if (value is ContextualResource) { if (mapper != null) { value = mapper(value); } - add(key, [value]); + add(key, [value as ContextualResource]); } else if (value is Iterable) { for (var e in value) { if (mapper != null) { @@ -463,36 +455,36 @@ class ContextualResourceResolver> { } /// The default resource to return when is not possible to resolve one. - ContextualResource/*?*/ defaultResource; + ContextualResource? defaultResource; /// The default context to be used when resolve is called without one. - C defaultContext; + C? defaultContext; /// Resolves a resource. - T resolve(String key, [C/*?*/ context]) { + T? resolve(String key, [C? context]) { var options = _resources[key]; if (isEmptyObject(options)) return defaultResource?.resource; context ??= defaultContext; - if (context == null) { /*!!!*/ - return (defaultResource ?? options.first)?.resource; + if (context == null) { + return (defaultResource ?? options!.first).resource; } var sortedOptions = _resourcesSorted.putIfAbsent(key, () { - var list = options.toList(); + var list = options!.toList(); list.sort(); return list; }); - return _getResource(sortedOptions, context)?.resource; + return _getResource(sortedOptions, context).resource; } ContextualResource _getResource( - List>/*!*/ options, C/*!*/ context) { + List> options, C context) { var low = 0; var high = options.length - 1; - var comparator = contextComparator; + var comparator = contextComparator as int Function(C?, C)?; while (low <= high) { var mid = (low + high) ~/ 2; @@ -515,7 +507,7 @@ class ContextualResourceResolver> { } /// Returns a resolved resource using [defaultContext]. - T operator [](String key) => resolve(key); + T? operator [](String key) => resolve(key); @override String toString() { diff --git a/lib/src/string.dart b/lib/src/string.dart index 8e62015..6fdc3a0 100644 --- a/lib/src/string.dart +++ b/lib/src/string.dart @@ -1,12 +1,12 @@ import 'math.dart'; /// Returns [true] if [c] is a blank char (space, \t, \n, \r). -bool isBlankChar(String /*?*/ c) { +bool isBlankChar(String? c) { return c == ' ' || c == '\n' || c == '\t' || c == '\r'; } /// Returns ![isBlankChar]. -bool isNonBlankChar(String /*?*/ c) { +bool isNonBlankChar(String? c) { return !isBlankChar(c); } @@ -16,7 +16,7 @@ final int _codeUnit_r = '\r'.codeUnitAt(0); final int _codeUnit_t = '\t'.codeUnitAt(0); /// Returns [true] if [c] is a blank char code unit. -bool isBlankCodeUnit(int /*!*/ c) { +bool isBlankCodeUnit(int c) { return c == _codeUnit_space || c == _codeUnit_n || c == _codeUnit_t || @@ -24,22 +24,22 @@ bool isBlankCodeUnit(int /*!*/ c) { } /// Returns ![isBlankCodeUnit]. -bool isNotBlankCodeUnit(int /*!*/ c) { +bool isNotBlankCodeUnit(int c) { return !isBlankCodeUnit(c); } /// Returns [true] if [s] has a blank character. -bool hasBlankChar(String /*!*/ s) { +bool hasBlankChar(String s) { return hasBlankCharFrom(s, 0); } /// Returns [true] if [s] has a blank character from [offset]. -bool hasBlankCharFrom(String /*!*/ s, [int /*!*/ offset]) { +bool hasBlankCharFrom(String s, [int offset = 0]) { return hasBlankCharInRange(s, offset, s.length - offset); } /// Returns [true] if [s] has a blank character in range [offset]+[length]. -bool hasBlankCharInRange(String /*!*/ s, int /*!*/ offset, int /*!*/ length) { +bool hasBlankCharInRange(String s, int offset, int length) { if (length <= 0) return false; var end = Math.min(s.length, offset + length); @@ -53,12 +53,12 @@ bool hasBlankCharInRange(String /*!*/ s, int /*!*/ offset, int /*!*/ length) { } /// Returns [true] if [s] has only blank characters. -bool isBlankString(String /*!*/ s, [int /*!*/ offset = 0]) { +bool isBlankString(String s, [int offset = 0]) { return isBlankStringInRange(s, offset, s.length - offset); } /// Returns [true] if [s] has only blank characters in range [offset]+[length]. -bool isBlankStringInRange(String /*!*/ s, int /*!*/ offset, int /*!*/ length) { +bool isBlankStringInRange(String s, int offset, int length) { if (length <= 0) return false; var end = Math.min(s.length, offset + length); @@ -79,12 +79,12 @@ final int _codeUnit_z = 'z'.codeUnitAt(0); final int _codeUnit_A = 'A'.codeUnitAt(0); final int _codeUnit_Z = 'Z'.codeUnitAt(0); -bool isDigit(int /*!*/ c) { +bool isDigit(int c) { if (c < _codeUnit_0 || c > _codeUnit_9) return false; return true; } -bool isAlphaNumeric(int /*!*/ c) { +bool isAlphaNumeric(int c) { if (c < _codeUnit_0 || c > _codeUnit_z || ((c > _codeUnit_9 && c < _codeUnit_A) || @@ -94,11 +94,11 @@ bool isAlphaNumeric(int /*!*/ c) { return true; } -bool isDigitString(String /*!*/ s, [int offset = 0]) { +bool isDigitString(String s, [int offset = 0]) { return isDigitStringInRange(s, offset, s.length - offset); } -bool isDigitStringInRange(String /*!*/ s, int offset, int length) { +bool isDigitStringInRange(String s, int offset, int length) { if (length <= 0) return false; var end = Math.min(s.length, offset + length); @@ -111,12 +111,11 @@ bool isDigitStringInRange(String /*!*/ s, int offset, int length) { return true; } -bool isAlphaNumericString(String /*!*/ s, [int offset = 0]) { +bool isAlphaNumericString(String s, [int offset = 0]) { return isAlphaNumericStringInRange(s, offset, s.length - offset); } -bool isAlphaNumericStringInRange( - String /*!*/ s, int /*!*/ offset, int /*!*/ length) { +bool isAlphaNumericStringInRange(String s, int offset, int length) { if (length <= 0) return false; var end = Math.min(s.length, offset + length); @@ -130,7 +129,7 @@ bool isAlphaNumericStringInRange( } /// Removes quotes from [String] [s] -String unquoteString(String /*!*/ s) { +String unquoteString(String s) { if (s.length <= 1) return s; if ((s.startsWith('"') && s.endsWith('"')) || diff --git a/lib/src/uri.dart b/lib/src/uri.dart index 93713d4..1e843d0 100644 --- a/lib/src/uri.dart +++ b/lib/src/uri.dart @@ -4,7 +4,7 @@ import 'package:swiss_knife/src/collections.dart'; /// /// - In the browser is the current window.location.href. /// - When not in a Browser is the current working directory. -Uri /*!*/ getUriBase() { +Uri getUriBase() { return Uri.base; } @@ -12,25 +12,25 @@ Uri /*!*/ getUriBase() { /// /// - In the browser will be current URL with `/` path. /// - When not in a Browser will be the `/` directory. -Uri /*!*/ getUriRoot() { +Uri getUriRoot() { var base = getUriBase(); return buildUri(base.scheme, base.host, base.port); } /// The scheme of base Uri. -String /*!*/ getUriBaseScheme() { +String getUriBaseScheme() { var uri = getUriBase(); return uri.scheme; } /// The host of base Uri. -String /*!*/ getUriBaseHost() { +String getUriBaseHost() { var uri = getUriBase(); return uri.host; } /// The port of base Uri. -int /*!*/ getUriBasePort() { +int getUriBasePort() { var uri = getUriBase(); return uri.port; } @@ -38,8 +38,7 @@ int /*!*/ getUriBasePort() { /// The host and port of base Uri. /// /// [suppressPort80] if true suppresses port 80 and returns only the host. -String /*!*/ getUriBaseHostAndPort( - {bool /*!*/ suppressPort80 = true, int /*?*/ port}) { +String getUriBaseHostAndPort({bool suppressPort80 = true, int? port}) { var uri = getUriBase(); port ??= uri.port; @@ -55,7 +54,7 @@ String /*!*/ getUriBaseHostAndPort( } /// Returns base Uri as URL string. -String getUriRootURL({bool /*!*/ suppressPort80 = true, int /*?*/ port}) { +String getUriRootURL({bool suppressPort80 = true, int? port}) { return getUriBaseScheme() + '://' + getUriBaseHostAndPort(suppressPort80: suppressPort80, port: port) + @@ -65,11 +64,8 @@ String getUriRootURL({bool /*!*/ suppressPort80 = true, int /*?*/ port}) { /// Builds an Uri with the parameters. /// /// [path2] appends to [path]. If starts with `/` overwrites it. -Uri buildUri(String /*?*/ scheme, String /*?*/ host, int /*?*/ port, - {String /*?*/ path, - String /*?*/ path2, - String /*?*/ queryString, - String /*?*/ fragment}) { +Uri buildUri(String? scheme, String? host, int? port, + {String? path, String? path2, String? queryString, String? fragment}) { var base = getUriBase(); if (isEmptyString(scheme)) scheme = base.scheme; @@ -233,7 +229,7 @@ Uri buildUri(String /*?*/ scheme, String /*?*/ host, int /*?*/ port, } /// Removes query string from [url] and returns an [Uri]. -Uri removeUriQueryString(String /*!*/ url) { +Uri removeUriQueryString(String url) { var uri = Uri.parse(url); var fragment = uri.fragment; return buildUri(uri.scheme, uri.host, uri.port, @@ -241,7 +237,7 @@ Uri removeUriQueryString(String /*!*/ url) { } /// Removes fragment from [url] and returns an [Uri]. -Uri removeUriFragment(String /*!*/ url) { +Uri removeUriFragment(String url) { var uri = Uri.parse(url); return buildUri(uri.scheme, uri.host, uri.port, path: uri.path, queryString: uri.query); @@ -254,12 +250,11 @@ Uri removeUriFragment(String /*!*/ url) { /// - [baseURL] Base URL to use. If is null will use [baseUri] parameter or [getUriBase] result. /// - [baseUri] Base URI to use. If is null will use [getUriBase] result. /// - If both [baseUri] and [baseURL] are null, if needed, [getUriBase] will be used. -Uri /*!*/ resolveUri(String /*!*/ url, - {String /*?*/ baseURL, Uri /*?*/ baseUri}) { +Uri resolveUri(String url, {String? baseURL, Uri? baseUri}) { url = url.trim(); var base = - baseUri ?? (isNotEmptyString(baseURL) ? Uri.parse(baseURL /*!*/) : null); + baseUri ?? (isNotEmptyString(baseURL) ? Uri.parse(baseURL!) : null); if (url.isEmpty) return base ?? getUriBase(); @@ -276,8 +271,7 @@ Uri /*!*/ resolveUri(String /*!*/ url, } /// Same as [resolveUri], but returns [Uri] as URL String. -String /*!*/ resolveURL(String /*!*/ url, - {String /*?*/ baseURL, Uri /*?*/ baseUri}) { +String resolveURL(String url, {String? baseURL, Uri? baseUri}) { var uri = resolveUri(url, baseURL: baseURL, baseUri: baseUri); return uri.toString(); } @@ -285,24 +279,24 @@ String /*!*/ resolveURL(String /*!*/ url, RegExp _REGEXP_localhost = RegExp(r'^(?:localhost|127\.0\.0\.1|0.0.0.0|::1)$'); /// Returns [true] if base Uri is localhost. See [isLocalhost]. -bool /*!*/ isUriBaseLocalhost() { +bool isUriBaseLocalhost() { var host = getUriBaseHost(); return host.isEmpty || isLocalhost(host); } -bool /*!*/ isUriBaseIP() { +bool isUriBaseIP() { var host = getUriBaseHost(); return isIPAddress(host); } /// Returns [true] if [host] is localhost (also checks for IPv4 and IPv6 addresses). -bool /*!*/ isLocalhost(String /*?*/ host) { +bool isLocalhost(String? host) { if (host == null || host.isEmpty) return false; return _REGEXP_localhost.hasMatch(host); } /// Returns [true] if is a IPv4 or IPv6 address. -bool /*!*/ isIPAddress(String /*?*/ host) { +bool isIPAddress(String? host) { return isIPv4Address(host) || isIPv6Address(host); } @@ -310,7 +304,7 @@ RegExp _REGEXP_IPv4 = RegExp( r'^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$'); /// Returns [true] if is a IPv4 address. -bool /*!*/ isIPv4Address(String /*?*/ host) { +bool isIPv4Address(String? host) { if (host == null) return false; return _REGEXP_IPv4.hasMatch(host); } @@ -319,7 +313,7 @@ RegExp _REGEXP_IPv6 = RegExp( r'^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$'); /// Returns [true] if is a IPv6 address. -bool /*!*/ isIPv6Address(String /*?*/ host) { +bool isIPv6Address(String? host) { if (host == null) return false; return _REGEXP_IPv6.hasMatch(host) || host == '::/0' || @@ -327,7 +321,7 @@ bool /*!*/ isIPv6Address(String /*?*/ host) { } /// Returns [true] if [value] represents a HTTP or HTTPS URL. -bool /*!*/ isHttpURL(dynamic /*?*/ value) { +bool isHttpURL(dynamic /*?*/ value) { if (value == null) return false; if (value is Uri) { return value.scheme == 'http' || value.scheme == 'https'; @@ -343,7 +337,7 @@ bool /*!*/ isHttpURL(dynamic /*?*/ value) { } /// Returns the File name of a [path]. -String /*?*/ getPathFileName(String /*?*/ path) { +String? getPathFileName(String? path) { if (path == null) return null; path = path.trim(); if (path.isEmpty) return null; @@ -356,7 +350,7 @@ String /*?*/ getPathFileName(String /*?*/ path) { } /// Returns [path] removing File name if present. -String /*?*/ getPathWithoutFileName(String /*?*/ path) { +String? getPathWithoutFileName(String? path) { if (path == null) return null; path = path.trim(); if (path.isEmpty) return null; @@ -369,7 +363,7 @@ String /*?*/ getPathWithoutFileName(String /*?*/ path) { } /// Returns the File extension of a [path]. -String /*?*/ getPathExtension(String /*?*/ path) { +String? getPathExtension(String? path) { if (path == null) return null; path = path.trim(); if (path.isEmpty) return null; diff --git a/lib/src/utils.dart b/lib/src/utils.dart index ee3f9cc..f9df0bd 100644 --- a/lib/src/utils.dart +++ b/lib/src/utils.dart @@ -6,14 +6,14 @@ import 'package:swiss_knife/src/collections.dart'; /// /// [delayMs] is milliseconds. If null or <= 0 won't have a delay. Future callAsync(int delayMs, Function() function) { - if (delayMs == null || delayMs <= 0) { + if (delayMs <= 0) { return Future.microtask(function); } return Future.delayed(Duration(milliseconds: delayMs), function); } /// Encodes [parameters] as a query string. -String encodeQueryString(Map parameters) { +String encodeQueryString(Map? parameters) { if (parameters == null || parameters.isEmpty) return ''; var pairs = []; @@ -29,7 +29,7 @@ String encodeQueryString(Map parameters) { } /// Decodes [queryString] to a [Map]. -Map decodeQueryString(String queryString) { +Map decodeQueryString(String? queryString) { if (queryString == null || queryString.isEmpty) return {}; var pairs = queryString.split('&'); @@ -54,10 +54,10 @@ Map decodeQueryString(String queryString) { /// Formats [s] with initial character to Upper case. String toUpperCaseInitials(String s) { - if (s == null || s.isEmpty) return s; + if (s.isEmpty) return s; return s.toLowerCase().replaceAllMapped(RegExp(r'(\s|^)(\S)'), (m) { - var m1 = m[1] /*!*/; - var m2 = m[2] /*!*/; + var m1 = m[1]!; + var m2 = m[2]!; return '$m1${m2.toUpperCase()}'; }); } @@ -73,11 +73,8 @@ String toCamelCase(String s) { /// [limit] The maximum elements to return. /// /// Note: Standard Dart split doesn't have [limit] parameter. -List /*!*/ split(String /*!*/ s, Pattern delimiter, - [int limit]) { - if (delimiter == null) { - return [s]; - } else if (delimiter is String) { +List split(String s, Pattern delimiter, [int? limit]) { + if (delimiter is String) { return _split(s, delimiter, limit); } else if (delimiter is RegExp) { return _split_RegExp(s, delimiter, limit); @@ -86,7 +83,7 @@ List /*!*/ split(String /*!*/ s, Pattern delimiter, } } -List /*!*/ _split(String /*!*/ s, String delimiter, int limit) { +List _split(String s, String delimiter, int? limit) { if (limit == null) return s.split(delimiter); if (limit == 1) return [s]; @@ -123,8 +120,7 @@ List /*!*/ _split(String /*!*/ s, String delimiter, int limit) { return parts; } -List /*!*/ _split_RegExp( - String /*!*/ s, RegExp delimiter, int limit) { +List _split_RegExp(String s, RegExp delimiter, int? limit) { if (limit == null) return s.split(delimiter); if (limit == 1) return [s]; @@ -166,18 +162,18 @@ class Parameter { Parameter(this.a); - Parameter copy() => Parameter(deepCopy(a)); + Parameter copy() => Parameter(deepCopy(a)); @override bool operator ==(Object other) => identical(this, other) || other is Parameter && isEqualsDeep(a, other.a); - int /*?*/ _hashCode; + int? _hashCode; @override int get hashCode { _hashCode ??= computeHashCode; - return _hashCode; + return _hashCode!; } int get computeHashCode => deepHashCode(a); @@ -194,7 +190,7 @@ class Parameters2 extends Parameter { Parameters2(A a, this.b) : super(a); @override - Parameters2 copy() => Parameters2(deepCopy(a), deepCopy(b)); + Parameters2 copy() => Parameters2(deepCopy(a), deepCopy(b)); @override bool operator ==(Object other) => @@ -216,7 +212,7 @@ class Parameters3 extends Parameters2 { Parameters3(A a, B b, this.c) : super(a, b); @override - Parameters3 copy() => + Parameters3 copy() => Parameters3(deepCopy(a), deepCopy(b), deepCopy(c)); @override @@ -239,7 +235,7 @@ class Parameters4 extends Parameters3 { Parameters4(A a, B b, C c, this.d) : super(a, b, c); @override - Parameters4 copy() => + Parameters4 copy() => Parameters4(deepCopy(a), deepCopy(b), deepCopy(c), deepCopy(d)); @override @@ -260,12 +256,12 @@ class Parameters4 extends Parameters3 { class CachedComputation { final R Function(T) function; - final K Function(T) keyGenerator; + final K? Function(T) keyGenerator; - CachedComputation(this.function, [K Function(T) keyGenerator]) + CachedComputation(this.function, [K Function(T)? keyGenerator]) : keyGenerator = keyGenerator ?? ((T value) => deepCopy(value as K)); - final Map _cache = {}; + final Map _cache = {}; int get cacheSize => _cache.length; @@ -274,7 +270,7 @@ class CachedComputation { _cache.clear(); } - K generateKey(T value) => keyGenerator(value); + K? generateKey(T value) => keyGenerator(value); int _computationCount = 0; diff --git a/pubspec.yaml b/pubspec.yaml index c482f76..cbe25d1 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -4,12 +4,13 @@ version: 3.0.0 homepage: https://github.com/gmpassos/swiss_knife environment: - sdk: '>=2.6.0 <3.0.0' + sdk: '>=2.12.0 <3.0.0' dependencies: intl: ^0.17.0 resource_portable: ^3.0.0 #path: ../resource_portable + collection: ^1.15.0 dev_dependencies: pedantic: ^1.11.0 diff --git a/test/swiss_knife_resource_test.dart b/test/swiss_knife_resource_test.dart index 087fe10..1cf2111 100644 --- a/test/swiss_knife_resource_test.dart +++ b/test/swiss_knife_resource_test.dart @@ -17,7 +17,7 @@ class MyResourceLoader extends ResourceLoader { } @override - Future readAsString(Uri uri, {Encoding encoding}) async { + Future readAsString(Uri uri, {Encoding? encoding}) async { return uri.toString().split('://')[1]; } } @@ -29,7 +29,7 @@ void main() { test('ResourceContent', () async { var loader = MyResourceLoader(); var resourceContent = - ResourceContent.from(Resource('test://foo', loader: loader)); + ResourceContent.from(Resource('test://foo', loader: loader))!; expect(resourceContent.isLoaded, isFalse); @@ -79,11 +79,11 @@ void main() { var cache = ResourceContentCache(); var resourceContent = - ResourceContent.from(Resource('test://foo', loader: loader)); + ResourceContent.from(Resource('test://foo', loader: loader))!; expect(resourceContent.isLoaded, isFalse); - var resourceContentCached = cache.get(resourceContent); + var resourceContentCached = cache.get(resourceContent)!; expect(await resourceContentCached.getContent(), 'foo'); diff --git a/test/swiss_knife_test.dart b/test/swiss_knife_test.dart index 3109f63..0b71af7 100644 --- a/test/swiss_knife_test.dart +++ b/test/swiss_knife_test.dart @@ -77,7 +77,7 @@ void main() { equals(MapEntry('Aa', 11).toString())); expect(getIgnoreCase({'Aa': 11, 'b': 22}, 'aa'), equals(11)); - expect(getEntryIgnoreCase({'Aa': 11, 'b': 22}, 'aa').value, equals(11)); + expect(getEntryIgnoreCase({'Aa': 11, 'b': 22}, 'aa')!.value, equals(11)); { var map = {'Aa': 11.0, 'b': 22}; @@ -180,7 +180,8 @@ void main() { ] }; - deepReplaceValues(deepObj2, (c, k, v) => k == 'id', (c, k, v) => (v as int) * 10); + deepReplaceValues( + deepObj2, (c, k, v) => k == 'id', (c, k, v) => (v as int) * 10); expect( isEqualsDeep(deepObj2, { @@ -413,11 +414,16 @@ void main() { expect(formatPercent(3.3), equals('3.3%')); expect(formatPercent(0.33, precision: 2, isRatio: true), equals('33%')); - expect(formatPercent(0.333, precision: 2, isRatio:true), equals('33.30%')); - expect(formatPercent(0.3333, precision: 2, isRatio:true), equals('33.33%')); - expect(formatPercent(1 / 3, precision: 2, isRatio:true), equals('33.33%')); - expect(formatPercent(1 / 3, precision: 3, isRatio:true), equals('33.333%')); - expect(formatPercent(1 / 3, precision: 4, isRatio:true), equals('33.3333%')); + expect( + formatPercent(0.333, precision: 2, isRatio: true), equals('33.30%')); + expect( + formatPercent(0.3333, precision: 2, isRatio: true), equals('33.33%')); + expect( + formatPercent(1 / 3, precision: 2, isRatio: true), equals('33.33%')); + expect( + formatPercent(1 / 3, precision: 3, isRatio: true), equals('33.333%')); + expect(formatPercent(1 / 3, precision: 4, isRatio: true), + equals('33.3333%')); expect(formatPercent(33), equals('33%')); expect(formatPercent(33.3), equals('33.3%')); @@ -455,8 +461,8 @@ void main() { expect(clipNumber(2, 10, 20), equals(10)); expect(clipNumber(30, 10, 20), equals(20)); - expect(clipNumber(null, 10, 20, 15), equals(15)); - expect(clipNumber(null, 10, 20, 150), equals(20)); + expect(clipNumber(null, 10, 20, 15), equals(15)); + expect(clipNumber(null, 10, 20, 150), equals(20)); }); test('isPositiveNumber', () { @@ -478,13 +484,13 @@ void main() { }); test('Scale', () { - var s1 = Scale.from([10, -10, 20, 5]); + var s1 = Scale.from([10, -10, 20, 5])!; expect(s1.minimum, equals(-10)); expect(s1.maximum, equals(20)); expect(s1.length, equals(30)); - var s2 = ScaleNum.from([10, -10, 20, 5]); + var s2 = ScaleNum.from([10, -10, 20, 5])!; expect(s2.minimum, equals(-10)); expect(s2.maximum, equals(20)); @@ -518,10 +524,10 @@ void main() { equals(true)); expect( - DataURLBase64.parse('data:text/plain;base64,$textBase64') + DataURLBase64.parse('data:text/plain;base64,$textBase64')! .payloadBase64, equals(textBase64)); - expect(DataURLBase64.parse('data:text/plain;base64,$textBase64').payload, + expect(DataURLBase64.parse('data:text/plain;base64,$textBase64')!.payload, equals(text)); }); @@ -709,7 +715,7 @@ void main() { var dialect = RegExpDialect.from({ 's': '[ \t]', 'commas': ',+', - }, multiLine: false, caseSensitive: false); + }, multiLine: false, caseSensitive: false)!; expect(dialect.hasErrors, isFalse); @@ -725,7 +731,10 @@ void main() { var dialect = RegExpDialect.from({ 's': '[ \t', 'commas': ',+', - }, multiLine: false, caseSensitive: false, throwCompilationErrors: false); + }, + multiLine: false, + caseSensitive: false, + throwCompilationErrors: false)!; expect(dialect.hasErrors, isTrue); @@ -1112,21 +1121,24 @@ void main() { }); test('listMatchesAll/listNotMatchesAll', () { - expect(listMatchesAll(null, (e) => e == 1), equals(false)); - expect(listMatchesAll([], (e) => e == 1), equals(false)); + expect(listMatchesAll(null, (dynamic e) => e == 1), equals(false)); + expect(listMatchesAll([], (dynamic e) => e == 1), equals(false)); - expect(listMatchesAll([1, 1, 1], (e) => e == 1), equals(true)); - expect(listMatchesAll([1, 0, 1], (e) => e == 1), equals(false)); - expect(listMatchesAll([1, 1, 1], (e) => e == 0), equals(false)); - expect(listMatchesAll([1, 1, null, 1], (e) => e == 0), equals(false)); + expect(listMatchesAll([1, 1, 1], (dynamic e) => e == 1), equals(true)); + expect(listMatchesAll([1, 0, 1], (dynamic e) => e == 1), equals(false)); + expect(listMatchesAll([1, 1, 1], (dynamic e) => e == 0), equals(false)); + expect(listMatchesAll([1, 1, null, 1], (dynamic e) => e == 0), + equals(false)); - expect(listNotMatchesAll(null, (e) => e == 1), equals(false)); - expect(listNotMatchesAll([], (e) => e == 1), equals(false)); + expect(listNotMatchesAll(null, (dynamic e) => e == 1), equals(false)); + expect(listNotMatchesAll([], (dynamic e) => e == 1), equals(false)); - expect(listNotMatchesAll([1, 1, 1], (e) => e == 1), equals(false)); - expect(listNotMatchesAll([1, 0, 1], (e) => e == 1), equals(true)); - expect(listNotMatchesAll([1, 1, 1], (e) => e == 0), equals(true)); - expect(listNotMatchesAll([1, 1, null, 1], (e) => e == 0), equals(true)); + expect( + listNotMatchesAll([1, 1, 1], (dynamic e) => e == 1), equals(false)); + expect(listNotMatchesAll([1, 0, 1], (dynamic e) => e == 1), equals(true)); + expect(listNotMatchesAll([1, 1, 1], (dynamic e) => e == 0), equals(true)); + expect(listNotMatchesAll([1, 1, null, 1], (dynamic e) => e == 0), + equals(true)); expect(isListValuesAllEquals([3, 3, 3, 3, 3], 3), equals(true)); expect(isListValuesAllEquals([3, 3, 3, 3, 3]), equals(true)); @@ -1353,7 +1365,7 @@ void main() { test('getDateTimeStartOf/EndOf', () { var cachedComputation = CachedComputation, int>, Parameters2, int>>((v) { - return sumIterable(v.a.map((n) => n * v.b)); + return sumIterable(v.a.map((n) => n * v.b)) as int; }); expect(cachedComputation.cacheSize, equals(0)); diff --git a/test/swiss_knife_tree_reference_test.dart b/test/swiss_knife_tree_reference_test.dart index 740f7d7..4930da8 100644 --- a/test/swiss_knife_tree_reference_test.dart +++ b/test/swiss_knife_tree_reference_test.dart @@ -1,16 +1,17 @@ +import 'package:collection/collection.dart' show IterableExtension; import 'package:swiss_knife/src/collections.dart'; import 'package:test/test.dart'; class MyNode { - MyNode _parent; + MyNode? _parent; - MyNode get parent => _parent; + MyNode? get parent => _parent; - Set children = {}; + final Set children = {}; String text; - MyNode(this.text, {List children}) { + MyNode(this.text, {List? children}) { if (children != null) { for (var child in children) { add(child); @@ -32,10 +33,10 @@ class MyNode { class MyTree extends TreeReferenceMap { MyTree( root, { - bool autoPurge, - bool keepPurgedKeys, - Duration purgedEntriesTimeout, - int maxPurgedEntries, + bool autoPurge = false, + bool keepPurgedKeys = false, + Duration? purgedEntriesTimeout, + int? maxPurgedEntries, }) : super(root, autoPurge: autoPurge, keepPurgedKeys: keepPurgedKeys, @@ -43,15 +44,14 @@ class MyTree extends TreeReferenceMap { maxPurgedEntries: maxPurgedEntries); @override - MyNode getParentOf(MyNode key) => key?.parent; + MyNode? getParentOf(MyNode key) => key.parent; @override bool isChildOf(MyNode parent, MyNode child, bool deep) { - if (parent == null || child == null) return false; - if (deep ?? false) { + if (deep) { if (parent.children.contains(child)) return true; - var found = parent.children - .firstWhere((e) => isChildOf(e, child, true), orElse: () => null); + var found = + parent.children.firstWhereOrNull((e) => isChildOf(e, child, true)); return found != null; } else { return parent.children.contains(child); @@ -59,7 +59,7 @@ class MyTree extends TreeReferenceMap { } @override - Iterable getChildrenOf(MyNode key) => key?.children?.toList(); + Iterable getChildrenOf(MyNode key) => key.children.toList(); } void main() { @@ -100,11 +100,11 @@ void main() { expect(tree.get(b21), equals('B21')); expect(tree.get(c), equals('C')); - expect(tree.getParentKey(a).text, equals('root')); - expect(tree.getParentKey(b).text, equals('root')); - expect(tree.getParentKey(b1).text, equals('b')); - expect(tree.getParentKey(b2).text, equals('b')); - expect(tree.getParentKey(b21).text, equals('b')); + expect(tree.getParentKey(a)!.text, equals('root')); + expect(tree.getParentKey(b)!.text, equals('root')); + expect(tree.getParentKey(b1)!.text, equals('b')); + expect(tree.getParentKey(b2)!.text, equals('b')); + expect(tree.getParentKey(b21)!.text, equals('b')); expect(tree.getParentValue(a), equals('ROOT')); expect(tree.getParentValue(b), equals('ROOT'));