- Unified Paginator: Introduced
BasePaginator<T>
for shared logic and a singleInfinitePaginator
to handle both page-based and cursor-based infinite scrolling through factory constructors. - Improved
AsyncPaginator
: Now usesCancelableOperation
to optionally cancel in-flight requests whenautoCancelFetches
is true, preventing race conditions. - Enhanced Caching: A consistent
_CacheEntry
class now stores eitherPaginator<T>
orList<T>
with expiration checks for both sync and async paginators. - Analytics: Added
PaginationAnalytics
mixin to track page loads, errors, and cache hits.
- New
StringSimilarity
Utility: Added with algorithms likediceCoefficient
,levenshteinDistance
,jaro
,jaroWinkler
, andcosine
. String
Extension:compareWith
method for quick similarity comparisons.
Added new Debouncer
class for function execution control:
- Configurable delay and max wait times
- Support for sync/async functions
- Real-time state monitoring via stream
- Optional execution history tracking
- Error handling with customizable callbacks
- Debug logging capabilities
- Methods: run(), flush(), cancel(), runIfNotPending()
- State inspection: remainingTime, executionCount, etc.
sqrt()
: Added to numeric extensions for square root calculations.
- HTTP Status Code Helpers:
- Added
isOkCode
,isCreatedCode
,isAcceptedCode
,isNoContentCode
,isTemporaryRedirect
,isPermanentRedirect
,isAuthenticationError
,isValidationError
,isRateLimitError
,isTimeoutError
,isConflictError
,isNotFoundError
, andisRetryableError
. - Added
statusCodeRetryDelay
for suggested retry durations. - Added
toHttpStatusUserMessage
andtoHttpStatusDevMessage
for user-friendly and developer-specific messages. isSuccessCode
now checks for all 2xx codes (not just 200 and 201).
- Added
- Refactored for Consistency:
- Removed generic
delay()
on numbers. Use specific duration methods instead (e.g.,1.secondsDelay()
,5.minutesDelay()
). - All delay methods now support typed computations.
- Converted getter delays to methods and used more descriptive names.
- Removed generic
- Added
isBetween
for date range checks.
- HTTP Status Messages: Added
httpStatusUserMessage
(user-friendly) andhttpStatusDevMessage
(technical) for explanations and troubleshooting hints. - cssColorNamesToArgb: Maps CSS color names to their corresponding ARGB values. e.g.
cssColorNamesToArgb['red']
returns0xFFFF0000
.
- See the Migration Guide for upgrading instructions.
- Introduced a new
Object
extension for converting objects into all supported types provided by theConvertObject
class.
-
Introduced
formatAsReadableNumber
onnum
for customizable number formatting.- Supports locale-based formatting.
- Allows custom grouping and decimal separators.
- Includes options for trimming trailing zeros and setting decimal precision.
-
Fixed
toFullDayName
on num.
- Fixed a bug in the
num
extension'ssafeDivide
function where optional parameters were not being passed to theNumbersHelper
's method.
Added nullIfBlank
getter in the String Extension:
- Returns the string itself if it is not blank (non-empty and contains non-whitespace characters) "Hello".nullIfBlank; // Output: "Hello" " ".nullIfBlank; // Output: null
-
New Pagination Classes:
Paginator
: For synchronous pagination.AsyncPaginator
: Supports asynchronous pagination.InfinitePaginator
: Enables infinite scrolling pagination.
-
New Constants:
- Greek Number Suffixes:
greekNumberSuffixes
: Suffixes for large numbers, such asK
,M
,B
, representing thousands, millions, billions, etc.
- Roman Numerals:
romanNumerals
: Maps integers to Roman numerals, includingI
,V
,X
,L
,C
,D
,M
.
- Weekdays:
smallWeekdays
andfullWeekdays
: Maps integers to abbreviated (Mon
,Tue
, etc.) and full weekday names (Monday
,Tuesday
, etc.).
- Months:
smallMonthsNames
andfullMonthsNames
: Maps integers to abbreviated (Jan
,Feb
, etc.) and full month names (January
,February
, etc.).
- Time Durations:
oneSecond
,oneMinute
,oneHour
,oneDay
: Constants for handling standard time durations.
- Milliseconds Constants for precise time calculations:
millisecondsPerSecond
,millisecondsPerMinute
,millisecondsPerHour
,millisecondsPerDay
.
- Regular Expressions:
- Patterns for alphanumeric validation, special characters, usernames, currency, phone numbers, emails, IPv4, IPv6, URLs, and numeric/alphabet-only entries.
- HTTP Status Messages:
httpStatusMessages
: A map of HTTP status codes to their corresponding messages, from100
(Continue) to599
(Network Connect Timeout Error).
- Greek Number Suffixes:
-
New DateTime Extension Method:
calculateAge()
: Calculates age from a date, with leap year consideration.
-
New Numerical Utilities:
- Number Checks and Conversions:
safeDivide
: Safely divides two numbers with custom handling for division by zero.roundToNearestMultiple
,roundUpToMultiple
,roundDownToMultiple
: Rounds numbers to specified multiples.isBetween
: Checks if a number is within a specified range.toCurrency
,toPercent
,toFractionString
: Converts numbers to currency, percentage, or fraction formats.isApproximatelyEqual
,isCloseTo
: Compares numbers with tolerance.scaleBetween
: Normalizes a number between specified minimum and maximum values.isInteger
: Checks if a number is an integer.factorial
,gcd
,lcm
: Calculates factorial, greatest common divisor, and least common multiple.isPrime
,primeFactors
: Checks for primality and calculates prime factors.toRomanNumeral
,toOrdinal
: Converts integers to Roman numerals or ordinal representation.isPerfectSquare
,isPerfectCube
,isFibonacci
: Checks if a number is a perfect square, cube, or Fibonacci number.isPowerOf
: Checks if a number is a power of another number.toBinaryString
,toHexString
,bitCount
: Converts integers to binary, hexadecimal, and counts set bits.isDivisibleBy
: Checks if an integer is divisible by another number.
- New
NumbersHelper
Class:- Provides static utilities for safe division, mean, median, mode, variance, standard deviation, and percentiles.
- Includes methods for GCD, perfect square checks, and Roman numeral to integer conversion.
- Number Checks and Conversions:
- Enhanced
tryGetX
Methods inIterable
andMap
extensions to allow alternative key lookups usingaltKeys
in methods likegetString()
,getInt()
, etc.
HttpResStatus
Enum:- Removed
HttpResStatus
enum and associated extensions, replaced by lightweight HTTP status code handling with methods liketoHttpStatusMessage
.
- Removed
- Added the
toDecimalString
method on numbers: similar totoStringAsFixed
which allows formatting numbers to a specified number of decimal places, but this one includes optional control over trailing zeros.
- The following methods in the DoublyLinkedList class now accept an optional
orElse
function to handle cases where no matching node is found:firstNodeWhere
,lastNodeWhere
, andsingleNodeWhere
firstNodeWhereOrNull
,lastNodeWhereOrNull
, andsingleNodeWhereOrNull
findNodeByElement
remainingDays
now returns negative values for dates in the past to correctly reflect the number of days remaining.passedDays
now returns 0 for dates in the future, to correctly indicate that no days have passed yet.- Note: For the previous behavior of always returning absolute day differences, use the
daysDifferenceTo
method.
- Added support for WASM.
- Added topics to pubspec.yaml.
- Renamed
castTo<R>()
toconvertTo<R>()
in List and Set extensions. - Renamed
toListCasted<R>()
&toSetCasted<R>()
totoListConverted<R>()
&toSetConverted<R>()
in the Iterable extension.- Reason: The methods perform type conversion rather than casting, which is more accurately reflected in the new names.
- Added
castTo<R>()
to the List and Set extensions andtoListCasted<R>()
&toSetCasted<R>()
to the Iterable extension. - Enhanced numeric extensions with additional date-related helpers:
- Added helpers to check if the number matches the current year, month, day of the month, or day of the week:
isCurrentYear
,isCurrentMonth
,isCurrentDay
, andisCurrentDayOfWeek
. isBetweenMonths
: Checks if a number (representing a month) falls within a specified range, handling year boundaries gracefully.
- Added helpers to check if the number matches the current year, month, day of the month, or day of the week:
- Added
isInThisMonth
in the date extension, it checks if a month of this date matches the month of now. - Updated some docs.
void main() {
final list = [1, 2, '3', '3.1', 22.3];
// Parsing a dynamic numeric list to num, int, and double.
print(list.castTo<num>()); // [1, 2, 3, 3.1, 22.3]
print(list.castTo<int>()); // [1, 2, 3, 3, 22]
print(list.castTo<double>()); // [1.0, 2.0, 3.0, 3.1, 22.3]
}
total
on Iterable<num>
: This getter computes the sum of all numeric elements within the iterable, with null
values being treated as zeros
totalBy
on Iterable<E>
: Allows you to calculate the total of a specific numeric property within the objects of
the iterable by providing a selector function.
nodesWhere
on DoublyLinkedList
The DoublyLinkedList
now includes a nodesWhere
method, which returns all
nodes that satisfy a given condition specified by the test function bool Function(Node<E>)
.
num totalPrice = productList.totalBy((product) => product?.price);
int total = [1, 2, 3].total; // 6
- Added
firstNodeWhere
,firstNodeWhereOrNull
,lastNodeWhere
,lastNodeWhereOrNull
,singleNodeWhere
,singleNodeWhereOrNull
,replaceNode
,removeNodesWhere
,swapNodes
, andreverse
to theDoublyLinkedList
class.
- Introduced
DoublyLinkedList
a doubly linked list implementation for dart.- Supports standard list operations (append, prepend, insert, remove, etc.)
- Includes convenient constructors (
filled
,generate
,from
) - Offers bidirectional traversal with
next
andprev
node references - Provides
nodes
iterable for easy access to nodes in for-loops - Fully compatible with standard Dart
for...in
loops and other collection methods
- Added
tryDecode
on anyString
which tries decodes the JSON string into a dynamic data structure, similar to the'jsonData'.decode()
but this returns null upon failure. - Enhanced all the
ConvertObject
methods. distinctBy
on Iterable: Resolved an issue where thedistinctBy
method did not correctly identify distinct elements. The method now accepts akeySelector
function for more flexible uniqueness determination.final people = [ Person('Alice', 25), Person('Bob', 30), Person('Alice', 28), // Duplicate name ]; final uniquePeople = people.distinctBy((p) => p.name); // Result: [Person('Alice', 25), Person('Bob', 30)]
This major release focuses on significantly enhancing internationalization (i18n) capabilities, expanding utility functions for maps and numbers, refining date/time manipulation, and introducing substantial improvements to type conversions.
- Extensions:
- General:
intlSelectLogic
,intlSelect
(Map)pluralize
,getPluralCategory
(Num)setAsDefaultLocale
,setAsSystemLocale
,translate
,genderSelect
,getGenderCategory
(String)
- DateFormat:
tryFormat
,format
, and various formatting methods (DateTime)dateFormat
,toDateAutoFormat
,toDateFormatted
,toDateFormattedLoose
,toDateFormattedStrict
,toDateFormattedUtc
,localeExists
(String)
- Bidi:
toBidiFormatter
(TextDirection)- Various bidi text manipulation methods (String)
- NumberFormat:
toNumFormatted
,toIntFormatted
,toDoubleFormatted
(String)formatAsCurrency
,formatAsCompact
, and various other formatting methods (Num)
- General:
- Access:
- We provided direct access to the intl common classes like
Intl
,Bidi
,BidiFormatter
,NumberFormat
, andDateFormat
. - Instead of directly exposing the
TextDirection
class (which could cause confusion with theTextDirection
enum in Flutter'sdart:ui
library), we've provided three global constants:textDirectionLTR
,textDirectionRTL
, andtextDirectionUNKNOWN
.
- We provided direct access to the intl common classes like
httpFormat
(formats this date according to RFC-1123 e.g."Thu, 1 Jan 2024 00:00:00 GMT"
)
- Added optional
startOfWeek
parameter tofirstDayOfWeek
andlastDayOfWeek
.
- Consolidated various DateTime manipulation methods for consistency and added tests.
isEqual
: checks for deep equality with other Map of the same type.isPrimitive
: checks if every Key and Value is a primitive type.setIfMissing
(add entries conditionally)update
(update values based on a condition)filter
(filter entries using predicates)keysList
,valuesList
,keysSet
,valuesSet
(get lists or sets of keys/values)
isEqual
: checks for deep equality with other iterable of the same type.isPrimitive
: checks if every element is a primitive type.
isEqual(dynamic a, dynamic b)
: Determines deep equality between two objects, including nested lists, maps,and custom types.isValuePrimitive(dynamic value)
: Checks if a given value is a primitive type (e.g.,num
,bool
,String
,DateTime
, etc.) based on its runtime type.isTypePrimitive<T>()
: Checks if a given typeT
is considered a primitive type at compile time.
- Added a new set of type-safe converters to safely extract values from
Map<K, V>
andList<E>
:getString
,getNum
,getInt
,getBigInt
,getDouble
,getBool
,getDateTime
,getUri
,getMap
,getSet
,getList
.- It also supports nullable converters such as
tryGetString
,tryGetNum
,tryGetInt
, etc. - for Map, it requires the key e.g.
map.getNum('key')
- for List, it requires the index e.g.
list.getNum(1)
- all other optionals in the
ConvertObject
class are also supported.
- Added optional
format
andlocale
parameters to numeric conversion functions (toNum
,tryToNum
,toInt
,tryToInt
,toDouble
,tryToDouble
). - Added optional
format
,locale
,autoDetectFormat
,useCurrentLocale
, andutc
parameters to datetime conversion functions (toDateTime
,tryToDateTime
). - All of these optionals are available to all static methods int he ConvertObject class, as well the global methods and the new extraction methods on the Map and Iterable.
- Fixed various minor bugs and inconsistencies in extension methods.
- Enhanced documentation.
- Added test coverage for all date related extensions, with more tests planned for the future.
- Update any code referencing
try/toDateWithFormat
to usetry/toDateFormatted
instead.
- instead of
'yyyy MM'.dateFormat
use'yyyy MM'.dateFormat()
oryyyy MM'.dateFormat('en_US')
.
- Update any code referencing
isPrimitiveType
to useisValuePrimitive
instead.
- Update any code referencing
flatJson
to useflatMap
instead.
- Fixed an issue where sets were not correctly converted to JSON-encodable lists.
- Update any code referencing these methods to use their new names.
- These methods now have an optional
startOfWeek
parameter, which may affect behavior if not explicitly specified.
- You can see the migration guide for this version from here.
- You can see all the migration guides in the GitHub repo from here.
-
New Feature: Added the
toWords
getter onString
, which converts anyString
to aList<String>
, handling complex cases more effectively than the nativesplit()
method.-
Example Usage:
print("FlutterAndDart_are-AWESOME".toWords); // [Flutter, And, Dart, are, AWESOME]
-
- String Case Conversions:
capitalizeFirstLetter
: Now only capitalizes the first letter, preserving the rest of the case.- NEW:
capitalizeFirstLowerRest
: Provides the previous behavior, capitalizing the first letter and lowercasing the rest.
-
Expanded String Case Conversions: Added comprehensive case conversion extensions:
toPascalCase
: PascalCase (UpperCamelCase).toTitleCase
: Title Case.toCamelCase
: camelCase (dromedaryCase).toSnakeCase
: snake_case (snail_case, pothole_case).toKebabCase
: kebab-case (dash-case, lisp-case, spinal-case).toScreamingSnakeCase
: SCREAMING_SNAKE_CASE (MACRO_CASE, CONSTANT_CASE, ALL_CAPS).toScreamingKebabCase
: SCREAMING-KEBAB-CASE (COBOL-CASE).toPascalSnakeCase
: Pascal_Snake_Case.toPascalKebabCase
: Pascal-Kebab-Case.toTrainCase
: Train-Case (HTTP-Header-Case).toCamelSnakeCase
: camel_Snake_Case.toCamelKebabCase
: camel-Kebab-Case.toDotCase
: dot.case.toFlatCase
: flatcase.toScreamingCase
: SCREAMINGCASE (UPPERCASE).
-
Nullable String Handling: Added extensions for case conversion of nullable strings:
lowercaseFirstLetter
: Lowercases only the first letter of the string, preserving the rest of the case.capitalizeFirstLowerRest
: Capitalizes the first letter of the string and lowers the rest.tryToLowerCase
: same as the nativetoLowerCase()
but for nullable strings.tryToUpperCase
same as the nativetoUpperCase()
but for nullable strings.
-
String Utility:
isBlank
: Alias forisEmptyOrNull
, checks if a string is null, empty, or solely whitespace.
- Updated the README.
Initial release of dart_helper_utils
, which includes all the Dart
utilities from flutter_helper_utils
up to version
4.1.0
ConvertObject
class now accepts raw JSON strings forList
,Set
, andMap
conversions, e.g.,tryToList<int>("[1,2,3]")
.- New
TimeUtils
class for measuring and comparing execution times, with methods like:executionDuration
: Calculates the duration of a task (synchronous or asynchronous).executionDurations
: Measures execution times for a list of tasks.compareExecutionTimes
: Compares the execution durations of two tasks.throttle
: Creates a throttled function that invokes the function at most once per specified interval.runPeriodically
: Executes a function periodically with a given interval.runWithTimeout
: Executes a function with a timeout, cancelling if it exceeds the specified duration.
- Future updates and feature changes for Dart-specific utilities will be added to the
dart_helper_utils
package. - If you were using Dart-specific utilities from
flutter_helper_utils
, migrate todart_helper_utils
. If you are using both Flutter and Dart utilities, you can continue usingflutter_helper_utils
as it exportsdart_helper_utils
internally. - This package aims to provide comprehensive Dart utilities for non-Flutter projects.