Skip to main content

dart_helper_utils 7.0.0 copy "dart_helper_utils: ^7.0.0" to clipboard
dart_helper_utils: ^7.0.0 copied to clipboard

Dart utilities and extensions with re-exported convert_object, stringo, collection, and intl APIs.

CHANGELOG #

7.0.0 #

A correctness release. It moves to Dart 3.13.5 and stringo 3, fixes a set of calendar, number, and stream bugs that only showed up in some time zones or edge cases, and gives every helper one name and one meaning. Most renames migrate automatically with dart fix, and all but two of the old names keep compiling (as deprecated aliases) until 8.0.0.

Upgrading #

  1. Require dart_helper_utils: ^7.0.0 (Dart 3.13.5 or later; Flutter 3.47.7 or later) and run dart pub get or flutter pub get.
  2. Run dart fix --dry-run, then dart fix --apply.
  3. Review the manual steps below, then run dart analyze and your tests.

The automatic migration was verified on Dart 3.13.5 against code written for 6.1.0. The migration guide lists every rename and manual step.

Breaking changes migrated by dart fix #

The old names are deprecated aliases until 8.0.0, so code keeps compiling while you migrate:

  • isAtSameYearAs through isAtSameMicrosecondAs are isSameYearAs through isSameMicrosecondAs. The isSame*As family was incomplete before; isSameMinuteAs, isSameSecondAs, isSameMillisecondAs, and isSameMicrosecondAs are new.
  • addOrSubtractYears and addOrSubtractMonths are addYears and addMonths; addOrSubtractDays, addOrSubtractMinutes, addOrSubtractSeconds, addOrSubtractMilliseconds, and addOrSubtractMicroseconds are the existing addDays, addMinutes, addSeconds, addMilliseconds, and addMicroseconds. subtractYears and subtractMonths are new.
  • DateTime.tomorrow and yesterday are nextDay and previousDay.
  • DateTime?.isPresent is isFuture. It always meant "later than now".
  • formatASyQQQ is formatAsyQQQ, and enforceRtlIn is enforceRtl, to pair with enforceLtr.
  • Iterable.swap is swapped, because it returns a copy. On a List, swap already meant collection's in-place swap, and still does.
  • isEmptyOrNull and isNotEmptyOrNull on String? are isBlank and isNotBlank. stringo 2.0.0 removed these synonyms; this package keeps them as deprecated aliases so nullable receivers migrate too. The collection versions on Iterable? and Map? are unchanged.

These are removed outright, and dart fix still migrates them:

  • Iterable.find becomes collection's identical firstWhereOrNull. Rewrite an explicit DHUCollectionsExtensions(x).find(...) call by hand.
  • DHUNullableSetExtensions becomes DHUCollectionsExtensionsNS, which already declared the same members for any Iterable?.

