From 430cb04d27bd857a2cd7d3a3191ffa5d33200dd9 Mon Sep 17 00:00:00 2001 From: Konstantin Pelz Date: Tue, 21 Dec 2021 11:47:51 +0100 Subject: [PATCH] #150 add String.isNullOrBlank and String.isNotNullOrBlank --- README.md | 24 ++++++++++++++++++++++++ lib/src/string.dart | 10 ++++++++++ test/string_test.dart | 16 ++++++++++++++++ 3 files changed, 50 insertions(+) diff --git a/README.md b/README.md index 1722ed9..8148a50 100644 --- a/README.md +++ b/README.md @@ -207,6 +207,30 @@ final isBlank = ' '.isNullOrEmpty; // false final isLineBreak = '\n'.isNullOrEmpty; // false ``` +### .isNullOrBlank + +Returns `true` if the String is either `null` or blank. + +```dart +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. + +```dart +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. diff --git a/lib/src/string.dart b/lib/src/string.dart index 47fa254..1f2d561 100644 --- a/lib/src/string.dart +++ b/lib/src/string.dart @@ -254,3 +254,13 @@ extension NullableStringIsNotNullOrEmptyExtension on String? { /// Returns `true` if the string is neither null nor empty. bool get isNotNullOrEmpty => !isNullOrEmpty; } + +extension NullableStringIsNullOrBlankExtension on String? { + /// Returns `true` if the string is either `null` or blank. + bool get isNullOrBlank => this?.isBlank ?? true; +} + +extension NullableStringIsNotNullOrBlankExtension on String? { + /// Returns `true` if the string is neither null nor blank. + bool get isNotNullOrBlank => !isNullOrBlank; +} diff --git a/test/string_test.dart b/test/string_test.dart index 6a5aed5..a2d0e49 100644 --- a/test/string_test.dart +++ b/test/string_test.dart @@ -161,6 +161,22 @@ void main() { expect('\n'.isNotNullOrEmpty, true); }); + test('.isNullOrBlank', () { + expect(null.isNullOrBlank, true); + expect(''.isNullOrBlank, true); + expect(' '.isNullOrBlank, true); + expect('\n'.isNullOrBlank, true); + expect(' foo '.isNullOrBlank, false); + }); + + test('.isNotNullOrBlank', () { + expect(null.isNotNullOrBlank, false); + expect(''.isNotNullOrBlank, false); + expect(' '.isNotNullOrBlank, false); + expect('\n'.isNotNullOrBlank, false); + expect(' foo '.isNotNullOrBlank, true); + }); + test('.toUtf8()', () { expect(''.toUtf8(), []); expect('hello'.toUtf8(), [104, 101, 108, 108, 111]);