Viewing version 1.2.0. Open the latest package page.
dartx
1.2.0Superpowers for Dart. Collection of useful static extension methods.
Readme
Dart CI Codecov dartx flutterx
If you miss an extension, please open an issue or pull request
Resources:
On this page you can find some of the extensions. Take a look at the docs to see all of them.
Getting started 🎉
Add the following to your pubspec.yaml:
dependencies:
dartx: any
After you import the library, you can use the extensions.
import 'package:dartx/dartx.dart';
final slice = [1, 2, 3, 4, 5].slice(1, -2); // [2, 3, 4]
Iterable
.slice()
Returns elements at indices between start (inclusive) and end (inclusive).
final list = [0, 1, 2, 3, 4, 5];
final last = list.slice(-1); // [5]
final lastHalf = list.slice(3); // [3, 4, 5]
final allButFirstAndLast = list.slice(1, -2); // [1, 2, 3, 4]
.sortedBy() & .thenBy()
Sort lists by multiple properties.
final dogs = [
Dog(name: "Tom", age: 3),
Dog(name: "Charlie", age: 7),
Dog(name: "Bark", age: 1),
Dog(name: "Cookie", age: 4),
Dog(name: "Charlie", age: 2),
];
final sorted = dogs
.sortedBy((dog) => dog.name)
.thenByDescending((dog) => dog.age);
// Bark, Cookie, Charlie (7), Charlie (2), Tom
.distinctBy()
Get distinct elements from a list.
final list = ['this', 'is', 'a', 'test'];
final distinctByLength = list.distinctBy((it) => it.length); // ['this', 'is', 'a']
.flatten()
Get a new lazy Iterable of all elements from all collections in a collection.
final nestedList = [[1, 2, 3], [4, 5, 6]];
final flattened = nestedList.flatten(); // [1, 2, 3, 4, 5, 6]
.chunkWhile() & .splitWhen()
Chunk entries as long as two elements match a predicate:
final list = [1, 2, 4, 9, 10, 11, 12, 15, 16, 19, 20, 21];
final increasingSubSequences = list.chunkWhile((a, b) => a + 1 == b);
// increasingSubSequences = [[1, 2], [4], [9, 10, 11, 12], [15, 16], [19, 20, 21]]
splitWhen is the opposite of chunkWhile that starts a new chunk every time
the predicate didn't match.
int
buildString()
Builds new string by populating newly created StringBuffer using provided builderAction
and then converting it to String.
final word = buildString((sb) {
for (var i = 0; i < 10; i++) {
sb.write(i);
}
});
// 0123456789
.ordinal
Returns an ordinal number of String type for any integer
final a = 1.ordinal(); // 1st
final b = 108.ordinal(); // 108th
String
.capitalize
Returns a copy of the string having its first letter uppercased, or the original string, if it's empty or already starts with an upper case letter.
final word = 'abcd'.capitalize(); // Abcd
final anotherWord = 'Abcd'.capitalize(); // Abcd
.decapitalize
Returns a copy of the string having its first letter lowercased, or the original string, if it's empty or already starts with a lower case letter.
final word = 'abcd'.decapitalize(); // abcd
final anotherWord = 'Abcd'.decapitalize(); // abcd
.isAscii
Returns true if the string is ASCII encoded.
final isAscii = 'abc123 !,.~'.isAscii; // true
final isNotAscii = '§3'.isAscii; // false
.isBlank
Returns true if this string is empty or consists solely of whitespace characters.
final notBlank = ' .'.isBlank; // false
final blank = ' '.isBlank; // true
.isDouble
Returns true if the string can be parsed as a double.
final a = ''.isDouble; // false
final b = 'a'.isDouble; // false
final c = '1'.isDouble; // true
final d = '1.0'.isDouble; // true
final e = '123456789.987654321'.isDouble; // true
final f = '1,000'.isDouble; // false
.isInt
Returns true if the string can be parsed as an integer.
final a = ''.isInt; // false
final b = 'a'.isInt; // false
final c = '1'.isInt; // true
final d = '1.0'.isInt; // false
final e = '1,000'.isInt; // false
.isLatin1
Returns true if the string is Latin 1 encoded.
final isLatin1 = '§Êü'.isLatin1; // true
final isNotLatin1 = 'ő'.isLatin1; // false
.isLowerCase
Returns true if the entire string is lower case.
final a = 'abc'.isLowerCase; // true
final b = 'abC'.isLowerCase; // false
final c = ' '.isLowerCase; // true
final d = ''.isLowerCase; // false
.isNotBlank
Returns true if this string is not empty and contains characters except whitespace characters.
final blank = ' '.isNotBlank; // false
final notBlank = ' .'.isNotBlank; // true
.isNullOrEmpty
Returns true if the String is either null or empty.
final isNull = null.isNullOrEmpty; // true
final isEmpty = ''.isNullOrEmpty; // true
final isBlank = ' '.isNullOrEmpty; // false
final isLineBreak = '\n'.isNullOrEmpty; // false
.isNotNullOrEmpty
Returns true if the String is neither null nor empty.
final isNull = null.isNullOrEmpty; // true
final isEmpty = ''.isNullOrEmpty; // true
final isBlank = ' '.isNullOrEmpty; // false
final isLineBreak = '\n'.isNullOrEmpty; // false
.isNullOrBlank
Returns true if the String is either null or blank.
final isNull = null.isNullOrBlank; // true
final isEmpty = ''.isNullOrBlank; // true
final isBlank = ' '.isNullOrBlank; // true
final isLineBreak = '\n'.isNullOrBlank; // true
final isFoo = ' foo '.isNullOrBlank; // false
.isNotNullOrBlank
Returns true if the String is neither null nor blank.
final isNull = null.isNullOrBlank; // true
final isEmpty = ''.isNullOrBlank; // true
final isBlank = ' '.isNullOrBlank; // true
final isLineBreak = '\n'.isNullOrBlank; // true
final isFoo = ' foo '.isNullOrBlank; // true
.isUpperCase
Returns true if the entire string is upper case.
final a = 'ABC'.isUpperCase; // true
final b = 'ABc'.isUpperCase; // false
final c = ' '.isUpperCase; // true
final d = ''.isUpperCase; // false
.md5
Calculates the MD5 digest and returns the value as a string of hexadecimal digits.
final a = 'abc'.md5; // 900150983cd24fb0d6963f7d28e17f72
final b = 'ഐ⌛酪Б👨👨👧👦'.md5; // c7834eff7c967101cfb65b8f6d15ad46
.urlEncode
Translates a string into application/x-www-form-urlencoded format using a specific encoding scheme.
const originalUrl = 'Hello Ladies + Gentlemen, a signed OAuth request!';
final encodedUrl = originalUrl.urlEncode;
// 'Hello%20Ladies%20+%20Gentlemen,%20a%20signed%20OAuth%20request!'
.urlDecode
Decodes an application/x-www-form-urlencoded string using a specific encoding scheme.
const encodedUrl = 'Hello%20Ladies%20+%20Gentlemen,%20a%20signed%20OAuth%20request!';
final decodedUrl = encodingUrl.urlDecode;
// 'Hello Ladies + Gentlemen, a signed OAuth request!'
.removePrefix(), .removeSuffix() and .removeSurrounding()
Remove a prefix, a suffix, or both from a given string:
final name = 'James Bond'.removePrefix('James '); // Bond
final milliseconds = '100ms'.removeSuffix('ms'); // 100
final text = '<p>Some HTML</p>'
.removeSurrounding(prefix: '<p>', suffix: '</p>'); // Some HTML
.reversed
Returns a new string with characters in reversed order.
final emptyString = ''.reversed; // ''
final reversed = 'abc🤔'.reversed; // '🤔cba'
.slice()
Returns a new substring containing all characters including indices [start] and [end].
If [end] is omitted, it is being set to lastIndex.
final sliceOne = 'awesomeString'.slice(0,6)); // awesome
final sliceTwo = 'awesomeString'.slice(7)); // String
.toDoubleOrNull()
Parses the string as a double and returns the result or null if the String is not a valid representation of a number.
final numOne = '1'.toDoubleOrNull(); // 1.0
final numTwo = '1.2'.toDoubleOrNull(); // 1.2
final blank = ''.toDoubleOrNull(); // null
.toInt()
Parses the string as an integer and returns the result. The radix (base) thereby defaults to 10. Throws a FormatException if parsing fails.
final a = '1'.toInt(); // 1
final b = '100'.toInt(radix: 2); // 4
final c = '100'.toInt(radix: 16); // 256
final d = '1.0'.toInt(); // throws FormatException
.toIntOrNull()
Parses the string as an integer or returns null if it is not a number.
final number = '12345'.toIntOrNull(); // 12345
final notANumber = '123-45'.toIntOrNull(); // null
.toUtf8()
Converts String to UTF-8 encoding.
final emptyString = ''.toUtf8(); // []
final hi = 'hi'.toUtf8(); // [104, 105]
final emoji = '😄'.toUtf8(); // [240, 159, 152, 132]
.toUtf16()
Converts String to UTF-16 encoding.
final emptyString = ''.toUtf16(); // []
final hi = 'hi'.toUtf16(); // [104, 105]
final emoji = '😄'.toUtf16(); // [55357, 56836]
.orEmpty()
Returns the string if it is not null, or the empty string otherwise.
String? nullableStr;
final str = nullableStr.orEmpty(); // ''
.matches()
Returns true if this char sequence matches the given regular expression.
print('as'.matches(RegExp('^.s\$'))) // true
print('mst'.matches(RegExp('^.s\$'))) // false
Time utils
Dartx exports @jogboms great ⏰ time.dart package so you can do the following:
int secondsInADay = 1.days.inSeconds;
Duration totalTime = [12.5.seconds, 101.milliseconds, 2.5.minutes].sum();
DateTime oneWeekLater = DateTime.now() + 1.week;
Check out ⏰ time.dart for more information and examples.
num
.coerceIn()
Ensures that this value lies in the specified range.
final numberInRange = 123.coerceIn(0, 1000); // 123
final numberOutOfRange = -123.coerceIn(0, 1000); // 0
.toBytes()
Converts this value to binary form.
.toChar()
Converts this value to character
final character = 97.toChar(); // a
range
rangeTo
Creates a range between two ints (upwards, downwards and with custom steps)
// upwards with default step size 1
for (final i in 1.rangeTo(5)) {
print(i); // 1, 2, 3, 4, 5
}
// downwards with custom step
for (final i in 10.rangeTo(2).step(2)) {
print(i); // 10, 8, 6, 4, 2
}
Function
.partial(), .partial2() ...
Applies some of the required arguments to a function and returns a function which takes the remaining arguments.
void greet(String firstName, String lastName) {
print('Hi $firstName $lastName!');
}
final greetStark = greet.partial('Stark');
greetStark('Sansa'); // Hi Sansa Stark!
greetStark('Tony'); // Hi Tony Stark!
File
.name
Get the name and extension of a file.
final file = File('some/path/testFile.dart');
print(file.name); // testFile.dart
print(file.nameWithoutExtension); // testFile
.appendText()
Append text to a file.
await File('someFile.json').appendText('{test: true}');
.isWithin()
Checks if a file is inside a directory.
final dir = Directory('some/path');
File('some/path/file.dart').isWithin(dir); // true
Directory
.file(String)
References a file within a Directory
Directory androidDir = Directory('flutter-app/android');
File manifestFile = androidDir.file("app/src/main/AndroidManifest.xml");
References a directory within a Directory
.directory(String)
Directory androidDir = Directory('flutter-app/android');
Directory mainSrc = androidDir.directory("app/src/main");
.contains(FileSystemEntity entity, {bool recursive = false})
Checks if a Directory contains a FileSystemEntity. This can be a File or a Directory.
Use the recursive argument to include the subdirectories.
final File someFile = File('someFile.txt');
final Directory someDir = Directory('some/dir');
final Directory parentDir = Directory('parent/dir');
parentDir.contains(someFile);
parentDir.contains(someDir);
parentDir.contains(someFile, recursive: true);
parentDir.contains(someDir, recursive: true);
This is the async method, which returns a Future<bool>.
.containsSync(FileSystemEntity entity, {bool recursive = false})
Same as .contains(FileSystemEntity entity, {bool recursive = false}) but synchronous. Returns a bool.
License
Copyright 2019 Simon Leier
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Changelog
1.2.0
- Official Dart 3.0 release
- General cleanup and CI update
1.1.0
- PR-151 New:
String?.isNullOrBlank,String?.isNotNullOrBlank - PR-149 Fix type of extension:
IterableForthItem->IterableFourthItem - PR-147 New:
int.toChar(): String - PR-147 New:
String?.orEmpty: bool - PR-147 New:
String.matches(RexExp): bool - PR-147 New:
String.urlEncodeandString.urlDecode - PR-147 New:
buildStringto build aStringBufferan immediately return it - PR-156 Fix:
Iterable.takeFirst(n)andIterable.takeLast(n)crashed when n > length
1.0.0
- Promote to stable version
- Remove deprecated extensions
0.8.0
- PR-136 New: Multiple extensions for
Map.all(),any(),count(),filter(),filterKeys(),filterNot,filterValues,getOrElse(),mapEntries(),mapKeys(),mapValues(),maxBy(),maxWith(),minBy(),minWith,none(),toList(),toMap(),orEmpty() - PR-127 Improve:
sumByis now generic and works equally fornum/int/double - PR-131 Fix:
min()/max()which returned the wrong item for reversed ordered lists - PR-133 New:
plus()/minus()andplusOrNull/minusOrNulltonumwhich handlenull - PR-138 Improve:
Iterable.secondreturnsTinstead ofT?. Analog tofirst - PR-142 Fix:
isUpperCase/isLowerCasenow threat only[a-zA-Z]chars as being uppercase
Also, all linting issues have been fixed and the README has been drastically improved. Thanks @minhqdao
0.7.1
- PR-126 Improve runtime of
elementAtOrNullforList - PR-125 Fix
whereNotNullto actually return non-null elements
0.7.0
- All extensions methods now have their own extension which can be imported explicitly with
show/hide. This allows the usage ofpackage:collectionanddartxin the same file. - Undeprecate
firstOrNullWhereuntildartxcan exportpackage:collectionitself - New
Directory.fileandDirectory.directoryextensions to quickly create file/directory references - Update
timepackage
0.6.0
- PR-120 Migrate to nullsafety
- Fix
minBy,maxByNPE for empty lists - PR-69 New
Dictionary.contains - PR-57 New
Iterable.slice
0.5.0
- PR-94 Breaking:
Iterable<T>.zip(other, transform)now support zipping iterables of other types theT. This is a breaking change because it is now required to add types in the transform function.final amounts = [2, 3, 4]; final animals = ['dogs', 'birds', 'cats']; final all = amounts.zip(animals, (int amount, String animal) => '$amount $animal'); // lambda types are now required: ⇧ ⇧ // all: ['2 dogs', '3 birds', '4 cats'] - PR-90 New
StringextensionsString removePrefix(String prefix)String removeSuffix(String suffix)String removeSurrounding({String prefix, String suffix})
final name = 'James Bond'.removePrefix('James '); // Bond final milliseconds = '100ms'.removeSuffix('ms'); // 100 final text = '<p>Some HTML</p>'.removeSurrounding(prefix: '<p>', suffix: '</p>'); // Some HTML - PR-88 New
Listextensionvoid swap(int, int)which swaps the elements in the indices provided.final list = [1, 2, 3, 4]; list.swap(0, 2); // [3, 2, 1, 4] - PR-100 Relax the upper version constraint of
collectionto support Flutter 1.20 (which usescollection: 1.3.0-nullsafety) - PR-101 Relax the upper version constraint of
crypto
0.4.2
- Increase dependency range of
charactersto include1.0.0 - Raise min sdk version to
2.6.0to prevent pub publishing warning for pre-release versions
0.4.1
0.4.0
Iterable
- PR-41 New
Iterable<T>.containsAny(Iterable<T>)extension - PR-46 New
Iterable<num>.median()extension - PR-53 New
Iterable<T>.asStream()extension converts any Iterable to a Stream - PR-59 New
Iterable<T>.cachedextension creates a cachedIterablepreventing lazy operators such as.mapto execute again - PR-56 Make
Iterable<Iterable<T>>.flatten()typesafe and returnIterable<T>instead ofIterable<dynamic> - PR-62 New
Iterable<T>.chunkWhile(bool Function(T, T) predicate): Iterable<List<E>>extension splits a collection into a lazy Iterables of chunks, where chunks are created as long aspredicateis true for a pair of entries. - PR-62 New
Iterable<T>.splitWhen(bool Function(E, E) predicate): Iterable<List<E>>extension splits a collection into a lazyIterable, where each split will be make ifpredicatereturnstruefor a pair of entries. - PR-54 New
Iterable<Future<T>>.asStreamAwaited(): Stream<T>extension to create a stream from a group of futures.
String
- PR-72 New
String.isNullOrEmptyextension - PR-43 New
String.toInt({int radix})extension as alias forint.parse(String, {int radix})(alsoString.toIntOrNull({int radix})) - PR-75 Deprecate
String.charsin favour ofString.charactersfrom the officialcharacterspackage.
Ranges
- PR-74 New
Comparable<T>.rangeTo(Comparable<T> end)extension to create ranges ofDateTimeorString. - PR-45 New
num.between(num first, num endInclusive): boolextension - PR-45 New
num.inRange(Range<num> range): boolextension - PR-45 New
Comparable<T>.between(T first, T endInclusive): boolextension - PR-45 New
Comparable<T>.inRange(ComparableRange<T> range): boolextension
0.3.0+1
- Improve package scoring by upgrading dependencies and formatting files
- Change README slightly
0.3.0
- PR-14 New
int.rangeTo(int)extension - PR-24 Default implementations for
Comparable<,<=,>=and>operators. - PR-13 Removed
quiverdependency - PR-21 New
String.md5to calculate a MD5 digest - PR-25 New
FileSystemEntity.withName(String newName)to get aFilewith a different name - PR-25 New
FileSystemEntity.extensionto get the file extension - PR-17
Callable.invoke()is now marked asDeprecatedin favour of dartscall()method. It will not be removed though, until darts.call()methods gets auto-completion. - PR-30 New
Comparable.coerceIn(),Comparable.coerceAtLeast()andComparable.coerceAtMost() - PR-31 Fixed
num.toBytes() - PR-33 Fixed
.thenBy()and.thenWith()extensions for Lists
Breaking
- PR-29
Iterable<E>.windowed- remove the required transform lambda
0.2.0
- Moved to
time.dartlibrary for time extensions
0.1.2
- Fixed docs
- Added
Function.curry(),Function.invoke(),Function.partial()andFunction.flip() 'string'.reversednow correctly handles grapheme clusters (like emoji)
Breaking
'string'.charsnow returns the grapheme clusters instead ofRunes
0.1.1
- Bugfixes
- More tests
0.1.0+1
- Initial release
Installing
export PUB_HOSTED_URL=https://pub.mirror.p-hatan.ir
flutter pub add 'dartx:1.2.0'pubspec.yaml
name: dartx
description: Superpowers for Dart. Collection of useful static extension methods.
version: 1.2.0
homepage: https://github.com/leisim/dartx
environment:
sdk: '>=2.12.0 <4.0.0'
dependencies:
characters: ^1.1.0
collection: ^1.15.0
crypto: ^3.0.0
meta: ^1.3.0
path: ^1.8.0
time: ^2.0.0
dev_dependencies:
fake_async: ^1.2.0
lint: '>=1.5.0 <3.0.0'
test: ^1.16.4
Version history
| Version | Published | Archive | SHA-256 |
|---|---|---|---|
| 0.0.1 | On demand | Download | 7458caa9…f40d0a |
| 0.0.2 | On demand | Download | 75e85c21…4bceb7 |
| 0.0.3 | On demand | Download | a3f22d6a…5e8bd7 |
| 0.0.5 | On demand | Download | e488aa93…9bdfb7 |
| 0.0.6 | On demand | Download | dcedc4d7…1a88ab |
| 0.0.7 | On demand | Download | 5ad516dd…5b4912 |
| 0.0.8 | On demand | Download | 97a9d8ef…75f1b2 |
| 0.1.0 | On demand | Download | 720aa6af…9efdbc |
| 0.1.0+1 | On demand | Download | 08b3ca23…7433cb |
| 0.1.1 | On demand | Download | 74bc2526…703daa |
| 0.1.2 | On demand | Download | 0ef632be…59a020 |
| 0.2.0 | On demand | Download | 39a6f27c…3f7c7f |
| 0.3.0 | On demand | Download | b467ad37…509503 |
| 0.4.0 | On demand | Download | d3bc1786…21dc18 |
| 0.4.1 | On demand | Download | 051dda64…3f64dc |
| 0.4.2 | On demand | Download | 28b536d8…6d11a0 |
| 0.5.0 | On demand | Download | 6a58805e…9eff38 |
| 0.6.0 | On demand | Download | 91f581ee…350eb5 |
| 0.7.0 | On demand | Download | 5582cc16…e41320 |
| 0.7.1 | On demand | Download | 4bc88120…915776 |
| 0.8.0 | On demand | Download | 08790dff…f0ae27 |
| 1.0.0 | On demand | Download | 4ec9cf3d…4920c8 |
| 1.1.0 | On demand | Download | 45d71767…764871 |
| 1.2.0 | Cached · Upstream SHA-256 matched | Download | 8b254356…13d244 |
Dependencies
characters "^1.1.0"
collection "^1.15.0"
crypto "^3.0.0"
meta "^1.3.0"
path "^1.8.0"
time "^2.0.0"