Breaking changes that need a manual check #

  • Requirements: Dart 3.13.5 or later. The equatable dependency is gone, and the re-exported stringo moves from 1.x to 3.x. Its 2.0.0 behavior changes reach you through this package: truncate counts its suffix against the length, mask and insert return String? even on a non-null String (append ?? '' where a String is required), slugify treats -, _, and whitespace alike, toCharArray splits by code point, and toWords drops empty words. See the stringo changelog.
  • Iterable<int> statistics no longer truncate. mean, median, variance, and standardDeviation return double, so [1, 2].mean is 1.5 instead of 1. percentile still returns an int, and mode a List<int>. The Iterable<num> and NumbersHelper mean, variance, and standard deviation are typed double too. Where an int is required, add .round() or .toInt().
  • Calendar helpers keep the receiver's time zone. startOfDay, dateOnly, startOfMonth, startOfYear, firstDayOfMonth, lastDayOfMonth, previousMonth, nextMonth, addMonths, and addYears return a UTC value for a UTC receiver. 6.x returned local time for UTC receivers.
  • Day arithmetic moves by calendar days. addDays, subtractDays, nextDay, previousDay, nextWeek, previousWeek, firstDayOfWeek, lastDayOfWeek, addBusinessDays, and daysUpTo keep the wall-clock time across daylight-saving changes, and every daysInMonth entry is the startOfDay of its date. 6.x added 24-hour durations, so the time shifted by an hour across a transition. On the day of a change, a time the clocks skip moves forward by the jump, and a time they repeat resolves to its first occurrence, unless the receiver is itself the repeat, which keeps its offset. Use add(Duration(days: n)) for exact 24-hour steps. addHours and smaller units still add exact durations.
  • Day counts are calendar-based. remainingDays, passedDays, daysDifferenceTo, isTomorrow, and isYesterday no longer come out one short when a daylight-saving day of 23 hours lies between the dates.
  • roundTo, floorTo, and ceilTo align to the receiver's wall clock. In zones with a half-hour offset, 6.x rounded local times to the wrong boundary (floorTo(1 hour) returned 12:30). Dates before 1970 now floor down instead of toward the epoch. Around a clock change, floorTo and ceilTo return the latest and earliest instant whose wall clock shows an aligned time (an aligned time the clocks skip counts at the jump), and whole-day steps count calendar dates, so floorTo(const Duration(days: 1)) equals startOfDay.
  • Office MIME checks are precise. isDOCX is only .docx, isDOC is only .doc (it was an alias of isDOCX), and isXLSX is only .xlsx. Use the new isWord, or the existing isExcel, for either format.
  • isValidPhoneNumber on a String? matches the String check. A non-null receiver has always resolved to convert_object's permissive check, but a String? receiver got a stricter, North-American pattern, so the same text could pass or fail depending on the static type. Every receiver now gets the permissive check. regexValidPhoneNumber is unchanged if you want the strict pattern.
  • Debouncer.executionHistory is typed. It returns List<DebouncerExecutionRecord> (startTime, endTime, duration, success, error) instead of maps. Call toMap() where you need the old shape.
  • DebouncerState no longer extends Equatable. Equality and hashCode behave as before; props is gone.
  • bufferCount and rateLimit keep state per subscription. Each listener of a broadcast stream gets its own batches and its own rate budget, and the result is a broadcast stream when the source is. rateLimit no longer listens to the source before the result is listened to, and pausing or cancelling the result now pauses or cancels the source.
  • TimeUtils and NumbersHelper are abstract final and can no longer be extended or implemented.
  • Removed duplicates of SDK and re-exported members. Calls compile unchanged because the replacement has the same name: DateTime.copyWith (dart:core has the same signature), int.gcd and num.isNegative (SDK instance members already won), and num?.asBool (convert_object's asBool gives the same answer). Only explicit extension overrides of these need editing. isNegative on a num? now delegates to the SDK getter, so -0.0 counts as negative there too, as it already did on a num.

Fixed #

  • httpDateFormat took the weekday and month from local time while the rest of the date came from UTC, so a local date printed the wrong weekday and month whenever its local and UTC calendar dates differed (for example, shortly after midnight in Tokyo).
  • addOrSubtractMonths (now addMonths) landed in the wrong year for negative offsets: January minus 2 months gave November of the same year.
  • isPowerOf no longer loops forever on zero, and is false for non-positive numbers.
  • toFileSize no longer throws for values between 0 and 1 byte.
  • bitCount no longer counts the minus sign of a negative number.
  • lcm returns 0 for a zero operand instead of throwing.
  • primeFactors factors the magnitude of negative numbers instead of throwing.
  • isFibonacci and NumbersHelper.isPerfectSquare return false for negative numbers instead of true or throwing.
  • NumbersHelper.gcd never returns a negative number.
  • asGreeks abbreviates negative numbers too: -2500000000 is -2.5B.
  • Debouncer.remainingTime and remainingMaxWait report the frozen values while paused instead of null.
  • An unhandled error from a throttled action keeps its original stack trace.
  • DateTime.min and max compare at microsecond precision.
  • The format validators compile their regular expressions once instead of on every call.

Added #

  • preserveOrder on mapConcurrent and waitConcurrency returns results in input order. Completion order stays the default.
  • TimeUtils.throttle accepts asynchronous callbacks; their errors go to onError.
  • DateTime?.tryFormat takes an optional locale, like format.
  • Iterable?.orEmpty() works on a null iterable. Before, it was declared only for non-null iterables, where it did nothing. lastOrDefault returns a non-nullable element.
  • Precompiled validator patterns (patternValidEmail, patternValidUrl, patternValidUuid, and the rest) and the regexValidUuid source.
  • The AI coding-assistant plugin gains a migrate-dart-helper-utils-v6-to-v7 skill for this upgrade, and now installs in Google Antigravity as well as Claude Code and Codex. The README lists the install commands.

Documentation #

  • The README is rewritten for 7.0, and every Dart example in it runs as a test that checks the printed output.

6.1.0 #

String text-transformation helpers now live in the new zero-dependency stringo package, which this package depends on and re-exports.

Your call sites do not change. 'x'.toSnakeCase, 'x'.slugify(), 'x'.isBlank, and the rest still resolve from import 'package:dart_helper_utils/dart_helper_utils.dart'; exactly as before, because Dart resolves extension members by name. If you want only the string helpers in another project, you can now depend on stringo alone instead of pulling in convert_object, intl, collection, and mime.

What moved to stringo #

Case conversion (toWords and the 15 case styles, toTitle, capitalizeFirstLetter and friends), transforms (slugify, truncate, mask, normalizeWhitespace, clean, words, lines, insert, removeSurrounding, replaceBefore / replaceAfter, and so on), the blank checks (isBlank / isEmptyOrNull and negations), the character predicates (isNumeric, isAlphabet, isAlphanumeric, startsWithNumber, containsDigits, hasCapitalLetter, hasMatch), and their six backing regex constants.

What stayed here #

Domain validation (isValidEmail, isValidPhoneNumber, isValidUrl, isValidUsername, isValidCurrency, isValidIp4, isUuid, maskEmail, hasSpecialChars, isBool), MIME and file-type checks, parseDuration, the base64 helpers, isPalindrome, wrapString, limitFromStart / limitFromEnd, lastIndex, anyChar, and ifEmpty. These judge real-world formats or parse values rather than transform text, and the right answer for them varies by project.

⚠️ Two things to check when upgrading #

  1. Extension type names changed for the moved members. DHUCaseConversionExtensions, DHUNullSafeCaseConversionExtensions, and the moved half of DHUStringExtensions / DHUNullSafeStringExtensions are now StringCaseExtensions, NullableStringCaseExtensions, StringTransformExtensions, NullableStringTransformExtensions, and StringChecksExtensions. This only affects code that names an extension explicitly - show DHUCaseConversionExtensions in an import, or DHUStringExtensions('x').clean to disambiguate. Ordinary 'x'.toSnakeCase usage is unaffected. Dart provides no deprecation path for extension names (they cannot be aliased, and two extensions declaring the same members collide), so there is no soft-migration shim for this.
  2. toTitleCase and toTitle now capitalize the first word. Previously a leading stop word was lowercased, so 'the lord of the rings'.toTitleCase returned 'the Lord of the Rings'. It now returns 'The Lord of the Rings', which matches conventional title casing and the behavior the doc comments already described.

Also #

  • titleCaseExceptions (the title-case stop-word list) is now public and backed by a Set for constant-time lookup.
  • mask now rejects negative visibleStart / visibleEnd with an ArgumentError instead of failing later with a RangeError.

6.0.3 #

No Dart API changes.

  • Added an installable AI coding-assistant plugin for Claude Code and OpenAI Codex, hosted in this repository (tooling/ai/dart-helper-utils/) with four package-specific skills: exact utility-API usage, async/timing/stream lifecycles (Debouncer, throttle, rateLimit, waitConcurrency), the v5-to-v6 breaking migration, and version-aware upgrades. Install via /plugin marketplace add omar-hanafy/dart_helper_utils (Claude Code) or codex plugin marketplace add omar-hanafy/dart_helper_utils (Codex CLI); see the README's "AI coding-assistant support" section.
  • Added maintainer tooling: tool/validate_agent_plugin.dart (runs in CI) keeps plugin manifests, marketplace catalogs, and skill metadata in sync with the package version.
  • The plugin tree and maintainer files are excluded from the pub.dev archive (.pubignore); the package payload is unchanged.

6.0.2 #

  • Require convert_object: ^1.1.0 so the re-exported tryGetRaw and the updated alternativeKeys fallback (now selects the first non-null candidate) are always available.
  • Documented the firstValueForKeys → tryGetRaw migration in the v6 migration guide.

6.0.1 #

  • Re-exported package:collection/collection.dart from dart_helper_utils.dart.
  • Corrected the v6 migration docs for JSON helpers moved to convert_object.
  • Refreshed the README

6.0.0 #

🎉 Major Release: V6

This release represents a massive overhaul of dart_helper_utils, focusing on production stability, symmetry across APIs, and filling critical gaps in the Dart ecosystem. It includes significant architectural changes, new asynchronous utilities, robust collection helpers, and comprehensive test coverage.

Note: Several large features (String Similarity, Conversions, Linked List) have been moved to their own dedicated packages to keep this core package lightweight.

⚠️ Breaking Changes #

  • Architecture & Moved Packages:

    • Conversion: All conversion logic moved to convert_object. ConvertObject is renamed to Convert. Top-level functions like toNum are now convertToNum.
    • String Similarity: Algorithms moved to string_search_algorithms.
    • Data Structures: DoublyLinkedList moved to doubly_linked_list.
    • Pagination: Removed Paginator, AsyncPaginator, and InfinitePaginator to focus on core utils.
  • API Cleanups:

    • DatesHelper Removed: Use DateTime extensions directly (e.g., date.isSameDayAs(other)).
    • Duplicate Extensions: Removed extensions that now exist in Dart SDK or package:collection (e.g., firstOrNull, groupBy).
    • Renaming:
      • httpFormat → httpDateFormat
      • encodableCopy → use toJsonSafe() / toJsonMap() from the re-exported convert_object package
      • encodedJsonString → use toJsonString(...) or encodeWithIndent from the re-exported convert_object package
    • Throttling: TimeUtils.throttle now returns a callable ThrottledCallback object with disposal support.

✨ New Features #

  • Async & Futures:

    • Future.minWait(Duration): Prevent UI flicker by enforcing minimum execution time.
    • Future.timeoutOrNull(Duration): Graceful timeout handling.
    • Future.retry(): Robust retry logic with exponential backoff.
    • waitConcurrency: Run a list of futures with a configurable concurrency limit.
  • Streams (New!):

    • Safety: safeAdd, safeAddError, safeClose to prevent "Stream has already been listened to" or closed errors.
    • Transformers: bufferCount, window(duration), rateLimit, withLatestValue.
    • Resilience: retry() (resubscribe on error), replaceOnError, completeOnError.
    • Pausable: asPausable() wrapper.
  • Debouncing:

    • Added TimeUtils.debounce returning a DebouncedCallback with support for flush, cancel, and immediate execution.
  • Collections:

    • chunks(size), windowed(), pairwise(), partition(), intersperse().
    • associate() (Iterable to Map).
    • mapConcurrent: Process collections asynchronously with parallelism control.
    • Maps: deepMerge, unflatten, getPath, setPath (dot-notation access).
  • Strings & MIME:

    • MIME Checks: Extensive getters for file types (e.g., .isImage, .isVideo, .isPDF, .isJSON).
    • truncate(), maskEmail, isUuid, slugify.
    • parseDuration() (handles "1h 30m" and "01:30:00").
  • Dates & Numbers:

    • isWeekend, roundTo/floorTo/ceilTo (duration based).
    • addBusinessDays.
    • toFileSize (formatted bytes).
    • Expanded HTTP status code helpers (isRateLimitError, statusCodeRetryDelay).

🐛 Bug Fixes #

  • Critical: Fixed Uri.rebuild incorrectly stringifying Iterable query parameters (e.g., ?ids=[1,2] is now ?ids=1&ids=2).
  • Critical: indexWhereOrNull no longer swallows exceptions thrown by the predicate.
  • Fixed takeOnly and drop causing runtime errors on fixed-length lists.
  • Fixed isBetween date logic to correctly respect normalization.
  • Fixed percentage calculation to handle division by zero.
  • Fixed Map.setIfMissing to correctly check key presence before setting.
  • Fixed recursion issues in Map.flatMap.

⚡️ Improvements #

  • Scope Functions: Added let, also, takeIf, takeUnless (via convert_object).
  • Validation: Updated regex for URLs and Colors (RGB/HSL/Modern).
  • Performance: Optimized getRandom for non-list iterables.
  • Docs: Significantly expanded documentation and test coverage (now ~99%).

5.5.0 #

  • Enum conversion: ConvertObject.toEnum<T extends Enum>() / tryToEnum<T extends Enum>() + top-level mirrors.
  • Collection extensions: getEnum/tryGetEnum for Map and Iterable (nullable and non-nullable).
  • Helpers: EnumParsers (byName, fromString, byNameOrFallback, byNameCaseInsensitive, byIndex) and List<T extends Enum> shortcuts (.parser, .parserWithFallback, .parserCaseInsensitive, .parserByIndex).
  • Safer try* conversions via _convertObject improvements; enum APIs constrained to T extends Enum.

5.4.1 #

  • Fixed a bug in ConvertObject where innerKey navigation was ignored if the intermediate object matched the target type.
  • Improved String.toDateAutoFormat docs (parsing order, locale, time zones) with examples. Refactored implementation for better normalization and locale-aware disambiguation.
  • Added documentation_rules.md for module docs standards.

5.4.0 #

  • Enhanced ParsingException to provide comprehensive debugging information with structured argument maps and filtered output.

5.3.0 #

  • Reintroduced Coordinates typedef with serialization support (to/from JSON)

5.2.2 #

  • Added public methods firstValueForKeys and firstElementForIndices to Map and Iterable extensions for accessing values with fallback options.

5.2.1 #

  • exported exception classes.

5.2.0 #

  • Made the encode on object returns String instead of dynamic, to prevent confusion.
  • Added Kotlin-style let extension for T and T? types to simplify value transformations and null-safe chaining.

5.1.0 #

  • Added new global randomBool, randomInt, and randomDouble
  • Updated the StringSimilarity:
    • Focused on six key algorithms with enhanced accuracy (to see demo, you can view my enefty_icons_preview website for the enefty_icons package).
    • Improved caching and performance for large strings.
    • New extension methods and advanced ranking features.
    • Richer Unicode support, and more flexible configurations.
    • Better documentation included.

5.0.0 #

  • Breaking changes:

    • Removed conversion helpers on Object to prevent confusion in IDE suggestions.
    • Updated DateTime extension methods:
      • Renamed the following methods for clarity:
        • addOrRemoveYears to addOrSubtractYears
        • addOrRemoveMonths to addOrSubtractMonths
        • addOrRemoveDays to addOrSubtractDays
        • addOrRemoveMinutes to addOrSubtractMinutes
        • addOrRemoveSeconds to addOrSubtractSeconds
      • Fixed a bug in addOrSubtractMonths to correctly handle negative month adjustments (previously, subtracting months could result in incorrect years).
      • Improved addOrSubtractYears and addOrSubtractMonths to preserve millisecond and microsecond components (previously, these were reset to zero).
  • New features:

    • Added new methods to DateTime:
      • addOrSubtractMilliseconds
      • addOrSubtractMicroseconds
      • addMinutes
      • addSeconds
      • addMilliseconds
      • addMicroseconds
      • subtractDays
      • subtractHours
      • subtractMinutes
      • subtractSeconds
      • subtractMilliseconds
      • subtractMicroseconds
    • Add AI documentation to the source code, enabling AI to use these utilities when crafting snippets.

4.1.2 #

  • Updated docs

4.1.1 #

  • Fixed rebuild method in the Uri extension to pass either path or pathSegments not both.

4.1.0 #

  • Introduced rebuild in Uri extension, a builder-based URI replacement.

4.0.1 #

  • renamed Builder class to StringSimilarityBuilder to avoid conflict with Builder widget the flutter sdk.

4.0.0 #

String Similarity #

  • New StringSimilarity Utility: Added with algorithms like diceCoefficient, levenshteinDistance, jaro, jaroWinkler, and cosine.
  • String Extension: compareWith method for quick similarity comparisons.

Debouncer #

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.

Math #

  • sqrt(): Added to numeric extensions for square root calculations.

Number Extensions #

  • HTTP Status Code Helpers:
    • Added isOkCode, isCreatedCode, isAcceptedCode, isNoContentCode, isTemporaryRedirect, isPermanentRedirect, isAuthenticationError, isValidationError, isRateLimitError, isTimeoutError, isConflictError, isNotFoundError, and isRetryableError.
    • Added statusCodeRetryDelay for suggested retry durations.
    • Added toHttpStatusUserMessage and toHttpStatusDevMessage for user-friendly and developer-specific messages.
    • isSuccessCode now checks for all 2xx codes (not just 200 and 201).

Delay Extensions #

  • 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.

DateTime Extensions #

  • Added isBetween for date range checks.

Pagination #

  • Unified Paginator:
    Introduced BasePaginator<T> to centralize shared logic - such as debouncing, lifecycle events, and disposal checks - across all paginators. The new design includes a single InfinitePaginator that supports both page-based and cursor-based infinite scrolling via dedicated factory constructors.
  • Improved AsyncPaginator:
    Updated AsyncPaginator to utilize CancelableOperation for deduplication and optional cancellation of in-flight requests when autoCancelFetches is set to true in PaginationConfig. This prevents race conditions and overlapping requests.
  • Enhanced Caching and Transformations:
    Implemented a consistent _CacheEntry class to cache both Paginator<T> objects and raw List<T> results with time-based expiration checks. Transformation methods (e.g., where(), sort(), and map()) now return fully instantiated Paginator<T> objects with internal caching.
  • Lifecycle and Disposal Improvements:
    Added robust disposal checks and modified methods (like goToPage) to be no-ops after disposal instead of throwing exceptions. This ensures that lifecycle streams remain silent post-disposal.
  • Analytics:
    Introduced the PaginationAnalytics mixin to track page loads, errors, and cache hits, enabling detailed insights into paginator usage.

New Raw Data #

  • HTTP Status Messages: Added httpStatusUserMessage (user-friendly) and httpStatusDevMessage (technical) for explanations and troubleshooting hints.
  • cssColorNamesToArgb: Maps CSS color names to their corresponding ARGB values. e.g. cssColorNamesToArgb['red'] returns 0xFFFF0000.

Migration #

3.3.0 #

  • Introduced a new Object extension for converting objects into all supported types provided by the ConvertObject class.

3.2.0 #

  • Introduced formatAsReadableNumber on num 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.

3.1.1 #

  • Fixed a bug in the num extension's safeDivide function where optional parameters were not being passed to the NumbersHelper's method.

3.1.0 #

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

3.0.0 #

Added #

  • 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 as K, M, B, representing thousands, millions, billions, etc.
    • Roman Numerals:
      • romanNumerals: Maps integers to Roman numerals, including I, V, X, L, C, D, M.
    • Weekdays:
      • smallWeekdays and fullWeekdays: Maps integers to abbreviated (Mon, Tue, etc.) and full weekday names ( Monday, Tuesday, etc.).
    • Months:
      • smallMonthsNames and fullMonthsNames: 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, from 100 (Continue) to 599 (Network Connect Timeout Error).
  • 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.

Changed #

  • Enhanced tryGetX Methods in Iterable and Map extensions to allow alternative key lookups using altKeys in methods like getString(), getInt(), etc.

Removed (Breaking Change) #

  • HttpResStatus Enum:
    • Removed HttpResStatus enum and associated extensions, replaced by lightweight HTTP status code handling with methods like toHttpStatusMessage.

2.7.0 #

  • Added the toDecimalString method on numbers: similar to toStringAsFixed which allows formatting numbers to a specified number of decimal places, but this one includes optional control over trailing zeros.

2.6.0 #

  • The following methods in the DoublyLinkedList class now accept an optional orElsefunction to handle cases where no matching node is found:
    • firstNodeWhere, lastNodeWhere, and singleNodeWhere
    • firstNodeWhereOrNull, lastNodeWhereOrNull, and singleNodeWhereOrNull
    • findNodeByElement

2.5.3 #

  • 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.

2.5.2 #

  • Added support for WASM.
  • Added topics to pubspec.yaml.

2.5.1 #

  • Renamed castTo<R>() to convertTo<R>() in List and Set extensions.
  • Renamed toListCasted<R>() & toSetCasted<R>() to toListConverted<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.

2.5.0 #

  • Added castTo<R>() to the List and Set extensions and toListCasted<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, and isCurrentDayOfWeek.
    • isBetweenMonths: Checks if a number (representing a month) falls within a specified range, handling year boundaries gracefully.
  • 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]
}

