First off let’s define some criteria for this extension:
- It should return true if the object is null or an empty string.
- I should be able to use it on a chained nullable object.
- I should not have to use parentheses, type casts or
== 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.
2
Answers
I tried to write code according to all the criteria and it turned out like this
But without parentheses with a null object it produces null and not boolean
Yes, it is possible to create a String extension isEmptyOrNull in Dart.
To use the extension, you can simply call the isNullOrEmpty method on any string variable. For example: