Dart Grammar Foundation Series Four Basic Data Types

Dart's basic built-in type in programming

Dart supports the following built-in types:

  • Number
  • String
  • Boolean
  • List (also known as Array)
  • Map
  • Set
  • Rune (used to represent Unicode characters in strings)
  • Symbol

These types can be initialized to literals. For example,'this is a string'is a literal quantity of a string, and true is a Boolean literal quantity.

Because all variables in Dart are ultimately an object (an instance of a class), variables can be initialized using the number of construction connotations. Some built-in types have their own constructors. For example, a map variable is constructed using Map().

 

Number

There are two types of Number in Dart:

int
Integer values are no larger than 64 bits, depending on the platform. On Dart VM, values range from -263 to 263 - 1.When Dart is compiled as JavaScript, JavaScript numbers are used, with values ranging from -253 to 253 - 1.

double
64-bit (double-precision) floating point number, according to the IEEE 754 standard.

Both int and double are subtypes of num.Num types include basic operations+, -, /, and*, as well as functional methods such as abs(), ceil(), and floor(), etc. (Bitwise operators, such as, are defined in the int class.) If num and its subtypes cannot find the method you want, try to find out how to use the dart:math library.

Integer types do not contain decimal points. The following are examples of defining literal quantities of integer types:

var x = 1;
var hex = 0xDEADBEEF;

If a number contains a decimal point, it is of the decimal type. Here is an example of defining literal quantities of the decimal type:

var y = 1.1;
var exponents = 1.42e5;

Starting with Dart 2.1, the int literal quantity is automatically converted to the double type when necessary.

double z = 1; // Equivalent to double z = 1.0.

The following is how strings are converted to numbers and vice versa:

// String -> int
var one = int.parse('1');
assert(one == 1);

// String -> double
var onePointOne = double.parse('1.1');
assert(onePointOne == 1.1);

// int -> String
String oneAsString = 1.toString();
assert(oneAsString == '1');

// double -> String
String piAsString = 3.14159.toStringAsFixed(2);
assert(piAsString == '3.14');

int-specific traditional bitwise operations, shift (<<, >), bitwise and (&), and bitwise or (|). For ex amp le:

assert((3 << 1) == 6); // 0011 << 1 == 0110
assert((3 >> 1) == 1); // 0011 >> 1 == 0001
assert((3 | 4) == 7); // 0011 | 0100 == 0111

Number type literals are compile-time constants. In arithmetic expressions, the result of an arithmetic expression is compile-time constants as long as the factors involved in the calculation are compile-time constants.

const msPerSecond = 1000;
const secondsUntilRetry = 5;
const msUntilRetry = secondsUntilRetry * msPerSecond;

 

String

The Dart string is a sequence of UTF-16 units. Strings are created with single or double quotes.

var s1 = 'Single quotes work well for string literals.';
var s2 = "Double quotes work just as well.";
var s3 = 'It\'s easy to escape the string delimiter.';
var s4 = "It's even easier to use the other delimiter.";

Strings can be embedded in an expression by ${expression}. If the expression is an identifier, {} can be omitted. In Dart, the string corresponding to the object is obtained by calling the toString() method on the object.

var s = 'string interpolation';

assert('Dart has $s, which is very handy.' ==
    'Dart has string interpolation, ' +
        'which is very handy.');
assert('That deserves all caps. ' +
        '${s.toUpperCase()} is very handy!' ==
    'That deserves all caps. ' +
        'STRING INTERPOLATION is very handy!');

Tip: ==The operator is used to test whether two objects are equal. In a string, if two strings contain the same encoding sequence, the two strings are equal.

You can use the + operator to concatenate multiple strings into one, or you can write multiple literal strings together to achieve string concatenation:

var s1 = 'String '
    'concatenation'
    " works even over line breaks.";
assert(s1 ==
    'String concatenation works even over '
    'line breaks.');

var s2 = 'The + operator ' + 'works, as well.';
assert(s2 == 'The + operator works, as well.');

Use three consecutive single or three double quotes to create a multiline string object:

var s1 = '''
You can create
multi-line strings like this one.
''';

var s2 = """This is also a
multi-line string.""";

Using the r prefix, you can create the "raw" string:

var s = r"In a raw string, even \n isn't special.";

In a literal string of compile-time constants, if an interpolation expression exists and the content of the expression is also a compile-time constant, the string remains a compile-time constant. Inserted constants can be null, numeric, string, or Boolean.

// const type data
const aConstNum = 0;
const aConstBool = true;
const aConstString = 'a constant string';

// Data of non-const type
var aNum = 0;
var aBool = true;
var aString = 'a string';
const aConstList = [1, 2, 3];

const validConstString = '$aConstNum $aConstBool $aConstString'; //const type data
// Const invalidConstString ='$aNum $aBool $aString $aConstList'; //Data of non-const type

Boolean