2.4.0 #

New Features #

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

2.3.0 #

  • Added firstNodeWhere, firstNodeWhereOrNull, lastNodeWhere, lastNodeWhereOrNull, singleNodeWhere, singleNodeWhereOrNull, replaceNode, removeNodesWhere, swapNodes, and reverse to the DoublyLinkedList class.

2.2.1 #

  • 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 and prev 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

2.1.0 #

  • Added tryDecode on any String 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 the distinctBy method did not correctly identify distinct elements. The method now accepts a keySelector 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)]
    

2.0.0 #

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.

Internationalization (i18n) #

intl Package Integration:

  • 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)
  • Access:
    • We provided direct access to the intl common classes like Intl, Bidi, BidiFormatter, NumberFormat, and DateFormat.
    • Instead of directly exposing the TextDirection class (which could cause confusion with the TextDirection enum in Flutter's dart:ui library), we've provided three global constants:
      • textDirectionLTR, textDirectionRTL, and textDirectionUNKNOWN.

Date and Time Utilities #

New Getter

  • httpDateFormat (formats this date according to RFC-1123 e.g. "Thu, 1 Jan 2024 00:00:00 GMT")

Flexible Weekday Customization:

  • Added optional startOfWeek parameter to firstDayOfWeek and lastDayOfWeek.

Streamlined DateTime Calculations:

  • Consolidated various DateTime manipulation methods for consistency and added tests.

Other Utilities #

New Methods on Map:

  • 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)

