dart_extensions_kit 1.0.0
dart_extensions_kit: ^1.0.0 copied to clipboard
A comprehensive collection of useful extension methods for Dart and Flutter, including utilities for numbers, strings, lists, maps, dates, colors, and booleans.
dart_extensions_kit #
description: A comprehensive collection of useful extension methods for Dart and Flutter, including utilities for numbers, strings, lists, maps, dates, colors, and booleans.
Features #
Int Extensions #
isEven- Check if number is evenisOdd- Check if number is oddtoBinary- Convert to binary stringtoOctal- Convert to octal stringtoHexUpperCase- Convert to uppercase hex stringtoHexLowerCase- Convert to lowercase hex stringtoFileSize- Convert bytes to human readable file sizeisPrime- Check if number is primefactorial- Get factorial of numberfibonacci- Get fibonacci numberfactors- Get all factorsprimeFactors- Get prime factorsgcd(other)- Get greatest common divisortoRoman- Convert to Roman numeralsformatted- Format number with thousand separatorsrepeat(str)- Repeat string n timestimes<T>(generator)- Create list with generator functiontimesValue<T>(value)- Create list filled with value
Int Time Extensions (int?) #
formatMillisToSmartTime- Format millis to smart time stringformatSecondsToSmartTime- Format seconds to MM:SS or HH:MM:SSformatSecondsToHms- Format seconds to HH:MM:SSformatSecondsToHms2- Alternative format seconds to HH:MM:SSformatMillisToHms- Format milliseconds to HH:MM:SSformatSecondsToCompact- Format seconds to compact string (e.g., "2h23m12s")isWithinMinutes(other, minutes)- Check if within specified minutestoDate- Convert timestamp to DateTime
Double Extensions #
isInteger- Check if double is integerroundTo(decimals)- Round to specified decimal placesceilTo(decimals)- Ceil to specified decimal placesfloorTo(decimals)- Floor to specified decimal placestoPercentage(decimals)- Convert to percentage stringsquared- Get square of numbercubed- Get cube of numbertoDegrees- Convert radians to degreestoRadians- Convert degrees to radians
Price Formatting Extensions (double) #
toCurrency(symbol, decimals)- Convert to currency stringtoPriceStringSimple()- Simple price string (remove trailing .0)toPriceString()- Smart price string with NumberFormat
Num Extensions #
isPositive- Check if positiveisNegative- Check if negativeisZero- Check if zeroclamp(min, max)- Clamp value to rangeisInRange(min, max)- Check if in range (inclusive)isInRangeExclusive(min, max)- Check if in range (exclusive)lerp(other, t)- Linear interpolationmax(other)- Get maximum valuemin(other)- Get minimum valueisEven- Check if evenisOdd- Check if oddformatted- Format with thousand separators
String Extensions #
isBlank- Check if blank (null, empty, or whitespace only)isNotBlank- Check if not blankisNullString- Check if string is "null" (case insensitive)capitalize- Capitalize first letterunCapitalize- Uncapitalize first lettertoSnakeCase- Convert camelCase to snake_casetoCamelCase- Convert snake_case to camelCasetruncate(maxLength, suffix)- Truncate with ellipsisremoveHtmlTags- Remove HTML tagsisEmail- Check if valid email formatisPhoneNumber- Check if valid Chinese phone numberisUrl- Check if valid URL formattryToInt()- Try to parse as inttryToDouble()- Try to parse as doubletoColor- Convert hex string to Colorreversed- Reverse stringrepeat(times)- Repeat stringremove(char)- Remove characterremoveAll(chars)- Remove multiple characterscontainsNumber- Check if contains numbersisNumeric- Check if only contains numbersisAlphabetic- Check if only contains lettersisAlphanumeric- Check if only contains letters and numbers
Nullable String Extensions (String?) #
toIntOr(defaultValue)- Parse to int with defaulttoDoubleOr(defaultValue)- Parse to double with defaultisNullOrEmpty- Check if null or emptyisNotNullOrEmpty- Check if not null and not emptyisNullOrBlank- Check if null or blankisNotNullOrBlank- Check if not null and not blanktoBool- Parse to bool (loose)toBoolStrict()- Parse to bool (strict)
Enum Parsing Extensions #
toEnum<T>(values, defaultValue, ignoreCase)- Parse string to enumtoEnumOr<T>(values, defaultValue, ignoreCase)- Parse string to enum with default
List Extensions #
getOrNull(index)- Safe get element, return null if out of boundsgetOrDefault(index, defaultValue)- Safe get element with defaultrandomOrNull- Get random element or nullrandomOrDefault(defaultValue)- Get random element with defaultshuffled- Get shuffled copydistinct- Remove duplicates (preserve order)distinctBy(keySelector)- Remove duplicates by keychunk(chunkSize)- Split into chunksremoveFirstWhere(test)- Remove first matching elementinsertSafe(index, element)- Safe insert at indexswap(index1, index2)- Swap elementscount(test)- Count matching elementsfirstWhereOrNull(test)- Get first matching element or nulllastWhereOrNull(test)- Get last matching element or nullindexWhereOrNull(test)- Get index of first match or nulllastIndexWhereOrNull(test)- Get index of last match or nullisValidIndex(index)- Check if index is validsublistSafe(start, end)- Safe sublistaddIfNotNull(element)- Add if not nulladdAllNotNull(elements)- Add all non-null elementsprepend(element)- Add to beginningprependAll(elements)- Add all to beginningmiddle- Get middle elementfirstHalf- Get first halfsecondHalf- Get second halfhasDuplicates- Check if has duplicatesduplicates- Get duplicate elementsunique- Get unique elements (appear only once)
Nullable List Extensions (List #
isEmptyOrNull- Check if null or emptyisNotEmptyOrNull- Check if not null and not empty
String List Filter Extensions #
whereNotNullOrEmpty(ignoreWhitespaceOnly)- Filter null and empty strings
Enum Helper Extensions #
fromEnumName(name, defaultValue)- Get enum by namefromEnumNameOr(name, defaultValue)- Get enum by name with default
Map Extensions #
getOrNull(key)- Safe get value, return null if key doesn't existgetOrDefault(key, defaultValue)- Safe get value with defaultgetOrPut(key, defaultValue)- Get or put valuegetOrPutAsync(key, defaultValue)- Get or put value (async)removeWhere(test)- Remove matching key-value pairskeysList- Get keys as listvaluesList- Get values as listentriesList- Get entries as listreversed- Reverse key-value pairsfilterValues(test)- Filter by valuesfilterKeys(test)- Filter by keysmapValues<R>(transform)- Transform valuesmapKeys<R>(transform)- Transform keysmerge(other)- Merge with another mapdeepMerge(other)- Deep merge with another mapfirstEntry- Get first entrylastEntry- Get last entrycontainsValue(value)- Check if contains valuekeysSet- Get keys as setvaluesSet- Get values as setsortedByValue(compare)- Sort by valuessortedByKey(compare)- Sort by keysminByValue- Get entry with minimum valuemaxByValue- Get entry with maximum valuesumValues()- Sum numeric valuesaverageValues()- Average numeric valuesgroupByValue()- Group by valuesallValues(test)- Check if all values matchanyValue(test)- Check if any value matchesallKeys(test)- Check if all keys matchanyKey(test)- Check if any key matches
Nullable Map Extensions (Map<K, V>?) #
isEmptyOrNull- Check if null or emptyisNotEmptyOrNull- Check if not null and not empty
DateTime Extensions #
getWeekdayName(pattern, locale)- Get weekday namegetWeekdayNameShort(locale)- Get short weekday nameweekdayEn- Get weekday in EnglishweekdayShortEn- Get short weekday in EnglishweekdayCn- Get weekday in ChineseweekdayShortCn- Get short weekday in ChinesegetMonthName(pattern, locale)- Get month namegetMonthNameShort(locale)- Get short month namemonthEn- Get month in EnglishmonthShortEn- Get short month in EnglishisToday- Check if todayisYesterday- Check if yesterdayisTomorrow- Check if tomorrowisThisWeek- Check if this weekisThisMonth- Check if this monthisThisYear- Check if this yearstartOfMonth- Get start of monthendOfMonth- Get end of monthstartOfYear- Get start of yearendOfYear- Get end of yearstartOfWeek- Get start of week (Monday)endOfWeek- Get end of week (Sunday)formatDate- Format as yyyy-MM-ddformatTime- Format as HH:mm:ssformatDateTime- Format as yyyy-MM-dd HH:mm:ssformatDateTimeShort- Format as yyyy-MM-dd HH:mmformatMillisToSmartTime(locale)- Smart time formattingrelativeTime- Get relative time descriptionage- Get age in yearsaddYears(years)- Add yearsaddMonths(months)- Add monthsaddDays(days)- Add daysaddHours(hours)- Add hoursaddMinutes(minutes)- Add minutesaddSeconds(seconds)- Add secondssubtractYears(years)- Subtract yearssubtractMonths(months)- Subtract monthssubtractDays(days)- Subtract dayssubtractHours(hours)- Subtract hourssubtractMinutes(minutes)- Subtract minutessubtractSeconds(seconds)- Subtract secondssetTime(hour, minute, second, millisecond, microsecond)- Set timesetDate(year, month, day)- Set dateisWorkday- Check if workdayisWeekend- Check if weekendquarter- Get quarterstartOfQuarter- Get start of quarterendOfQuarter- Get end of quarter
Color Extensions #
hex- Get hex string with alphahexRGB- Get hex string without alphargb- Get RGB stringrgba- Get RGBA stringhsl- Get HSL valueshslString- Get HSL stringisDark- Check if dark colorisLight- Check if light colorcontrastColor- Get contrast color (black or white)luminance- Get luminancewithBrightness(brightness)- Adjust brightnesswithSaturation(saturation)- Adjust saturationwithHue(hue)- Adjust huewithOpacity(opacity)- Adjust opacityblend(other, ratio)- Blend with another colorcomplementary- Get complementary coloranalogous- Get analogous colortriadic- Get triadic colorsmonochromatic- Get monochromatic colorsfromHex(hex)- Create color from hex stringfromRGB(r, g, b, a)- Create color from RGB valuesfromHSL(h, s, l, a)- Create color from HSL values
Bool Extensions #
toInt- Convert to int (true=1, false=0)toChinese- Convert to Chinese (是/否)
Nullable Bool Extensions (bool?) #
isTrue- Check if true
Installation #
Add the dependency in pubspec.yaml:
dependencies:
dart_extensions_kit: ^1.0.0
Then run:
flutter pub get
Usage #
Please check the example.
Example #
See the example directory for a complete sample app.
License #
The project is under the MIT license.