skip to Main Content

First off let’s define some criteria for this extension:

  1. It should return true if the object is null or an empty string.
  2. I should be able to use it on a chained nullable object.
  3. 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


  1. 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

    Login or Signup to reply.
  2. 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
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search