Sage-Code Laboratory
index<--

Dart Types

Dart is object oriented and is using a hierarchy of classes to create data types. Everything you can place in a variable is an object, and every object is an instance of a class. Even numbers, functions, and null are objects. All objects inherit from the Object class.

Basic Types

The Dart language has special support for the following basic types:

Note: Dart has type inference. That means you do not have to make type annotations. Most of the time, the compiler will determine the data type from the literals or expressions you are using to declare the variables.

Numbers

Dart has two kind of numbers: discrete: integer and continuous: double-precision. With these two it keeps things simple and covers a wide range of computations. Both numbers occupy 64-bit.

Examples:

//simple Dart literals
var x = 10;         //integer
var h = 0xDEADBEEF; //integer
var y = 1.1;        //double
var e = 1.25e3;     //double

Implicit coercion:

Numbers are converted implicit when possible in this direction: int->double. In next example we use an integer literal but a double literal is required. However the compiler will not complain.

void main() {
  //implicit coercion
  double x = 10;
  print(x); // 10.0
}

Explicit coercion:

For conversion in this direction: double->int we can loose some data. In this case only explicitly coercion is possible: There are functions available to do the job.

void main() {
  //explicit coercion
  double y = 2.25;
  int a = y.floor();
  int b = y.ceil();

  print(a); // 2
  print(b); // 3
}

Homework: Let's try this example on-line: declare-vars

Constants

In Dart, a constant is an immutable value that can be assigned only once.

To create a constant, use the "const" keyword followed by the value you want to assign.

For example:


const int x = 5;
const String name = 'John';

The "const" keyword can be used with various data types in Dart, including numbers, strings, lists, and maps.

Constants are useful when you need to ensure that a value doesn't change during runtime, such as when you're working with configuration values or mathematical constants.

Note that constants are different from variables, which can be reassigned with a new value during runtime.

Strings

A string is a sequence of code units. You can use either single or double quotes to create a string. Dart strings are encoded using Unicode UTF-16. You can use single or double quotes to create string literals.

Examples:

//simple Dart strings
var message = 'Sage-Code teaches Computer Science for free!';
var why = "It's a hobby of the author.";

Conversion:

There is a technique often used to convert numbers into strings so that you can print the number withing a text. It is also possible to convert a string into a number but this require special attention since the string may contain something else and conversion may fail.

Example:

Number to string conversion:

// int -> String
String literalString = 101.toString(); // '101'

// double -> String
String piAsString = 3.1415.toStringAsFixed(2); // 3.14

Example:

String to number conversion:

// String -> int
var number = int.parse('101'); // 101

// String -> double
var piNumber = double.parse('3.14'); // 3.14

Interpolation:

You can use a special notation to insert the result of an expression inside to a string. The expression can be as simple as a variable or complex like the result of a function.

Example 1:

You can use "$var_name" notation to include a variable value into a string:

// using variable name
var name = "Elucian";
var twitter = "@elucian_moise";
print("May name is: $name");
print("My twitter is: $twitter");

Output:

May name is: Elucian
My twitter is: @elucian_moise

Example 2:

You can use "${expression}" notation to include result of expression into a string. This is very convenient way to create output strings.

// using toUpperCase() function
var language = "html";
print("Is: ${language.toUpperCase()} a programming language?");

Output:

Is: HTML a programming language?

Concatenation:

Strange but you can use "+" to concatenate two strings. This is the usual method, but in Dart there are other methods to concatenate strings, as we show in next examples.

Example 1:

You can not concatenate a string to a number. For this you can use interpolation or you can convert the number to string before be able to concatenate.

// using concatenation
void main() {
   var test = '10' + 10.toString();
   print(test); //1010
}

Output:

1010

Example 2:

Dart offer you surprises. Adjacent strings are automatically concatenated without "+" this can be useful for long strings that do not feet on a single line just in case you want to break it. The end of line is not included in string:

// using concatenation
void main() {
   var test = 'this is' " a "
              'test';
   print(test); //this is a test
}

Raw strings:

A regular string support escape sequences, for example "\n" represents new line. However there is a way to create "raw" strings that are immune to escape substitution. For this you add a small "r" before the string literal.

// using raw string
var test = r'escape sequence \n '
            'do not work inside '
            'raw strings.';
print(test); //

Output:

escape sequence \n do not work inside raw strings.

Triple quotes:

Python has introduced first time triple quoted strings. This notation is now popular among new computer languages, also Java was upgraded and so it is supported in Dart.

//using triple quoted strings
void main() {
    //incorrect indentation
    var s1 = '''
            You can create
            multi-line strings like this one.
            ''';
    print(s1);
    //correct indentation
    var s2 = """This is also a
multi-line string.""";
    print(s2);
}
Warning:  You think Dart is smart and will remove indentation spaces, but not so. The indentation spaces are preserved. You must be creative when you create multi-line strings with this technique.

Booleans

Boolean type is also known as logic type. It supports only two values: true and false. You can declare a Boolean using "var" or "bool" keywords. I mean, hold on, I lied. Boolean null is partially supported. A "bool" variable is null when not assigned. But this values are not valid in Boolean expressions.

Example:

//using Boolean
void main() {
    var b1 = true;
    bool b2 = false;
    bool b3;    //incorrect declaration
    print(b1);  //true
    print(b2);  //false
    print(b3);  //null (surprise)
}

The table of truth

Next table will help you understand better all possible combinations of values and the result yield by logical operators: "!" = NOT, "||" = OR, "&& "=  AND.

PQ!PP || QP && Q
falsefalsetrue falsefalse
true falsefalsetrue false
falsetrue true true false
true true falsetrue true

Comparison

Comparison operators like "==" or "!=" will create Boolean results based on non Boolean values. This operator can be used for: numbers, string as well as Boolean values. A less know trick is to assign result of expressions to a Boolean variable. Check this out:

//using comparison operators
void main() {
    //compare numbers
    bool b1 = 1 == 1;
    assert (b1); // true

    //compare booleans
    bool b2 = true == b1;
    assert (b2); // true

    //compare strings
    bool b3 = "this"!="that";
    assert (b3); // true

    //compare strings
    bool b4 = "yes is winter" =="yes " "is " "winter";
    assert (b4); // true

    print("done.");
}

Homework: Open on-line then modify this program to demonstrate that (1 < 2) and ( 2 > 0 ): dart-comparison


Read next: Functions