dart_helper_utils 1.2.0
dart_helper_utils: ^1.2.0 copied to clipboard
This package offers a collection of Dart utilities, tools for converting dynamic objects to various types, and extending core Dart classes with extensions.
The dart_helper_utils
package provides a collection of Dart utilities, tools for converting dynamic objects to various types, and extending core Dart classes with extensions.
Note: This package is tailored for Dart projects. For Flutter projects, use flutter_helper_utils
, which includes all dart_helper_utils
features plus additional utilities and extensions for Flutter, such as Widget
, Color
, and BuildContext
extensions.
Table of Contents #
- Featured
- Extensions
- Exceptions
- Contributions
- License
Featured #
Converting Objects #
Convert objects to various types, such as int
, double
, bool
, String
, List
, Set
, and Map
. These methods are useful when dealing with dynamic data from APIs, offering simple and flexible type conversions.
Sample Usage: #
Given an API response:
Map<String, dynamic> apiResponse = {'score': '12.4'};
// Using parse
int score = double.parse(apiResponse['score']).toInt();
// Using the package:
int score = toInt(apiResponse['score']);
Available Conversions: #
Methods:
toNum()
/tryToNum()
toInt()
/tryToInt()
toDouble()
/tryToDouble()
toBool()
/tryToBool()
toString1()
/tryToString1()
toList<T>()
/tryToList<T>()
toSet<T>()
/tryToSet<T>()
toMap<K, V>()
/tryToMap<K, V>()
Static Methods: #
The methods above call the original static methods from the ConvertObject
class. For instance:
int score = toInt(map['key']); // global method
// same as
int score = ConvertObject.toInt(map['key']); // static method
Note: To avoid conflicts with method names (e.g., toList
), use the static method directly:
List myList = ConvertObject.toList(dynamicObject);
Optional Parameters: #
Each method accepts two optional parameters: listIndex
and mapKey
. These parameters allow specific value extraction and conversion within a List
or Map
.
Example with listIndex
:
dynamic dynamicList = ['10', '20', '30'];
final int number = toInt(dynamicList, listIndex: 1); // 20
Example with mapKey
:
dynamic dynamicMap = {
'name': 'John',
'age': '30',
'bools': {
'isHuman': 'yes',
}
};
final bool isHuman = toBool(dynamicMap['bools'], mapKey: 'isHuman'); // true
Absolutely! Here's the enhanced documentation for the ConvertObject
class update:
Auto Decoding of JSON Strings for Collections
The ConvertObject
class now simplifies working with JSON data by automatically decoding raw JSON strings when converting to List
, Set
, or Map
types. This eliminates the need for manual parsing before conversion.
Example Usage:
final myList = tryToList<int>("[1, 2, 3]"); // List<int>
final mySet = tryToSet<String>('["hello", "world"]'); // Set<String>
final myMap = tryToMap<String, dynamic>('{"name": "Alice", "age": 30}'); // Map<String, dynamic>
TimeUtils: #
The TimeUtils class provides utilities for measuring and comparing execution times, creating throttled functions, running tasks periodically, and handling tasks with timeouts. Here is a sample with the executionDuration method:
final excutionTime = await TimeUtils.executionDuration(() {
for (var i = 0; i < 1000000; i++) {}
});
print('Synchronous task took $syncDuration');
// NOTE: works also with asynchronous task
Another example with runWithTimeout:
try {
final result = await TimeUtils.runWithTimeout(
task: () async {
await 5.secDelay;
return 'Completed';
},
timeout: const Duration(seconds: 3),
);
print('Result: $result');
} catch (e) {
print('Error: $e');
}
Extensions #
Date Extensions #
Month and Day Name Conversion #
toFullMonthName
: Numeric month (1-12) to full name (e.g., 1 to "January").toSmallMonthName
: Numeric month (1-12) to abbreviated name (e.g., 1 to "Jan").toFullDayName
: Numeric day (1-7) to full name (e.g., 1 to "Monday").toSmallDayName
: Numeric day (1-7) to abbreviated name (e.g., 1 to "Mon").
Date and Time Parsing #
timestampToDate
: Timestamp (milliseconds since epoch) toDateTime
.toDateWithFormat
: String toDateTime
with specific format (e.g., 'd-M-y').tryToDateTime
: Safely parses a nullable string to a nullableDateTime
.toDateTime
: String toDateTime
.dateFormat
: Returns aDateFormat
object based on the string pattern.
Date and Time Formatting #
local
: Converts a nullableDateTime
to local time.toUtcIso
: Converts a nullableDateTime
to ISO 8601 format in UTC.tryFormat
: Formats a nullableDateTime
to a string with the specified format.
Date and Time Comparison #
isTomorrow
: Checks if the nullableDateTime
is tomorrow.isToday
: Checks if the nullableDateTime
is today.isYesterday
: Checks if the nullableDateTime
is yesterday.isPresent
: Checks if the nullableDateTime
is in the future.isPast
: Checks if the nullableDateTime
is in the past.isInPastWeek
: Checks if the nullableDateTime
is within the past week.isInThisYear
: Checks if the nullableDateTime
is in the current year.isFirstDayOfMonth
: Checks if the nullableDateTime
is the first day of the month.isLastDayOfMonth
: Checks if the nullableDateTime
is the last day of the month.isLeapYear
: Checks if the nullableDateTime
is in a leap year.
Duration Calculations #
passedDuration
: Gets the duration since the nullableDateTime
.remainingDuration
: Gets the duration until the nullableDateTime
.remainingDays
: Gets the remaining days until the nullableDateTime
.passedDays
: Gets the passed days since the nullableDateTime
.
Basic DateTime Operations #
local
: Converts aDateTime
to local time.format
: Formats aDateTime
to a string with the specified format.toUtcIso
: Converts aDateTime
to ISO 8601 format in UTC.passedDuration
: Gets the duration since theDateTime
.passedDays
: Gets the passed days since theDateTime
.remainingDuration
: Gets the duration until theDateTime
.remainingDays
: Gets the remaining days until theDateTime
.
DateTime Comparison #
isAtSameYearAs
,isAtSameMonthAs
,isAtSameDayAs
,isAtSameHourAs
,isAtSameMinuteAs
,isAtSameSecondAs
,isAtSameMillisecondAs
,isAtSameMicrosecondAs
: Checks if anotherDateTime
matches the same component.
DateTime Manipulation #
startOfDay
,startOfMonth
,startOfYear
: Gets the start of the day, month, year.tomorrow
,yesterday
,today
: Gets the date of tomorrow, yesterday, today.dateOnly
: Gets the date only (midnight time).daysInMonth
: Gets the list of days in the month.previousDay
,nextDay
: Gets the previous/next day.previousWeek
,nextWeek
: Gets the date of the previous/next week.firstDayOfWeek
,lastDayOfWeek
: Gets the first/last day of the week.previousMonth
,nextMonth
: Gets the date of the previous/next month.firstDayOfMonth
,lastDayOfMonth
: Gets the first/last day of the month.addOrRemoveYears
,addOrRemoveMonth
,addOrRemoveDay
,addOrRemoveMinutes
,addOrRemoveSeconds
: Adds or removes years, months, days, minutes, seconds from aDateTime
.min
,max
: Returns the smaller/larger of twoDateTime
objects.addDays
,addHours
: Adds days/hours to aDateTime
.
Date Extensions #
Month and Day Name Conversion #
toFullMonthName
: Numeric month (1-12) to full name (e.g., 1 to "January").toSmallMonthName
: Numeric month (1-12) to abbreviated name (e.g., 1 to "Jan").toFullDayName
: Numeric day (1-7) to full name (e.g., 1 to "Monday").toSmallDayName
: Numeric day (1-7) to abbreviated name (e.g., 1 to "Mon").
Date and Time Parsing #
timestampToDate
: Timestamp (milliseconds since epoch) toDateTime
.toDateWithFormat
: String toDateTime
with specific format (e.g., 'd-M-y').tryToDateTime
: Safely parses a nullable string to a nullableDateTime
.toDateTime
: String toDateTime
.dateFormat
: Returns aDateFormat
object based on the string pattern.
Date and Time Formatting #
local
: Converts a nullableDateTime
to local time.toUtcIso
: Converts a nullableDateTime
to ISO 8601 format in UTC.tryFormat
: Formats a nullableDateTime
to a string with the specified format.
Date and Time Comparison #
isTomorrow
: Checks if the nullableDateTime
is tomorrow.isToday
: Checks if the nullableDateTime
is today.isYesterday
: Checks if the nullableDateTime
is yesterday.isPresent
: Checks if the nullableDateTime
is in the future.isPast
: Checks if the nullableDateTime
is in the past.isInPastWeek
: Checks if the nullableDateTime
is within the past week.isInThisYear
: Checks if the nullableDateTime
is in the current year.isFirstDayOfMonth
: Checks if the nullableDateTime
is the first day of the month.isLastDayOfMonth
: Checks if the nullableDateTime
is the last day of the month.isLeapYear
: Checks if the nullableDateTime
is in a leap year.
Duration Calculations #
passedDuration
: Gets the duration since the nullableDateTime
.remainingDuration
: Gets the duration until the nullableDateTime
.remainingDays
: Gets the remaining days until the nullableDateTime
.passedDays
: Gets the passed days since the nullableDateTime
.
Basic DateTime Operations #
local
: Converts aDateTime
to local time.format
: Formats aDateTime
to a string with the specified format.toUtcIso
: Converts aDateTime
to ISO 8601 format in UTC.passedDuration
: Gets the duration since theDateTime
.passedDays
: Gets the passed days since theDateTime
.remainingDuration
: Gets the duration until theDateTime
.remainingDays
: Gets the remaining days until theDateTime
.
DateTime Comparison #
isAtSameYearAs
,isAtSameMonthAs
,isAtSameDayAs
,isAtSameHourAs
,isAtSameMinuteAs
,isAtSameSecondAs
,isAtSameMillisecondAs
,isAtSameMicrosecondAs
: Checks if anotherDateTime
matches the same component.
DateTime Manipulation #
startOfDay
,startOfMonth
,startOfYear
: Gets the start of the day, month, year.tomorrow
,yesterday
,today
: Gets the date of tomorrow, yesterday, today.dateOnly
: Gets the date only (midnight time).daysInMonth
: Gets the list of days in the month.previousDay
,nextDay
: Gets the previous/next day.previousWeek
,nextWeek
: Gets the date of the previous/next week.firstDayOfWeek
,lastDayOfWeek
: Gets the first/last day of the week.previousMonth
,nextMonth
: Gets the date of the previous/next month.firstDayOfMonth
,lastDayOfMonth
: Gets the first/last day of the month.addOrRemoveYears
,addOrRemoveMonth
,addOrRemoveDay
,addOrRemoveMinutes
,addOrRemoveSeconds
: Adds or removes years, months, days, minutes, seconds from aDateTime
.min
,max
: Returns the smaller/larger of twoDateTime
objects.addDays
,addHours
: Adds days/hours to aDateTime
.
Duration Extensions: #
delayed(FutureOr<T> Function()? computation)
: Delays execution by the duration.
fromNow
: Adds the Duration to the current DateTime and gives a future time.ago
: Subtracts the Duration from the current DateTime and gives a pastime.
List and Iterable Extensions #
Nullable List Extensions #
of
: Retrieves the element at the specified index in a null-safe manner.tryRemoveAt
: Removes the element at the specified index in a null-safe manner.indexOfOrNull
: Retrieves the index of the specified element in a null-safe manner.indexWhereOrNull
: Retrieves the index of the first element that matches the specified predicate in a null-safe manner.tryRemoveWhere
: Removes elements that match the specified condition in a null-safe manner.
Nullable Iterable Extensions #
isEmptyOrNull
: Returns true if the iterable is either null or empty.isNotEmptyOrNull
: Returns false if the iterable is either null or empty._elementAtOrNull
: Retrieves the element at the specified index or returns null._elementOrNull
: Retrieves the element at the specified index or returns a default value.firstOrNull
: Retrieves the first element or returns null.lastOrNull
: Retrieves the last element or returns null.firstWhereOrNull
: Retrieves the first element that matches the specified predicate or returns null.lastOrDefault
: Retrieves the last element or returns a default value.firstOrDefault
: Retrieves the first element or returns a default value.tryGetRandom
: Retrieves a random element from the iterable or returns null.
Iterable Extensions #
orEmpty
: Returns the iterable if it's not null and the empty list otherwise.any
: Returns true if at least one element matches the given predicate.concatWithSingleList
: Concatenates the current list with another iterable.concatWithMultipleList
: Concatenates the current list with multiple iterables.toMutableSet
: Converts the iterable to a set.intersect
: Returns a set containing all elements that are contained by both this set and the specified collection.groupBy
: Groups the elements by the value returned by the specified key function.filter
: Returns a list containing only elements matching the given predicate.filterNot
: Returns a list containing all elements not matching the given predicate.halfLength
: Returns half the size of the list.takeOnly
: Returns a list containing the firstn
elements.drop
: Returns a list containing all elements except the firstn
elements.mapList
: Returns the result of applying a function to each element in the iterable as a list.firstHalf
: Returns the first half of the list.secondHalf
: Returns the second half of the list.swap
: Returns a list with two items swapped.getRandom
: Retrieves a random element from the iterable.whereIndexed
: Returns an iterable with all elements that satisfy the predicate.forEachIndexed
: Performs the given action on each element in the iterable, providing the sequential index with the element.sortedDescending
: Returns a new list with all elements sorted in descending order.containsAll
: Returns true if all elements in the specified collection are contained in this collection.count
: Returns the number of elements that match the given predicate.all
: Returns true if all elements match the given predicate.distinctBy
: Returns a list containing only elements that have distinct keys, determined by the predicate.subtract
: Returns a set containing all elements that are contained by this collection and not contained by the specified collection.find
: Returns the first element matching the given predicate, or null if not found.encodedJson
: Encodes the iterable as a JSON string.
Map Extensions: #
makeEncodable
: Converts a map to an encodable format.safelyEncodedJson
: Returns a safely encoded JSON string.isEmptyOrNull
: Checks if the map is empty or null.isNotEmptyOrNull
: Checks if the map is not empty or null.flatJson({String delimiter = '.', bool safe = false, int? maxDepth})
: Flattens a JSON structure.
Number Extensions #
For num?
#
isSuccessHttpResCode
: Checks if the HTTP response code is 200 or 201.isValidPhoneNumber
: Checks if the number is a valid phone number.toHttpResStatus
: Converts the number to anHttpResStatus
enum.
For num
#
isPositive
: Returns true if the number is positive.isNegative
: Returns true if the number is negative.isZero
: Returns true if the number is zero.isValidPhoneNumber
: Checks if the number is a valid phone number.numberOfDigits
: Returns the number of digits in the number.removeTrailingZero
: Removes trailing zeros from the number's string representation.roundToFiftyOrHundred
: Rounds the number to the nearest fifty or hundred.roundToTenth
: Rounds the number to the nearest tenth.tenth
: Returns a tenth of the number.fourth
: Returns a fourth of the number.third
: Returns a third of the number.half
: Returns half of the number.getRandom
: Returns a random integer between 0 and the number.asGreeks
: Converts the number to a format that includes Greek symbols for thousands, millions, and beyond.delay
: Delays code execution by the number of seconds.daysDelay
: Delays code execution by the number of days.hoursDelay
: Delays code execution by the number of hours.minDelay
: Delays code execution by the number of minutes.secDelay
: Delays code execution by the number of seconds.millisecondsDelay
: Delays code execution by the number of milliseconds.asMilliseconds
: Converts the number to aDuration
in milliseconds.asSeconds
: Converts the number to aDuration
in seconds.asMinutes
: Converts the number to aDuration
in minutes.asHours
: Converts the number to aDuration
in hours.asDays
: Converts the number to aDuration
in days.until
: Generates a sequence of numbers starting from the current number up to the specified end value, with the specified step size.
For int
#
inRangeOf
: Returns the number if it is within the specified range, otherwise returns the min or max value.absolute
: Returns the absolute value of the number.doubled
: Returns the number multiplied by two.tripled
: Returns the number multiplied by three.quadrupled
: Returns the number multiplied by four.squared
: Returns the square of the number.
For double
#
inRangeOf
: Returns the number if it is within the specified range, otherwise returns the min or max value.absolute
: Returns the absolute value of the number.doubled
: Returns the number multiplied by two.tripled
: Returns the number multiplied by three.quadrupled
: Returns the number multiplied by four.squared
: Returns the square of the number.
For num?
Null-Safe Extensions #
tryToInt
: Parses the number as an integer or returns null if it is not a number.tryToDouble
: Parses the number as a double or returns null if it is not a number.percentage
: Calculates the percentage of the number with respect to a total value, with an option to allow decimals.isNegative
: Returns true if the number is negative.isPositive
: Returns true if the number is positive.isZeroOrNull
: Returns true if the number is zero or null.asBool
: Returns true if the number is greater than zero.
Objects Extensions: #
encode({Object? Function(dynamic object)? toEncodable})
: Encodes an object to JSON.isNull
: Checks if the object is null.isNotNull
: Checks if the object is not null.asBool
: Converts an object to a boolean value.
Set Extensions: #
isEmptyOrNull
: Checks if the set is empty or null.isNotEmptyOrNull
: Checks if the set is not empty or null.addIfNotNull(T? value)
: Adds a value to the set if it's not null.toMutableSet()
: Converts the set to a mutable set.intersect(Iterable<T> other)
: Returns the intersection of two sets.
String Extensions #
Case Conversion #
-
toPascalCase
: PascalCase aka (UpperCamelCase). -
toTitleCase
: Title Case -
toCamelCase
: camelCase aka (dromedaryCase) -
toSnakeCase
: snake_case aka (snail_case, pothole_case). -
toKebabCase
: kebab-case aka (dash-case, lisp-case, spinal-case). -
toScreamingSnakeCase
: SCREAMING_SNAKE_CASE aka (MACRO_CASE, CONSTANT_CASE, ALL_CAPS). -
toScreamingKebabCase
: SCREAMING-KEBAB-CASE aka (COBOL-CASE). -
toPascalSnakeCase
: Pascal_Snake_Case. -
toPascalKebabCase
: Pascal-Kebab-Case. -
toTrainCase
: Train-Case aka (HTTP-Header-Case). -
toCamelSnakeCase
: camel_Snake_Case. -
toCamelKebabCase
: camel-Kebab-Case. -
toDotCase
: dot.case. -
toFlatCase
: flatcase. -
toScreamingCase
: SCREAMINGCASE. -
toTitle
: Capitalizes the first letter of each word in the string while retaining-
,_
, and space characters. -
toWords
: Converts anyString
to aList<String>
, handling complex cases more effectively than the nativesplit()
method.
Text Formatting #
lowercaseFirstLetter
: Lowercases only the first letter of the string, preserving the rest of the case.capitalizeFirstLetter
: Converts the first letter to uppercase and preserves the rest of the case.capitalizeFirstLowerRest
: Converts the first letter to uppercase and the rest to lowercase.tryToLowerCase
: Converts the string to lowercase if it's not null.tryToUpperCase
: Converts the string to uppercase if it's not null.removeEmptyLines
: Removes consecutive empty lines, replacing them with single newlines.toOneLine
: Converts to a single line by replacing all newline characters with spaces.removeWhiteSpaces
: Removes all whitespace characters.clean
: CombinesremoveWhiteSpaces
andtoOneLine
to collapse into a single line.wrapString
: Wraps text based on the specified word count, wrapping behavior, and custom delimiter.
String Replacement #
replaceAfter
: Replaces part of the string after the first occurrence of the given delimiter with a specified string.replaceBefore
: Replaces part of the string before the first occurrence of the given delimiter with a specified string.removeSurrounding
: Removes the surrounding delimiter if it exists at both ends.
String Comparison #
equalsIgnoreCase
: Compares with another string for equality, ignoring case differences.
String Limiting #
limitFromEnd
: Shrinks the string to no more than a specified length, starting from the end.limitFromStart
: Shrinks the string to no more than a specified length, starting from the start.
Character Checks #
isAlphanumeric
: Checks if the string contains only letters and numbers.hasSpecialChars
: Checks if the string contains any characters that are not letters, numbers, or spaces.hasNoSpecialChars
: Checks if the string does not contain any special characters.startsWithNumber
: Checks if the string starts with a number.containsDigits
: Checks if the string contains any digits.hasCapitalLetter
: Checks if the string contains at least one capital letter.isNumeric
: Checks if the string consists only of numbers.isAlphabet
: Checks if the string consists only of alphabetic characters.isBool
: Checks if the string is a boolean value (true or false).
Validation #
isValidUsername
: Checks if the string is a valid username.isValidCurrency
: Checks if the string is a valid currency format.isValidPhoneNumber
: Checks if the string is a valid phone number.isValidEmail
: Checks if the string is a valid email address.isValidHTML
: Checks if the string is a valid HTML file or URL.isValidIp4
: Checks if the string is a valid IPv4 address.isValidIp6
: Checks if the string is a valid IPv6 address.isValidUrl
: Checks if the string is a valid URL.
Utility #
orEmpty
: Returns the string if it is not null, or an empty string otherwise.ifEmpty
: Performs an action if the string is empty.lastIndex
: Gets the last character of the string.isNotBlank
: Returns true if the string is neither null, empty, nor solely made of whitespace characters.toCharArray
: Returns a list of characters.insert
: Inserts a specified string at a specified index position.isNullOrWhiteSpace
: Indicates whether the string is null, empty, or consists only of white-space characters.asBool
: Converts the string to a boolean.decode
: Decodes the JSON string into a dynamic data structure.
Parsing #
tryToNum
: Parses the string as a number or returns null if it is not a number.tryToDouble
: Parses the string as a double or returns null if it is not a number.tryToInt
: Parses the string as an integer or returns null if it is not a number.toNum
: Parses the string as a number.toDouble
: Parses the string as a double.toInt
: Parses the string as an integer.
Null-Safe String Extensions #
Validation #
isEmptyOrNull
||isBlank
: Checks if the string is null or empty.isNotEmptyOrNull
||isNotBlank
: Checks if the string is not null and not empty.isPalindrome
: Checks if the string is a palindrome.isValidUrl
: Checks if the string is a valid URL.isNumeric
: Checks if the string consists only of numbers.isAlphabet
: Checks if the string consists only of alphabetic characters.hasCapitalLetter
: Checks if the string contains at least one capital letter.isBool
: Checks if the string is a boolean value (true or false).
Utility #
removeWhiteSpaces
: Removes all whitespace characters.orEmpty
: Returns the string if it is not null, or an empty string otherwise.ifEmpty
: Performs an action if the string is empty.lastIndex
: Gets the last character of the string.isNotBlank
: Returns true if the string is neither null, empty, nor solely made of whitespace characters.toCharArray
: Returns a list of characters.insert
: Inserts a specified string at a specified index position.isNullOrWhiteSpace
: Indicates whether the string is null, empty, or consists only of white-space characters.asBool
: Converts the string to a boolean.decode
: Decodes the JSON string into a dynamic data structure.
Parsing #
tryToNum
: Parses the string as a number, or returns null if it is not a number.tryToDouble
: Parses the string as a double, or returns null if it is not a number.tryToInt
: Parses the string as an integer, or returns null if it is not a number.toNum
: Parses the string as a number.toDouble
: Parses the string as a double.toInt
: Parses the string as an integer.
Uri Extensions: #
isValidUri
: Checks if the string is a valid URI.toUri
: Converts the string to a URI object.isHttp
: Checks if the URI uses the HTTP scheme.isHttps
: Checks if the URI uses the HTTPS scheme.host
: Returns the host part of the URI.path
: Returns the path part of the URI.
Bool Extensions: #
toggled
: returns a new bool which is toggled from the current one.val
&isTrue
: (nullable boolean): Returnstrue
if the value is not null and trueisFalse
: (nullable boolean): Returnstrue
if the value is not null and falsebinary
: Returns1
if the value is non-null and true, otherwise returns0
.
Exceptions #
The ConvertObject
class throws a ParsingException
if there is an error while converting an object. This exception
provides information about the type of the object and the method used for conversion.
Contributions #
Contributions to this package are welcome. If you have any suggestions, issues, or feature requests, please create a pull request in the repository.
License #
dart_helper_utils
is available under the BSD 3-Clause License.
KEYWORDS: extension pack, helpers, utilities, string manipulation, conversions, time utils, date extensions, datetime helper, iterable, map, number, object, set, URI, and boolean extensions, JSON encoding/decoding.