New Methods on Iterable:

  • isEqual: checks for deep equality with other iterable of the same type.
  • isPrimitive: checks if every element is a primitive type.

New Global Methods:

  • 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 type T is considered a primitive type at compile time.

New Extractions on Map & Iterable:

  • Added a new set of type-safe converters to safely extract values from Map<K, V> and List<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.

Conversion Functions #

Enhanced Flexibility:

  • Added optional format and locale parameters to numeric conversion functions (toNum, tryToNum, toInt, tryToInt, toDouble, tryToDouble).
  • Added optional format, locale, autoDetectFormat, useCurrentLocale, and utc 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.

Additional Improvements #

  • 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.

Breaking Changes #

try/toDateWithFormat renamed to try/toDateFormatted:

  • Update any code referencing try/toDateWithFormat to use try/toDateFormatted instead.

dateFormat on String is no longer a getter, it's a method that accepts optional locale:

  • instead of 'yyyy MM'.dateFormat use 'yyyy MM'.dateFormat() or yyyy MM'.dateFormat('en_US').

isPrimitiveType (Global) renamed to isValuePrimitive:

  • Update any code referencing isPrimitiveType to use isValuePrimitive instead.

flatJson (Map) renamed to flatMap:

  • Update any code referencing flatJson to use flatMap instead.

