Skip to content
DeveloperMemos

Getting a substring in Dart

Dart, Flutter, Flutter Tips1 min read

I was trying to figure out the most efficient way to trim or shorten a String in Dart(more speficially for a Flutter project) yesterday. There's actually a couple of different ways to do it.

The substring method

The first and most typical one is using the substring method. The use case is pretty simple, you call substring on your string and specify a start and end index:

1final name = "developermemos";
2final portion = name.substring(0, 9); // developer

While it's easy to understand it wasn't great for my use case because I just wanted to shorten an existing string, and if you specify an end index that your string doesn't contain(for example 20 for the above case hypothetically) you will get a RangeError.

The characters approach

What I wanted to do was get the first x characters for a string that could potentially have a length of anything above 0. I found out that the easiest approach for this case is to use .characters.take on the string, here's an example:

1final name = "developermemos";
2final portion = name.characters.take(9).toString(); // developer

The good thing about this approach is that you won't get a RangeError like you would with substring if you specify an index that is too high, it will just return the entire string instead:

1final name = "developermemos";
2final portion = name.characters.take(30).toString(); // developermemos

This was perfect for my particular use case. The only caveat is that it seems like while the above will work without any imports in Flutter, if you are using plain Dart you need to add and import the characters package.

Bonus: The takeLast method

There's also another method called takeLast that does pretty much the same thing as take but in reverse, it will take the last x characters from a string. If you use a count that is higher than the length of the string itself it will just return the entire string. Here's a quick example:

1final name = "developermemos";
2final portion = name.characters.takeLast(5).toString(); // memos