Dart - Reverse a String Examples

This tutorial gives you examples of how to reverse a String in Dart programming language. This also works for any Dart framework including Flutter.

If you have a String in Dart and you want to reverse the order of the characters, there are several ways to do it. Below are the examples.

Reverse Using Split and Join

Dart's String doesn't have a built-in class member for reversing the characters. However, Dart's List has reversed getter. We can utilize it to reverse a String. The solution is to split the String into a List of characters, get the characters in the reversed order using the reversed getter, and join the List into a String.

  String reverseUsingSplitAndJoin(String text) {
    final chars = text.split('');
  
    return chars.reversed.join('');
  }

Reverse Using Runes

Another way to reverse is by getting the runes property of the String. The runes property returns an Iterable of unicode code-points (int) of the characters. The Iterable can be converted into a List by calling the toList method. Just like the previous method, use List's reversed property to get the elements in the reversed order. To convert the character codes to a String, use the factory method String.fromCharCodes.

  String reverseUsingRunes(String text) {
    final chars = text.runes.toList();
  
    return String.fromCharCodes(chars.reversed);
  }

Reverse Using Code Units

You can also get the codeUnits property of the String which returns a List of UTF-16 code units (int). Then, use the reversed method to reverse the order of the characters and convert it to a String using String.fromCharCodes factory method.

  String reverseUsingCodeUnits(String text) {
    final chars = text.codeUnits;
  
    return String.fromCharCodes(chars.reversed);
  }

Summary

Without any additional library, there are several ways to reverse a String in Dart. The first one is to split the String into a List of characters, reverse the order of the characters, and join the reversed characters. It can also be done by getting the runes or codeUnits of the String, reversing the order of the character codes and converting the character codes into a String.