Symbols in Dart are opaque, dynamic string name used in reflecting out metadata from a library. Simply put, symbols are a way to store the relationship between a human readable string and a string that is optimized to be used by computers. Reflection is a mechanism to get metadata of a type at runtime like the number of methods in a class, the number of constructors it has or the number of parameters in a function. You can even invoke a method of the type which is loaded at runtime. In Dart reflection specific classes are available in the dart:mirrors package. This library works in both web applications and command line applications. Syntax The name must be a valid public Dart member name, public constructor name, or library name. Example Consider the following example. The code declares a class Foo in a library foo_lib. The class defines the methods m1, m2, and m3. Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career. Foo.dart The following code loads Foo.dart library and searches for Foo class, with help of Symbol type. Since we are reflecting the metadata from the above library the code imports dart:mirrors library. FooSymbol.dart Note that the line libMirror.declarations.forEach((s, d) => print(s)); will iterate across every declaration in the library at runtime and prints the declarations as type of Symbol. This code should produce the following output − Example: Display the number of instance methods of a class Let us now consider displaying the number of instance methods in a class. The predefined class ClassMirror helps us to achieve the same. This code should produce the following output − Convert Symbol to String You can convert the name of a type like class or library stored in a symbol back to string using MirrorSystem class. The following code shows how you can convert a symbol to a string. It should produce the following output −
Map
The Map object is a simple key/value pair. Keys and values in a map may be of any type. A Map is a dynamic collection. In other words, Maps can grow and shrink at runtime. Maps can be declared in two ways − Declaring a Map using Map Literals To declare a map using map literals, you need to enclose the key-value pairs within a pair of curly brackets “{ }”. Here is its syntax − Declaring a Map using a Map Constructor To declare a Map using a Map constructor, we have two steps. First, declare the map and second, initialize the map. The syntax to declare a map is as follows − Now, use the following syntax to initialize the map − Example: Map Literal It will produce the following output − Example: Adding Values to Map Literals at Runtime It will produce the following output − Example: Map Constructor It will produce the following output − Note − A map value can be any object including NULL. Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career. Map – Properties The Map class in the dart:core package defines the following properties − Sr.No Property & Description 1 KeysReturns an iterable object representing keys 2 ValuesReturns an iterable object representing values 3 LengthReturns the size of the Map 4 isEmptyReturns true if the Map is an empty Map 5 isNotEmptyReturns true if the Map is an empty Map Map – Functions Following are the commonly used functions for manipulating Maps in Dart. Sr.No Function Name & Description 1 addAll()Adds all key-value pairs of other to this map. 2 clear()Removes all pairs from the map. 3 remove()Removes key and its associated value, if present, from the map. 4 forEach()Applies f to each key-value pair of the map.
Lists
A very commonly used collection in programming is an array. Dart represents arrays in the form of List objects. A List is simply an ordered group of objects. The dart:core library provides the List class that enables creation and manipulation of lists. The logical representation of a list in Dart is given below − Lists can be classified as − Let us now discuss these two types of lists in detail. Fixed Length List A fixed length list’s length cannot change at runtime. The syntax for creating a fixed length list is as given below − Step 1 − Declaring a list The syntax for declaring a fixed length list is given below − The above syntax creates a list of the specified size. The list cannot grow or shrink at runtime. Any attempt to resize the list will result in an exception. Step 2 − Initializing a list The syntax for initializing a list is as given below − Example It will produce the following output − Growable List A growable list’s length can change at run-time. The syntax for declaring and initializing a growable list is as given below − Step 1 − Declaring a List Step 2 − Initializing a List The index / subscript is used to reference the element that should be populated with a value. The syntax for initializing a list is as given below − Example The following example shows how to create a list of 3 elements.Live Demo It will produce the following output − Example The following example creates a zero-length list using the empty List() constructor. The add() function in the List class is used to dynamically add elements to the list. It will produce the following output − Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career. List Properties The following table lists some commonly used properties of the List class in the dart:core library. Sr.No Methods & Description 1 firstReturns the first element in the list. 2 isEmptyReturns true if the collection has no elements. 3 isNotEmptyReturns true if the collection has at least one element. 4 lengthReturns the size of the list. 5 lastReturns the last element in the list. 6 reversedReturns an iterable object containing the lists values in the reverse order. 7 SingleChecks if the list has only one element and returns it.
Boolean
Dart provides an inbuilt support for the Boolean data type. The Boolean data type in DART supports only two values – true and false. The keyword bool is used to represent a Boolean literal in DART. The syntax for declaring a Boolean variable in DART is as given below − Example It will produce the following output − Example Unlike JavaScript, the Boolean data type recognizes only the literal true as true. Any other value is considered as false. Consider the following example − The above snippet, if run in JavaScript, will print the message ‘String is not empty’ as the if construct will return true if the string is not empty. However, in Dart, str is converted to false as str != true. Hence the snippet will print the message ‘Empty String’ (when run in unchecked mode). Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career. Example The above snippet if run in checked mode will throw an exception. The same is illustrated below − It will produce the following output, in Checked Mode − It will produce the following output, in Unchecked Mode − Note − The WebStorm IDE runs in checked mode, by default.
String
The String data type represents a sequence of characters. A Dart string is a sequence of UTF 16 code units. String values in Dart can be represented using either single or double or triple quotes. Single line strings are represented using single or double quotes. Triple quotes are used to represent multi-line strings. The syntax of representing string values in Dart is as given below − Syntax The following example illustrates the use of String data type in Dart. It will produce the following Output − Strings are immutable. However, strings can be subjected to various operations and the resultant string can be a stored as a new value. String Interpolation The process of creating a new string by appending a value to a static string is termed as concatenation or interpolation. In other words, it is the process of adding a string to another string. The operator plus (+) is a commonly used mechanism to concatenate / interpolate strings. Example 1 It will produce the following output − Example 2 You can use “${}” can be used to interpolate the value of a Dart expression within strings. The following example illustrates the same. It will produce the following output − Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career. String Properties The properties listed in the following table are all read-only. Sr.No Property & Description 1 codeUnitsReturns an unmodifiable list of the UTF-16 code units of this string. 2 isEmptyReturns true if this string is empty. 3 LengthReturns the length of the string including space, tab and newline characters. Methods to Manipulate Strings The String class in the dart: core library also provides methods to manipulate strings. Some of these methods are given below − Sr.No Methods & Description 1 toLowerCase()Converts all characters in this string to lower case. 2 toUpperCase()Converts all characters in this string to upper case. 3 trim()Returns the string without any leading and trailing whitespace. 4 compareTo()Compares this object to another. 5 replaceAll()Replaces all substrings that match the specified pattern with a given value. 6 split()Splits the string at matches of the specified delimiter and returns a list of substrings. 7 substring()Returns the substring of this string that extends from startIndex, inclusive, to endIndex, exclusive. 8 toString()Returns a string representation of this object. 9 codeUnitAt()Returns the 16-bit UTF-16 code unit at the given index.
Numbers
Dart numbers can be classified as − The num type is inherited by the int and double types. The dart core library allows numerous operations on numeric values. The syntax for declaring a number is as given below − Example It will produce the following output − Note − The Dart VM will throw an exception if fractional values are assigned to integer variables. Parsing The parse() static function allows parsing a string containing numeric literal into a number. The following illustration demonstrates the same − The above code will result in the following output − The parse function throws a FormatException if it is passed any value other than numerals. The following code shows how to pass an alpha-numeric value to the parse() function. Example The above code will result in the following output − Number Properties The following table lists the properties supported by Dart numbers. Sr.No Property & Description 1 hashcodeReturns a hash code for a numerical value. 2 isFiniteTrue if the number is finite; otherwise, false. 3 isInfiniteTrue if the number is positive infinity or negative infinity; otherwise, false. 4 isNanTrue if the number is the double Not-a-Number value; otherwise, false. 5 isNegativeTrue if the number is negative; otherwise, false. 6 signReturns minus one, zero or plus one depending on the sign and numerical value of the number. 7 isEvenReturns true if the number is an even number. 8 isOddReturns true if the number is an odd number. Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career. Number Methods Given below are a list of commonly used methods supported by numbers − Sr.No Method & Description 1 absReturns the absolute value of the number. 2 ceilReturns the least integer no smaller than the number. 3 compareToCompares this to other number. 4 FloorReturns the greatest integer not greater than the current number. 5 remainderReturns the truncated remainder after dividing the two numbers. 6 RoundReturns the integer closest to the current numbers. 7 toDoubleReturns the double equivalent of the number. 8 toIntReturns the integer equivalent of the number. 9 toStringReturns the string equivalent representation of the number. 10 truncateReturns an integer after discarding any fractional digits.
Decision Making
A conditional/decision-making construct evaluates a condition before the instructions are executed. Conditional constructs in Dart are classified in the following table. Sr.No Statement & Description 1 if statementAn if statement consists of a Boolean expression followed by one or more statements. 2 If…Else StatementAn if can be followed by an optional else block. The else block will execute if the Boolean expression tested by the if block evaluates to false. 3 else…if LadderThe else…if ladder is useful to test multiple conditions. Following is the syntax of the same. 4 switch…case StatementThe switch statement evaluates an expression, matches the expression’s value to a case clause and executes the statements associated with that case.
Loops
At times, certain instructions require repeated execution. Loops are an ideal way to do the same. A loop represents a set of instructions that must be repeated. In a loop’s context, a repetition is termed as an iteration. The following figure illustrates the classification of loops − Let’s start the discussion with Definite Loops. A loop whose number of iterations are definite/fixed is termed as a definite loop. Sr.No Loop & Description 1 for loopThe for loop is an implementation of a definite loop. The for loop executes the code block for a specified number of times. It can be used to iterate over a fixed set of values, such as an array 2 for…in LoopThe for…in loop is used to loop through an object’s properties. Moving on, let’s now discuss the indefinite loops. An indefinite loop is used when the number of iterations in a loop is indeterminate or unknown. Indefinite loops can be implemented using − Sr.No Loop & Description 1 while LoopThe while loop executes the instructions each time the condition specified evaluates to true. In other words, the loop evaluates the condition before the block of code is executed. 2 do…while LoopThe do…while loop is similar to the while loop except that the do…while loop doesn’t evaluate the condition for the first time the loop executes. Let us now move on and discuss the Loop Control Statements of Dart. Sr.No Control Statement & Description 1 break StatementThe break statement is used to take the control out of a construct. Using break in a loop causes the program to exit the loop. Following is an example of the break statement. 2 continue StatementThe continue statement skips the subsequent statements in the current iteration and takes the control back to the beginning of the loop. Using Labels to Control the Flow A label is simply an identifier followed by a colon (:) that is applied to a statement or a block of code. A label can be used with break and continue to control the flow more precisely. Line breaks are not allowed between the ‘continue’ or ‘break’ statement and its label name. Also, there should not be any other statement in between a label name and an associated loop. Example: Label with Break The following output is displayed on successful execution of the above code. Example: Label with continue The following output is displayed on successful execution of the above code.
Operators
An expression is a special kind of statement that evaluates to a value. Every expression is composed of − Consider the following expression – “2 + 3”. In this expression, 2 and 3 are operands and the symbol “+” (plus) is the operator. In this chapter, we will discuss the operators that are available in Dart. Arithmetic Operators The following table shows the arithmetic operators supported by Dart. Sr.No Operators & Meaning 1 +Add 2 −Subtract 3 -exprUnary minus, also known as negation (reverse the sign of the expression) 4 *Multiply 5 /Divide 6 ~/Divide, returning an integer result 7 %Get the remainder of an integer division (modulo) 8 ++Increment 9 —Decrement Equality and Relational Operators Relational Operators tests or defines the kind of relationship between two entities. Relational operators return a Boolean value i.e. true/ false. Assume the value of A is 10 and B is 20. Operator Description Example > Greater than (A > B) is False < Lesser than (A < B) is True >= Greater than or equal to (A >= B) is False <= Lesser than or equal to (A <= B) is True == Equality (A==B) is False != Not equal (A!=B) is True Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career. Type test Operators These operators are handy for checking types at runtime. Operator Meaning is True if the object has the specified type is! False if the object has the specified type Bitwise Operators The following table lists the bitwise operators available in Dart and their role − Operator Description Example Bitwise AND a & b Returns a one in each bit position for which the corresponding bits of both operands are ones. Bitwise OR a | b Returns a one in each bit position for which the corresponding bits of either or both operands are ones. Bitwise XOR a ^ b Returns a one in each bit position for which the corresponding bits of either but not both operands are ones. Bitwise NOT ~ a Inverts the bits of its operand. Left shift a ≪ b Shifts a in binary representation b (< 32) bits to the left, shifting in zeroes from the right. Signpropagating right shift a ≫ b Shifts a in binary representation b (< 32) bits to the right, discarding bits shifted off. Assignment Operators The following table lists the assignment operators available in Dart. Sr.No Operator & Description 1 =(Simple Assignment )Assigns values from the right side operand to the left side operandEx:C = A + B will assign the value of A + B into C 2 ??=Assign the value only if the variable is null 3 +=(Add and Assignment)It adds the right operand to the left operand and assigns the result to the left operand.Ex: C += A is equivalent to C = C + A 4 ─=(Subtract and Assignment)It subtracts the right operand from the left operand and assigns the result to the left operand.Ex: C -= A is equivalent to C = C – A 5 *=(Multiply and Assignment)It multiplies the right operand with the left operand and assigns the result to the left operand.Ex: C *= A is equivalent to C = C * A 6 /=(Divide and Assignment)It divides the left operand with the right operand and assigns the result to the left operand. Note − Same logic applies to Bitwise operators, so they will become ≪=, ≫=, ≫=, ≫=, |= and ^=. Logical Operators Logical operators are used to combine two or more conditions. Logical operators return a Boolean value. Assume the value of variable A is 10 and B is 20. Operator Description Example && And − The operator returns true only if all the expressions specified return true (A > 10 && B > 10) is False. || OR − The operator returns true if at least one of the expressions specified return true (A > 10 || B > 10) is True. ! NOT − The operator returns the inverse of the expression’s result. For E.g.: !(7>5) returns false !(A > 10) is True. Conditional Expressions Dart has two operators that let you evaluate expressions that might otherwise require ifelse statements − condition ? expr1 : expr2 If condition is true, then the expression evaluates expr1 (and returns its value); otherwise, it evaluates and returns the value of expr2. expr1 ?? expr2 If expr1 is non-null, returns its value; otherwise, evaluates and returns the value of expr2 Example The following example shows how you can use conditional expression in Dart − It will produce the following output − Example Let’s take another example − It will produce the following output −
Variables
A variable is “a named space in the memory” that stores values. In other words, it acts a container for values in a program. Variable names are called identifiers. Following are the naming rules for an identifier − Type Syntax A variable must be declared before it is used. Dart uses the var keyword to achieve the same. The syntax for declaring a variable is as given below − All variables in dart store a reference to the value rather than containing the value. The variable called name contains a reference to a String object with a value of “Smith”. Dart supports type-checking by prefixing the variable name with the data type. Type-checking ensures that a variable holds only data specific to a data type. The syntax for the same is given below − Consider the following example − The above snippet will result in a warning since the value assigned to the variable doesn’t match the variable’s data type. Output All uninitialized variables have an initial value of null. This is because Dart considers all values as objects. The following example illustrates the same − Output The dynamic keyword Variables declared without a static type are implicitly declared as dynamic. Variables can be also declared using the dynamic keyword in place of the var keyword. The following example illustrates the same. Output Final and Const The final and const keyword are used to declare constants. Dart prevents modifying the values of a variable declared using the final or const keyword. These keywords can be used in conjunction with the variable’s data type or instead of the var keyword. The const keyword is used to represent a compile-time constant. Variables declared using the const keyword are implicitly final. Syntax: final Keyword OR Syntax: const Keyword OR Example – final Keyword Output Example – const Keyword The above example declares two constants, pi and area, using the const keyword. The area variable’s value is a compile-time constant. Output Note − Only const variables can be used to compute a compile time constant. Compile-time constants are constants whose values will be determined at compile time Example Dart throws an exception if an attempt is made to modify variables declared with the final or const keyword. The example given below illustrates the same − The code given above will throw the following error as output −