OneBite.Dev - Coding blog in a bite size

Check If A String Is A Palindrome In Dart

Code snippet for how to Check If A String Is A Palindrome In Dart with sample and detail explanation

Palindromes are patterns within texts that can improve our understanding of language and computational abilities. This article will help you understand how to verify if a string is a palindrome using Dart language.

Code snippet for Checking if a String is a Palindrome

In Dart, we can easily detect whether a string is a palindrome or not. Here’s a simple function that can do it:

bool isPalindrome(String str) {
  String reversed = str.split('').reversed.join('');
  return str == reversed;
}

You can use this function like so:

void main() {
  print(isPalindrome('madam'));  // true
  print(isPalindrome('hello'));  // false
}

Code Explanation for Checking if a String is a Palindrome

Let’s breakdown the function ‘isPalindrome’. The function isPalindrome takes a string str as an argument.

On the first line of the function, we’re reversing the string.

String reversed = str.split('').reversed.join('');

The split('') function breaks the string into a list of substrings. In this case it returns a list of all the characters.

reversed is a property that can be accessed to get an iterable that iterates over the elements of the list in reverse order.

With join('') we are converting back the Iterable to a string. This gives us a new string that is the reverse of the original.

Finally, the return line checks if the reversed string is equal to the input string:

return str == reversed;

If they are identical, this means the string is a palindrome, and the function will return true. Otherwise, it will return false.

That’s all! With these steps, you can check if any string is a palindrome using Dart.

dart