项目作者: leisim

项目描述 :
Superpowers for Dart. Collection of useful static extension methods.
高级语言: Dart
项目地址: git://github.com/leisim/dartx.git
创建时间: 2019-10-17T00:25:56Z
项目社区:https://github.com/leisim/dartx

开源协议:Apache License 2.0

下载


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:

  1. dependencies:
  2. dartx: any

After you import the library, you can use the extensions.

  1. import 'package:dartx/dartx.dart';
  2. 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).

  1. final list = [0, 1, 2, 3, 4, 5];
  2. final last = list.slice(-1); // [5]
  3. final lastHalf = list.slice(3); // [3, 4, 5]
  4. final allButFirstAndLast = list.slice(1, -2); // [1, 2, 3, 4]

.sortedBy() & .thenBy()

Sort lists by multiple properties.

  1. final dogs = [
  2. Dog(name: "Tom", age: 3),
  3. Dog(name: "Charlie", age: 7),
  4. Dog(name: "Bark", age: 1),
  5. Dog(name: "Cookie", age: 4),
  6. Dog(name: "Charlie", age: 2),
  7. ];
  8. final sorted = dogs
  9. .sortedBy((dog) => dog.name)
  10. .thenByDescending((dog) => dog.age);
  11. // Bark, Charlie (7), Charlie (2), Cookie, Tom

.distinctBy()

Get distinct elements from a list.

  1. final list = ['this', 'is', 'a', 'test'];
  2. 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.

  1. final nestedList = [[1, 2, 3], [4, 5, 6]];
  2. final flattened = nestedList.flatten(); // [1, 2, 3, 4, 5, 6]

.chunkWhile() & .splitWhen()

Chunk entries as long as two elements match a predicate:

  1. final list = [1, 2, 4, 9, 10, 11, 12, 15, 16, 19, 20, 21];
  2. final increasingSubSequences = list.chunkWhile((a, b) => a + 1 == b);
  3. // 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.

  1. final word = buildString((sb) {
  2. for (var i = 0; i < 10; i++) {
  3. sb.write(i);
  4. }
  5. });
  6. // 0123456789

.ordinal

Returns an ordinal number of String type for any integer

  1. final a = 1.ordinal(); // 1st
  2. 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.

  1. final word = 'abcd'.capitalize(); // Abcd
  2. 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.

  1. final word = 'abcd'.decapitalize(); // abcd
  2. final anotherWord = 'Abcd'.decapitalize(); // abcd

.isAscii

Returns true if the string is ASCII encoded.

  1. final isAscii = 'abc123 !,.~'.isAscii; // true
  2. final isNotAscii = '§3'.isAscii; // false

.isBlank

Returns true if this string is empty or consists solely of whitespace characters.

  1. final notBlank = ' .'.isBlank; // false
  2. final blank = ' '.isBlank; // true

.isDouble

Returns true if the string can be parsed as a double.

  1. final a = ''.isDouble; // false
  2. final b = 'a'.isDouble; // false
  3. final c = '1'.isDouble; // true
  4. final d = '1.0'.isDouble; // true
  5. final e = '123456789.987654321'.isDouble; // true
  6. final f = '1,000'.isDouble; // false

.isInt

Returns true if the string can be parsed as an integer.

  1. final a = ''.isInt; // false
  2. final b = 'a'.isInt; // false
  3. final c = '1'.isInt; // true
  4. final d = '1.0'.isInt; // false
  5. final e = '1,000'.isInt; // false

.isLatin1

Returns true if the string is Latin 1 encoded.

  1. final isLatin1 = '§Êü'.isLatin1; // true
  2. final isNotLatin1 = 'ő'.isLatin1; // false

.isLowerCase

Returns true if the entire string is lower case.

  1. final a = 'abc'.isLowerCase; // true
  2. final b = 'abC'.isLowerCase; // false
  3. final c = ' '.isLowerCase; // true
  4. final d = ''.isLowerCase; // false

.isNotBlank

Returns true if this string is not empty and contains characters except whitespace characters.

  1. final blank = ' '.isNotBlank; // false
  2. final notBlank = ' .'.isNotBlank; // true

.isNullOrEmpty

Returns true if the String is either null or empty.

  1. final isNull = null.isNullOrEmpty; // true
  2. final isEmpty = ''.isNullOrEmpty; // true
  3. final isBlank = ' '.isNullOrEmpty; // false
  4. final isLineBreak = '\n'.isNullOrEmpty; // false

.isNotNullOrEmpty

Returns true if the String is neither null nor empty.

  1. final isNull = null.isNullOrEmpty; // true
  2. final isEmpty = ''.isNullOrEmpty; // true
  3. final isBlank = ' '.isNullOrEmpty; // false
  4. final isLineBreak = '\n'.isNullOrEmpty; // false

.isNullOrBlank

Returns true if the String is either null or blank.

  1. final isNull = null.isNullOrBlank; // true
  2. final isEmpty = ''.isNullOrBlank; // true
  3. final isBlank = ' '.isNullOrBlank; // true
  4. final isLineBreak = '\n'.isNullOrBlank; // true
  5. final isFoo = ' foo '.isNullOrBlank; // false

.isNotNullOrBlank

Returns true if the String is neither null nor blank.

  1. final isNull = null.isNullOrBlank; // true
  2. final isEmpty = ''.isNullOrBlank; // true
  3. final isBlank = ' '.isNullOrBlank; // true
  4. final isLineBreak = '\n'.isNullOrBlank; // true
  5. final isFoo = ' foo '.isNullOrBlank; // true

.isUpperCase

Returns true if the entire string is upper case.

  1. final a = 'ABC'.isUpperCase; // true
  2. final b = 'ABc'.isUpperCase; // false
  3. final c = ' '.isUpperCase; // true
  4. final d = ''.isUpperCase; // false

