String in Dart
Dart

String in Dart

Hey guys, welcome to the new article! Today, we’re diving into String in Dart. If you’re new to programming, Strings are essential for handling text data like names, addresses, or even entire text of books.

In computer programming, a String is a sequence of characters. While computers speak in numbers, every character in a String is assigned a unique number within the computer’s language, forming what’s called a character set.

Once you create a String in Dart, you can’t change its characters directly; you create a new String if modification is needed. Each character in a Dart String is represented by a 16-bit code unit, allowing Dart to handle a wide range of characters from various languages.

When you press a key on your keyboard, you’re essentially sending a number to the computer, which converts it into the corresponding character and displays it to you.

Unicode

In isolation, a computer is free to choose whatever character set mapping it likes. If the computer wants the letter a to equal to number 10, then so be it. But when computers start talking to each other, they need to use a common character set.

If two computers used different character sets, then when one computer transferred a string to the other, they would end up thinking the strings contained different characters.

There have been several standards over the years, but the most modern standard is Unicode. It defines the character set mapping that almost all computer use today.

As an example, consider the word cafe. The Unicode standard tells us that the letters of this word should be mapped to number like so:

cafe
9997102101
Unicode

The number associated with each character is called a code point. So in the example above, c uses code point 99, a uses code point 97 and so on.

Of course, Unicode is not just for the simple Latin characters from languages around the world. The word cafe as you’re probably aware, is derived from French, in which it’s written as café. Unicode maps these characters like so:

café
9997102233
Unicode

And here’s an example using simplified Chinese characters that mean “I love you”:

251052923320320
Unicode

You’re familiar with the small pictures called emojis that you can use when texting your friends. These pictures are, in fact, just normal characters and are also mapped by Unicode.
For example:

🎯😂
127919128514
Unicode

These are only two characters. The code points for them are very large numbers, but each is still only a single code point. The computer considers them no different than any other two characters.

The word “emoji” comes from the Japanese 絵⽂ ,字 where “e” means picture and “moji” means character.

Note:

The numbers for each of the characters above were written in decimal notation, but you usually write Unicode code points in hexadecimal format. Here they are again in hex:

café🎯😂
636166E9621172314F601F3AF1F602
Unicode

Work with String in Dart

Dart, like any good programming language, can work directly with strings. It does so through the String data type.

If we talk about strings and characters, you have already seen a Dart string in my previous articles where you printed one:

print("Hello, Dart!");

You can extract that same string as a named variable:

var greeting = 'Hello, Dart!';
print(greeting);

So, what do you think about var greeting? Yes, right! The right-hand side of this expression is known as a string literal. Due to type inference, Dart knows that greeting is of type String. Isn’t that such a magical thing?

Since you used the var keyword, it means it’s a mutable variable, so you’re allowed to reassign the value of greeting as long as the new value is still a string.

var greeting = 'Hello, Dart!';
greeting = 'Hello, Flutter!';

Even though you changed the value of greeting here, you didn’t modify the string itself. That’s because strings are immutable in Dart. It’s not like you replaced ‘Dart’ in the first string with ‘Flutter’. No, you completely discarded the string ‘Hello, Dart!’ and replaced it with a whole new string whose value is ‘Hello, Flutter!’

Char

If you’re familiar with other programming languages, you may be wondering about a Characters or char type. Dart doesn’t have that.
Take a look at this example:

const letter = 'a';


So here, even though letter is only on character long, it’s still of type String.

But strings are a collections of characters, right? What if you want to know the underlying number value of the character?
No problem. Keep reading.

Dart strings are a collection of UTF-16 code units. UTF-16 is a way to encode Unicode values by using 16-bit numbers. If you want to find out what those UTF-16 codes are, you can do it like so:

var salutation = 'Hello!';
print(salutation.codeUnits);


This will print the following list of numbers in decimal notation:

[72, 101, 108, 111, 33]


H is 72, e is 101, and so on.

These UTF-16 code units have the same value as Unicode code points for most of the characters you see on a day to day basis. However, 16 bits only give you 65,536 combinations, and believe it or not, there are more than 65,536 characters in the world! Remember the large numbers that the emojis? You’ll need more than 16 bits to represent those values.

UTF-16 has a special way of encoding code points higher than, 65,536 by using tow code units called surrogate pairs.

const dart = '🎯';
print(dart.codeUnits);
//[55356, 57263]

The code point for 🎯 is 127919, but the surrogate pair for that in UTF-16 is 55356 and 57263. No one wants to mess with surrogate pairs. It would be much nicer to just get Unicode code points directly. And you can! Dart calls them runes.

Single-quotes vs. double-quotes

