Strings in Dart

The Dart programming language has many handy string manipulation features, which are commonly used and essential to most applications.

void main() {
  String fruit = 'orange';
  print(fruit.length);
}
// Result: 6

Sometimes you may want to use the string length value directly within a string value, which can be done using curly brackets after the dollar sign.

void main() {
  String fruit = 'orange';
  print("The word orange has ${fruit.length} letters.");
}
// Result: The word orange has 6 letters.

If you wanted double quotation marks around the word “orange” to make it stand out, then one way to do this is using the backslash character \ to escape or tell Dart to treat that character as part of the string value, like below.

void main() {
  String fruit = 'orange';
  print("The word \"orange\" has ${fruit.length} letters.");
}
// Result: The word "orange" has 6 letters.

Although, another way to do this is to use single quotes to indicate the beginning and end of the string text value.

void main() {
  String fruit = 'orange';
  print('The word "orange" has ${fruit.length} letters.');
}
// Result: The word "orange" has 6 letters.

Variables in Dart

Using our previous example that prints out some text to the output console, lets now create a variable to store the text, so we can re-use it.

void main() {
  var a = 'Hello World';
  print(a);
  print(a);
}

The above should print out two instances of the text “Hello World”, instead of just one. Instead of having the full longer text duplicating for each print() statement, we can store the full text in a variable we called “a” and then tell the program to print out what is stored in the variable.

Every time you create a variable, you need to use the keyword “var” at the beginning to indicate that it is a variable that you are creating. You can name your variables nearly anything you would like, as long as follows the following languages rules:

  • cannot be keywords
  • cannot have spaces or special character, except
  • underscores (_) and dollar signs ($)
  • cannot begin with a number

Here are a few examples of valid variable names:

void main() {
  var a = 'My variable a';
  print(a);
  var b = 'My variable b';
  print(b);
  var myVar = 'My variable myVar';
  print(myVar);
  var my_var = 'My variable my_var';
  print(my_var);
  var myVar3 = "My variable myVar3";
  print(myVar3);
}

You only need to use the keyword “var” at the beginning the first time you are creating and initializing the variable. Then after that you can leave off the keyword “var” and can also reassign or give the variable a new value or make it store something else that is similar, like this:

// This Dart program prints the first value of the variable "a" and then gives the variable "a" new value. Then it prints the new value too.

void main() {
  var a = 'First text';
  print(a);
  a = 'Second text';
  print(a);
}

When you create a variable in the Dart language, it automatically tries to recognize the type of variable you are trying to create, so in the example below, it set the type of variable to the type of “Text String”. This means that you can use that variable to store any text string you want, but will get an warning or error if you try to store something else that is not text in that same variable, as shown below:

void main() {
  var a = 'Some text';
  a = 7;
}
// Gives an error!

The above results in an error explaining that you cannot put a integer/number type value in a variable that is of a text string type. The text variable can only store text. This is why the Dart programming language is considered a statically typed language.

If you assign a number value to the variable “a”, then the variable will automatically be set to a “Number” type and will allow you to store any numbers in it. Go ahead and try this out and you should see it print out the two numbers:

void main() {
  var a = 100;
  print(a);
  a = 200;
  print(a);
}

You can also assign the resulting number of an mathematical equation as the number value the variable should store, like the this:

void main() {
  var a = 50 + 100;
  print(a);
}
// This Dart code prints 150 to the output console.

You can accomplish the same thing, by putting the equation in the print statement as well, like this:

void main() {
  var a = 50;
  print(a + 100);
}
// This Dart code also prints 150 to the output console.

It is worth experimenting with different types of numbers and combinations of where things are, to get understand how the results can be quite different, such as the following with negative and positive floating point numbers:

void main() {
  var a = -50.99;
  print(a + 100);
  // Result: 49.01
  
  var b = 50.99;
  print(b + 100);
  // Result: 150.99
}

Another option is to explicitly set the variable type to what you want it to be, instead of relying on the automatic variable type assignment to be inferred (type inference). The following explicitly set the variable type of “a” to text string type and if you try to store a number in it, you will get an error.

void main() {
  String a = 50;
  print(a);
}