.md5

Calculates the MD5 digest and returns the value as a string of hexadecimal digits.

  1. final a = 'abc'.md5; // 900150983cd24fb0d6963f7d28e17f72
  2. final b = 'ഐ⌛酪Б👨‍👨‍👧‍👦'.md5; // c7834eff7c967101cfb65b8f6d15ad46

.urlEncode

Translates a string into application/x-www-form-urlencoded format using a specific encoding scheme.

  1. const originalUrl = 'Hello Ladies + Gentlemen, a signed OAuth request!';
  2. final encodedUrl = originalUrl.urlEncode;
  3. // 'Hello%20Ladies%20+%20Gentlemen,%20a%20signed%20OAuth%20request!'

.urlDecode

Decodes an application/x-www-form-urlencoded string using a specific encoding scheme.

  1. const encodedUrl = 'Hello%20Ladies%20+%20Gentlemen,%20a%20signed%20OAuth%20request!';
  2. final decodedUrl = encodingUrl.urlDecode;
  3. // 'Hello Ladies + Gentlemen, a signed OAuth request!'

.removePrefix(), .removeSuffix() and .removeSurrounding()

Remove a prefix, a suffix, or both from a given string:

  1. final name = 'James Bond'.removePrefix('James '); // Bond
  2. final milliseconds = '100ms'.removeSuffix('ms'); // 100
  3. final text = '<p>Some HTML</p>'
  4. .removeSurrounding(prefix: '<p>', suffix: '</p>'); // Some HTML

.reversed

Returns a new string with characters in reversed order.

  1. final emptyString = ''.reversed; // ''
  2. 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.

  1. final sliceOne = 'awesomeString'.slice(0,6)); // awesome
  2. 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.

  1. final numOne = '1'.toDoubleOrNull(); // 1.0
  2. final numTwo = '1.2'.toDoubleOrNull(); // 1.2
  3. 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.

  1. final a = '1'.toInt(); // 1
  2. final b = '100'.toInt(radix: 2); // 4
  3. final c = '100'.toInt(radix: 16); // 256
  4. final d = '1.0'.toInt(); // throws FormatException

.toIntOrNull()

Parses the string as an integer or returns null if it is not a number.

  1. final number = '12345'.toIntOrNull(); // 12345
  2. final notANumber = '123-45'.toIntOrNull(); // null

.toUtf8()

Converts String to UTF-8 encoding.

  1. final emptyString = ''.toUtf8(); // []
  2. final hi = 'hi'.toUtf8(); // [104, 105]
  3. final emoji = '😄'.toUtf8(); // [240, 159, 152, 132]

.toUtf16()

Converts String to UTF-16 encoding.

  1. final emptyString = ''.toUtf16(); // []
  2. final hi = 'hi'.toUtf16(); // [104, 105]
  3. final emoji = '😄'.toUtf16(); // [55357, 56836]

.orEmpty()

Returns the string if it is not null, or the empty string otherwise.

  1. String? nullableStr;
  2. final str = nullableStr.orEmpty(); // ''

.matches()

Returns true if this char sequence matches the given regular expression.

  1. print('as'.matches(RegExp('^.s\$'))) // true
  2. print('mst'.matches(RegExp('^.s\$'))) // false

Time utils

Dartx exports @jogboms great ⏰ time.dart package so you can do the following:

  1. int secondsInADay = 1.days.inSeconds;
  2. Duration totalTime = [12.5.seconds, 101.milliseconds, 2.5.minutes].sum();
  3. 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.

  1. final numberInRange = 123.coerceIn(0, 1000); // 123
  2. final numberOutOfRange = -123.coerceIn(0, 1000); // 0

.toBytes()

Converts this value to binary form.

.toChar()

Converts this value to character

  1. final character = 97.toChar(); // a

range

rangeTo

Creates a range between two ints (upwards, downwards and with custom steps)

  1. // upwards with default step size 1
  2. for (final i in 1.rangeTo(5)) {
  3. print(i); // 1, 2, 3, 4, 5
  4. }
  5. // downwards with custom step
  6. for (final i in 10.rangeTo(2).step(2)) {
  7. print(i); // 10, 8, 6, 4, 2
  8. }

Function

.partial(), .partial2() …

Applies some of the required arguments to a function and returns a function which takes the remaining arguments.

  1. void greet(String firstName, String lastName) {
  2. print('Hi $firstName $lastName!');
  3. }
  4. final greetStark = greet.partial('Stark');
  5. greetStark('Sansa'); // Hi Sansa Stark!
  6. greetStark('Tony'); // Hi Tony Stark!

File

.name

Get the name and extension of a file.

  1. final file = File('some/path/testFile.dart');
  2. print(file.name); // testFile.dart
  3. print(file.nameWithoutExtension); // testFile

.appendText()

Append text to a file.

  1. await File('someFile.json').appendText('{test: true}');

.isWithin()

Checks if a file is inside a directory.

  1. final dir = Directory('some/path');
  2. File('some/path/file.dart').isWithin(dir); // true

Directory

.file(String)

References a file within a Directory

  1. Directory androidDir = Directory('flutter-app/android');
  2. File manifestFile = androidDir.file("app/src/main/AndroidManifest.xml");

References a directory within a Directory

.directory(String)

  1. Directory androidDir = Directory('flutter-app/android');
  2. 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.

  1. final File someFile = File('someFile.txt');
  2. final Directory someDir = Directory('some/dir');
  3. final Directory parentDir = Directory('parent/dir');
  4. parentDir.contains(someFile);
  5. parentDir.contains(someDir);
  6. parentDir.contains(someFile, recursive: true);
  7. 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

  1. Copyright 2019 Simon Leier
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.