In dart programming langauge we are allow to use either single-quotes or double quotes for string literals. Both of these are fine:

'I like cats'
"I like cats"

Although Dart doesn’t have a recommended practice, the Flutter style guide does recommend using single-quotes, so the article will also follow that practice.

You might want to use double-quotes, through, id your string includes any apostrophes.

"my cat's food"

Otherwise you would need to use the backslash \ as an escape character so that Dart knows that the string isn’t ending early:

'my cat\'s food'

Concatenation

You can do much more than create simple stings. Sometimes you need to manipulate a string, and one common way to do so is to combine it with another string.
This is called concatenation…with no relation to the aforementioned felines.

In Dart, you can concatenate string simply by using the addition operator. Just as you can add numbers, you can add strings:

var message = 'Hello' + ' my name is ';
const name = 'Ray';
message += name;
//'Hello my name is Ray'

String Buffer

You need to declare message as a variable, rather than a constant, because you want to modify it. You can add string literals together, as in the first line, and you can add string variables or constants together, as in third line.

If you find yourself doing a lot of concatenation, you should use a string buffer, which is more efficient.

final message = StringBuffer();
message.write('Hello');
message.write('my name is);
message.write('Ray');
message.toString();
// "Hello my name is Ray"

This create a mutable location in memory where you can add to the string without having to create a new string for every change. When you’re all done, you use toString to convert the string buffer to the String type.

Interpolation

You can also build up a string by using interpolation, which is a special Dart syntax that lets you build a string in a manner that’s easy for other people reading your code to understand:

const name = 'Ray'
const introduction = 'Hello my name is $name';
// 'Hello my name is Ray'

This is much more readable than the example in the previous section. It’s an extension of the string literal syntax, in which you replace certain parts of the string with other values. You add a dollar sign($) in front of the value that you want to insert.

The syntax works in the same way to build a string from other data types such as numbers:

const oneThird = 1/3;
const sentence = 'One third is $oneThird.';
//Output is
One third is 0.3333333333333333.

Here, you use a double for the interpolation. Your sentence constant will contain the following value:

Of course, it would actually take an infinite number of characters to represent one-third as a decimal, because it’s a repeating decimal. You can control the number of decimal places shown on a double by using toString AsFixed along with the number of decimal places to show:

final sentence = 'One third is ${oneThird.toStringAsFixed(3)}.';

There are a few items of interest here:

  • You’re requesting the string to show only three decimal places.
  • Since you’re performing an operation on oneThird, you need to surround the expression with curly braces after the dollar sign. This lets Dart know that the dot (.) after oneThird isn’t just a regular period.
  • The sentence variable need to be final now instead of const because toStringAsFixed(3) is calculated at runtime.

Here’s the result:

One third is 0.333.

Multi-line strings

Dart has a neat way to express strings that contain multiple lines, which can be rather useful when you need to use very long strings in your code.

You can support multi-line next like so:

const bigString = ''' 
You can have a string 
that contains multiple lines
by doing this. ''';
print(bigString);

The three single-quotes (‘ ‘ ‘) signify that this is a multi-line string. Three double-quotes (” ” ” ) would have done the same thing.

The example above will print the follwoing:

You can have a string
that contains multiple lines 
by doing this.

Notice that all of the newline locations are preserved. If you just want to use multiple lines in code but don’t want the output string to contain newline characters, then you can surround each line with single-quotes:

const oneLine = 'This is only'
'a single'
'line'
'at runtime.';

That’s because Dart ignores whitespace outside of quoted text. This does the same thing as if you concatenated each of those lines with the + operator:

const oneLine = 'This is only' + 'a single ' + 'line' + ' at runtime. ';

However, sometimes you want to ignore any special characters that a string might contain. To do that, you can create a raw string by putting r in front of the string literal.

const rawString = r'My name \n is $name.';

and that’s exactly what you get:

My name \n is $name.

Inserting characters from their codes

Similar to the way you can insert a newline character into a string using the \n escape sequence, you can also add Unicode characters if you know their codes. Take the following example:

print('I \u2764 Dart\u0021');

Here, you’ve used \u, followed by a four-digit hexadecimal code unit value. 2764 is the hex value for the heart emoji, and 21 is the hex value for an exclamation mark. Since 21 is only two digits, you pad it with extra zeros as 0021.

This prints:

I ❤️ Dart!

For code points with values higher than hexadecimal FFFF, you need to surround the code with curly braces:

print('I love \u{1F3AF}');

This prints:

I love 🎯

In this way, you can form any Unicode string from its codes.

Read my previous article
Type Inference Variable in Dart

6 thoughts on “String in Dart

  1. Pingback: Loop in Dart
  2. Pingback: Dart OOPs Concept

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top