makeEncodable and safelyEncodedJson renamed to encodableCopy and encodedJsonString:

  • Fixed an issue where sets were not correctly converted to JSON-encodable lists.
  • Update any code referencing these methods to use their new names.

firstDayOfWeek and lastDayOfWeek:

  • These methods now have an optional startOfWeek parameter, which may affect behavior if not explicitly specified.

Migration Guide #

  • You can see the migration guide for this version from here.
  • You can see all the migration guides in the GitHub repo from here.

1.2.0 #

  • New Feature: Added the toWords getter on String, which converts any String to a List<String>, handling complex cases more effectively than the native split() method.

    • Example Usage:

      print("FlutterAndDart_are-AWESOME".toWords); // [Flutter, And, Dart, are, AWESOME]
      

1.1.0 #

Enhancements #

  • 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.

Added #

  • 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 native toLowerCase() but for nullable strings.
    • tryToUpperCase same as the native toUpperCase() but for nullable strings.
  • String Utility:

    • isBlank: Alias for isEmptyOrNull, checks if a string is null, empty, or solely whitespace.

1.0.1 #

  • Updated the README.

1.0.0 - 2024-05-25 #

Initial release of dart_helper_utils, which includes all the Dart utilities from flutter_helper_utils up to version 4.1.0

Added #

  • ConvertObject class now accepts raw JSON strings for List, Set, and Map 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.

Notes #

44
likes
160
points
4.28k
downloads

Documentation

API reference

Publisher

verified publishertomars.tech

Weekly Downloads

Dart utilities and extensions with re-exported convert_object, stringo, collection, and intl APIs.

Repository (GitHub)
View/report issues

Topics

#utils #utilities #helpers #extensions-pack #case-conversion

License

BSD-3-Clause (license)

Dependencies

collection, convert_object, intl, meta, mime, stringo

More

Packages that depend on dart_helper_utils