But, if you put single or double quotes around the variable values to make them text strings, then it will print out the text to the console just fine. As well, you can add to string variables together like below, which is called string concatenation.

void main() {
  String a = 'The number ';
  String b = "3";
  print(a + b);
  // Result: The number 3

  String c = a + b + " is my favorite number.";
  print(c);
  // Result: The number 3 is my favorite number.
}

You can also insert variables directly inside the text string values, like the following (which is referred to as string interpolation).

void main() {
  String fruit = 'apple';
  print("Please eat an $fruit everyday.");
}
// Result: Please eat an apple everyday.

One other thing you can do that is probably worth noting at this point, is the ability to make a dynamic variable. So, if you create a variable named “a” and assign it a text string, it will be set to as a text type, but then if you re-assign it a number value, the variable type will automatically change to a number type.

void main() {
  dynamic a = "Some text";
  print(a);
  // Result: Some text

  a = 333;
  print(a);
  // Result: 333
}

Another example is when you are working with two different type of numbers and if you try to something like below, you will get an error, because the variable is automatically set as a integer number with no decimal.

void main() {
  var x = 3; // x is inferred as an int
  x = 4.0;
  print(x);
  // Gives an error!
}

So, one way to solve this is to make the variable dynamic, so that it will change the variable type after it creates and initializes the variable. In this case, from a double to an integer number type.

void main() {
  dynamic x = 4.5;
  x = 3;
  print(x);
}
// Result: 3

It is considered best practice to only use dynamic variables, if you don’t know what the variable type is going to be when it is initialized. Utilizing statically typed code can lead to code that is easier to use, safer and less error-prone.

If you know the variable type, then it is better to explicitly set the variable type as a number, so that you be sure your variable will stay some sort of number and not change to a text string, like this:

void main() {
  num x = 4.5;
  x = 3;
  print(x);
}
// Result: 3

Some variable types are more specific like double and integer (int), while other variable types like number (num) can be assigned an integer or a double number.

void main() {
  double a = 1.5;
  int b = 1;
  num c = 1.5;
  num d = 1;
  print(a + b + c + d);
  // Result: 5
}

It is good to be award that variables that are not assigned a value (uninitialized) but are created/declared and then used, will result in a null value, which essentially means that nothing is being stored in the variable, as illustrated below:

void main() { 
   var a; 
   print(a); 
}
// Result: null

There are also keywords that you can use when creating a variable to restrict the use of that variable, such as not allowing the variable’s value to be changed after first created or initialized. One such keyword is “final”, which makes it so the variable can only be assigned a value one time (single-assignment), so once the variable is initialized, the variable’s value cannot be changed. And, if you try to change the variable’s value, then you will get an error saying a final variable can only be set once, as illustrated below:

void main() { 
   final a = 3;
   print(a);
   a = 6;
}
// Result: Error!

When you use keywords such as final, it changes the mutability of the variable, meaning that if the keyword final is used, then the variable will be immutable. If the variable using the var keyword then it will be mutable.

void main() { 
  var a = 3;
  // The a variable is mutable, so its value can change.

   final b = 6;
  // The b variable is immutable, so its value can not change.
}

If you know that a variables value is not going to change, then it is usually best to make the variable immutable whenever possible, as a best practice.

To review the basic structure of a variable statement, lets look at the basic anatomy of the following text string variable assignment statement.

String fruit = 'apple';
  • The left side of the equal sign is the variable declaration:
    • String is the variable type
    • name is the variable name
  • The rest of the statement is the variable initialization:
    • = the equal sign indicates assignment
    • ‘apple’ is a string literal or the value
    • ; the semicolon is the terminator ending

Here is some additional notes on variables in Dart:

  • variables are named spaces in computer memory
  • variables act as containers to store values
  • variable names are called identifiers
  • variables must be declared before they can be used
  • variables in Dart store a reference to the value, rather than containing the value
  • variables have an initial value of null
  • the Dart language considers all values as objects

“Hello World” in Dart

As tradition has it, this is how you simply print out the text “Hello World” to the output console in Dart:

main() {
  print("Hello World");
}

