last method Null safety

String? last(
  1. {int n = 1}
)

Returns the last n characters of the string.

n is optional, by default it returns the first character of the string.

If n provided is longer than the string's length, the string will be returned.

Faster than using

substring(length-n,length)

Example 1

String foo = 'hello world';
String firstChars = foo.last(); // returns 'd'

Example 2

String foo = 'hello world';
bool firstChars = foo.last(3); // returns 'rld'

Implementation

String? last({int n = 1}) {
  if (this == null) {
    return null;
  }
  if (this!.isEmpty) {
    return this;
  }
  if (this!.length < n) {
    return this;
  }
  return this!.substring(this!.length - n, this!.length);
}