Reputation: 4040
First off let's define some criteria for this extension:
== true
when using the extension.Here is an example that should work:
extension StringExtension on String? {
bool get isEmptyOrNull {
// Implementation
}
}
class MyObject {
MyObject({this.myString});
final String? str;
}
// somewhere in the code:
final MyObject? obj = null;
if(obj?.str.isEmptyOrNull){
print('object was empty string or had the value null');
}
If this code compiles, follows all the criteria, and writes the correct output I would consider the solution correct.
Upvotes: 2
Views: 599
Reputation: 11220
The operatot ?.
is a conditional member access operator.
A conditional member access operator applies a member access (?.
) operation to its operand only if that operand evaluates to non-null; otherwise, it returns null
. That is:
If a
evaluates to null, the result of a?.x
is null
.
If a
evaluates to non-null, the result of a?.x
is the same as the result of a.x
.
This way your code will never be able to compile.
final MyObject? obj = null;
if(obj?.str.isEmptyOrNull){
print('object was empty string or had the value null');
}
Upvotes: 1
Reputation: 11
How about this approach?
extension StringExtension on String? {
bool get isEmptyOrNull => this?.isEmpty ?? true;
}
class MyObject {
MyObject({this.myString});
final String? str;
}
// somewhere in the code:
final MyObject? obj = null;
if (obj?.str.isEmptyOrNull) {
print('Object was empty string or had the value null');
}
Upvotes: 1
Reputation: 31
Yes, it is possible to create a String extension isEmptyOrNull in Dart.
extension StringExtensions on String {
bool get isNullOrEmpty => this == null || isEmpty;
}
To use the extension, you can simply call the isNullOrEmpty method on any string variable. For example:
String myString = '';
if (myString.isNullOrEmpty) {
// The string is null or empty
} else {
// The string is not null or empty
}
Upvotes: 1
Reputation: 443
I tried to write code according to all the criteria and it turned out like this
extension StringExtension on String? {
bool get isNull => this == null;
bool get isEmptyOrNull => isNull || this!.isEmpty;
}
class MyObject {
MyObject({this.str});
final String? str;
}
// somewhere in the code:
void main() {
const MyObject? objNull = null;
final MyObject objStrNull = MyObject();
final MyObject objStrEmpty = MyObject(str: '');
final MyObject objStrNotEmpty = MyObject(str: 'str');
print(objNull?.str.isEmptyOrNull); // null
print((objNull?.str).isEmptyOrNull); // true
print(objStrNull.str.isEmptyOrNull); // true
print(objStrEmpty.str.isEmptyOrNull); // true
print(objStrNotEmpty.str.isEmptyOrNull); // false
}
But without parentheses with a null object it produces null and not boolean
Upvotes: 1