There is a main() function, which is where every Dart program start executing your code.

  • main() is where your application starts.
  • the curly brackets { } indicate what code is part of the main function.
  • the print command tells the program to write something to an output console.
  • the parenthesis ( ) indicate what code is part of the print statement.
  • the double quotes ” ” indicate a string of text that should be part of what gets printed out to the console.
  • the semicolon ; at the end is the terminator, indicating the end of the print command.

Most of the time you will see a keyword like “void” in front of the function name like the following, which indicated this function does not return a value back, but simply just print the text to the console.

void main() {
  print("Hello World");
}

You will also usually see a comment in the code (indicated by the two forward slashes) explaining what the code is supposed to do or even just information about the code, like who wrote the code.

// This Dart program simply prints two words.
void main() {
  print("Hello World");
}

Go ahead and try this out using the free online editor called DartPad available here: https://dartpad.dartlang.org/

The Dart Programming Language

Dart 2 (https://www.dartlang.org/) was a huge improvement over the previous Dart language releases and helped launch Dart into a category of being a mainstream programming language. The success of Dart 2 is largely due to the hard work of Google’s Dart Team and some key advocate users of the language. Dart is free, open-sourced and developed on GitHub here: https://github.com/dart-lang

Dart is still somewhat unique, as a computer programming language, due to the fact that it offers both a virtual machine (VM) and it can compile to native code or cross-compile (transpile) to JavaScript.

The language itself has a C-style syntax and is considered a general-purpose language, meaning you can use it to build web, server, desktop, command line and cross-platform mobile apps (via Flutter).

The Dart language was originally developed by Google and later approved as a open standard by Ecma (ECMA-408). Learn more on the Wikipedia Dart (programming language) page here: https://en.wikipedia.org/wiki/Dart_(programming_language)

Dart is an object-oriented, class defined, statically typed, garbage-collected, interface supporting with mixin classes.

  • Object-Oriented: meaning the code is structured inside classes that hold data and have methods.
    • Methods are subroutines that can manipulate and do operations on objects or classes.
  • Class Defined: meaning that the classes act as template definitions of the methods and variables for each particular kind of object.
  • Statically Typed: meaning that the type of variables will be known at compile time, making for a sound type system that helps us write safer and more predictable code.
  • Garbage-Collected: means there are automatic memory management features of the Dart language that attempt to reclaim memory occupied by objects that are no longer being used by the program.
  • Interface Supporting: meaning that Dart supports interface-based programming architecture, which is a sort of architectural pattern aiming to modularize and structure code to help make your application easier to test and maintain.
  • Mixin Supporting: means that Dart supports classes that contain methods for use by other classes without needing to be the parent class.

Dart has plenty of solid mission-critical production use examples, such as Google’s Adwords, AdSense and AdMob. Supposedly, over 75% of Google’s revenue flows through these platforms, so it would suffice to say that Google is heavily invested in the Dart language and further proves it by introducing the cross-platform mobile framework called Flutter, which allows the creation of iOS and Android app development from a single codebase. Read more here about who uses Dart: https://www.dartlang.org/community/who-uses-dart

Using the Dart programming language can increase productivity and efficiency due to having a just-in-time (JIT) compiler, which allows the ability to compile code on-the-fly that hot reloads your application. But, Dart also comes with an ahead-of-time (AOT) compiler, which will compile your code before runtime to make it execute faster.

You can easily start trying out the Dart programming language for yourself using a free online editor called DartPad available here: https://dartpad.dartlang.org/

GTmetrix Performance Report

(For dartcoding.com homepage.)

Performance Scores:
 – PageSpeed Score = A (99%)
 – YSlow Score = A (97%)

Page Details
 – Fully Loaded Time = 0.8s
 – Total Page Size = 32.8KB
 – Requests = 9

NOTES:
Lowest scores are for inline small JavaScript and query strings for static resources.  Also, doesn’t appear that CSS or JavaScript is being completely minified yet.

Test server region: Vancouver, Canada
Using: Chrome (Desktop) 62.0.3202.94, PageSpeed 1.15-gt1, YSlow 3.1.8

Report generated:Wed, Dec 12, 2018, 10:23 PM -0800