Dart uses the bool type to represent Boolean values. Dart only has the literal quantities true and false as Boolean types, which are compile-time constants.

Dart's type security means that you cannot use if (nonbooleanValue) or assert (nonbooleanValue). Instead, you should explicitly check the values as follows:

// Check for empty strings.
var fullName = '';
assert(fullName.isEmpty);

// Check 0 value.
var hitPoints = 0;
assert(hitPoints <= 0);

// Check the null value.
var unicorn;
assert(unicorn == null);

// Check NaN.
var iMeantToDoThis = 0 / 0;
assert(iMeantToDoThis.isNaN);

List

The most common set in almost every programming language may be array or an ordered set of objects. Array in Dart is a List object, often referred to as a List.

List literals in Dart are very similar to array literals in JavaScript. Here is an example of a Dart List:

var list = [1, 2, 3];

Tip: Dart infers that a list is of type List. If you try to add a non-integer object to this list, the analyzer or runtime will cause an error. For more information, read Type Inference.

Lists start with a subscript index of 0, and the index of the first element is 0. list.length-1 is the index of the last element. The length and elements accessing the List are the same as they are used in JavaScript:

var list = [1, 2, 3];
assert(list.length == 3);
assert(list[1] == 2);

list[1] = 1;
assert(list[1] == 1);

By adding the const keyword before the List literal, you can define a List-type compile-time constant:

var constantList = const [1, 2, 3];
// constantList[1] = 1; //Uncomment can cause errors.

Set

Set is a unique and unnecessary collection of elements in Dart. Dart provides Set literals and Set types for Sets.

Release Tip: Although the Set type has always been a core part of Dart, the Set literal quantity was introduced in Dart 2.2.

Here is a simple example of creating a Set with literal quantities:

var halogens = {'fluorine', 'chlorine', 'bromine', 'iodine', 'astatine'};

To create an empty set, use {} preceded by a type parameter, or assign {} to a variable of type Set:

var names = <String>{};
// Set<String> names = {};//This is also possible.
// var names = {}; //This creates a Map, not a Set.

Set or Map? The Map literal grammar is very similar to the Set literal grammar. Because of the prior Map alphabet grammar, {} defaults to the Map type. If you forget to comment on the {} type or assign it to a variable of undeclared type, Dart creates an object of type Map<dynamic, dynamic>

Add elements to an existing Set using add() or addAll():

var elements = <String>{};
elements.add('fluorine');
elements.addAll(halogens);

Use.length to get the number of elements in the Set:

var elements = <String>{};
elements.add('fluorine');
elements.addAll(halogens);
assert(elements.length == 5);

Add const before the Set literal to create a compile-time Set constant:

final constantSet = const {
  'fluorine',
  'chlorine',
  'bromine',
  'iodine',
  'astatine',
};
// constantSet.add('helium'); // Uncommenting this causes an error.

Map

Generally speaking, a Map is an object used to associate keys with values. Keys and values can be any type of object. A key can only appear once in a Map object. However, a value can occur multiple times. Maps in Dart are implemented using Map literals and Map types.

Here are two simple examples of using Map literals:

var gifts = {
  // Key:    Value
  'first': 'partridge',
  'second': 'turtledoves',
  'fifth': 'golden rings'
};

var nobleGases = {
  2: 'helium',
  10: 'neon',
  18: 'argon',
};

Tip: Dart infers the type of gifts to Map<String, String>, nobleGases to Map<int, String>. If you try to add an error type to the map above, the analyzer or runtime will cause an error. For more information, read Type Inference.

The above Map objects can also be created using the Map constructor:

var gifts = Map();
gifts['first'] = 'partridge';
gifts['second'] = 'turtledoves';
gifts['fifth'] = 'golden rings';

var nobleGases = Map();
nobleGases[2] = 'helium';
nobleGases[10] = 'neon';
nobleGases[18] = 'argon';

Tip: Why only Map() is used here, not new Map(). Because the new keyword is optional in Dart 2. For more information, refer to Use of constructors.

Similar to JavaScript, add key-value pairs to an existing Map:

var gifts = {'first': 'partridge'};
gifts['fourth'] = 'calling birds'; // Add a key-value pair

Like JavaScript, get a value from a Map:

var gifts = {'first': 'partridge'};
assert(gifts['first'] == 'partridge');

If the Map does not contain the key to find, the Map returns null:

var gifts = {'first': 'partridge'};
assert(gifts['fifth'] == null);

Use the.length function to get the number of key-value pairs in the current Map:

var gifts = {'first': 'partridge'};
gifts['fourth'] = 'calling birds';
assert(gifts.length == 2);

To create a Map type runtime constant, precede the Map literal with the keyword const.

final constantMap = const {
  2: 'helium',
  10: 'neon',
  18: 'argon',
};

// ConstantMap[2] ='Helium'; //Uncomment can cause errors.

Keywords: list set dart map

Added by filippe on Fri, 08 Oct 2021 21:24:46 +0300