add method Null safety
- T element
Add a single element
to the collection.
Returns true if the addition was successful. In case of failure it will either return false (if sortingEnforcement == SortingEnforcement.skipWrongItems) or it will throw GpsPointsViewSortingException (if sortingEnforcement == SortingEnforcement.throwIfWrongItems).
Implementation
bool add(T element) {
try {
// [GpcCompact] and subclasses have very fast comparison operations for
// items that are in the list. It is therefore cheaper to not first check
// if the new item is valid, but rather add it to the list, check if that
// makes the list invalid, and rollback if necessary. This is of course
// for the common case where additions are typically valid, because if
// incoming data is mostly invalid the add-and-rollback combo may be more
// expensive.
add_Unsafe(element);
// For the non-empty list, we need to take into consideration sorting
// requirements.
if (length <= 1) {
return true;
} else {
// If it's already not sorted by time, we don't have to check anything, so
// only do further checks if currently sorted.
if (sortedByTime) {
final comparison = compareElementTime(length - 2, length - 1);
switch (comparison) {
case TimeComparisonResult.before:
return true;
case TimeComparisonResult.same:
case TimeComparisonResult.after:
case TimeComparisonResult.overlapping:
// Disallow adding unsorted item if configured to force sorting.
if (sortingEnforcement != SortingEnforcement.notRequired) {
throw GpsPointsViewSortingException(
'Adding element ${this[length - 1]} after ${this[length - 2]} would make the list unsorted!');
}
_sortedByTime = false;
return true;
}
}
}
} on GpsPointsViewSortingException {
rollbackAddingLastItem();
if (sortingEnforcement == SortingEnforcement.throwIfWrongItems) {
rethrow;
} // otherwise we just skip the item, silently
return false;
}
return false;
}