Dart Programming


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:

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';

Here is some additional notes on variables in Dart:


“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.

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.

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 dartprogramming.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


Hello world!


Copyright © 2024 dartprogramming.com
All rights reserved.