toSlug method Null safety

String? toSlug()

Returns the string to slug case.

Example

String foo = 'hello world';
String fooSlug = foo.toSlug(); // returns 'hello_world'

Implementation

String? toSlug() {
  if (this == null) {
    return null;
  }
  if (this!.isEmpty) {
    return this;
  }

  var words = this!.trim().split(RegExp(r'(\s+)'));
  var slugWord = '';

  if (this!.length == 1) {
    return this;
  }
  for (var i = 0; i <= words.length - 1; i++) {
    if (i == words.length - 1) {
      slugWord += words[i];
    } else {
      slugWord += words[i] + '_';
    }
  }
  return slugWord;
}