Blog

  • 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

    String  variable_name = 'value'  
    
    OR  
    
    String  variable_name = ''value''  
    
    OR  
    
    String  variable_name = '''line1 
    line2'''  
    
    OR  
    
    String  variable_name= ''''''line1 
    line2''''''
    

    The following example illustrates the use of String data type in Dart.

    void main() { 
       String str1 = 'this is a single line string'; 
       String str2 = "this is a single line string"; 
       String str3 = '''this is a multiline line string'''; 
       String str4 = """this is a multiline line string"""; 
       
       print(str1);
       print(str2); 
       print(str3); 
       print(str4); 
    }

    It will produce the following Output −

    this is a single line string 
    this is a single line string 
    this is a multiline line string 
    this is a multiline line string 
    

    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

    void main() { 
       String str1 = "hello"; 
       String str2 = "world"; 
       String res = str1+str2; 
       
       print("The concatenated string : ${res}"); 
    }

    It will produce the following output −

    The concatenated string : Helloworld
    

    Example 2

    You can use “${}” can be used to interpolate the value of a Dart expression within strings. The following example illustrates the same.

    void main() { 
       int n=1+1; 
       
       String str1 = "The sum of 1 and 1 is ${n}"; 
       print(str1); 
       
       String str2 = "The sum of 2 and 2 is ${2+2}"; 
       print(str2); 
    }

    It will produce the following output −

    The sum of 1 and 1 is 2 
    The sum of 2 and 2 is 4
    

    String Properties

    The properties listed in the following table are all read-only.

    Sr.NoProperty & Description
    1codeUnitsReturns an unmodifiable list of the UTF-16 code units of this string.
    2isEmptyReturns true if this string is empty.
    3LengthReturns 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.NoMethods & Description
    1toLowerCase()Converts all characters in this string to lower case.
    2toUpperCase()Converts all characters in this string to upper case.
    3trim()Returns the string without any leading and trailing whitespace.
    4compareTo()Compares this object to another.
    5replaceAll()Replaces all substrings that match the specified pattern with a given value.
    6split()Splits the string at matches of the specified delimiter and returns a list of substrings.
    7substring()Returns the substring of this string that extends from startIndex, inclusive, to endIndex, exclusive.
    8toString()Returns a string representation of this object.
    9codeUnitAt()Returns the 16-bit UTF-16 code unit at the given index.
  • Numbers

    Dart numbers can be classified as −

    • int − Integer of arbitrary size. The int data type is used to represent whole numbers.
    • double − 64-bit (double-precision) floating-point numbers, as specified by the IEEE 754 standard. The double data type is used to represent fractional numbers

    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 −

    int var_name;      // declares an integer variable 
    double var_name;   // declares a double variable 
    

    Example

    void main() {
       // declare an integer
       int num1 = 10;             
    
     
    // declare a double value double num2 = 10.50; // print the values print(num1); print(num2); }

    It will produce the following output −

    10 
    10.5 
    

    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 −

    void main() { 
       print(num.parse('12')); 
       print(num.parse('10.91')); 
    }

    The above code will result in the following output −

    12 
    10.91
    

    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

    void main() { 
       print(num.parse('12A')); 
       print(num.parse('AAAA')); 
    }

    The above code will result in the following output −

    Unhandled exception: 
    FormatException: 12A 
    #0 num.parse (dart:core/num.dart:446) 
    #1 main (file:///D:/Demos/numbers.dart:4:13) 
    #2 _startIsolate.<anonymous closure> (dart:isolatepatch/isolate_patch.dart:261) 
    #3 _RawReceivePortImpl._handleMessage (dart:isolatepatch/isolate_patch.dart:148)
    

    Number Properties

    The following table lists the properties supported by Dart numbers.

    Sr.NoProperty & Description
    1hashcodeReturns a hash code for a numerical value.
    2isFiniteTrue if the number is finite; otherwise, false.
    3isInfiniteTrue if the number is positive infinity or negative infinity; otherwise, false.
    4isNanTrue if the number is the double Not-a-Number value; otherwise, false.
    5isNegativeTrue if the number is negative; otherwise, false.
    6signReturns minus one, zero or plus one depending on the sign and numerical value of the number.
    7isEvenReturns true if the number is an even number.
    8isOddReturns true if the number is an odd number.

    Number Methods

    Given below are a list of commonly used methods supported by numbers −

    Sr.NoMethod & Description
    1absReturns the absolute value of the number.
    2ceilReturns the least integer no smaller than the number.
    3compareToCompares this to other number.
    4FloorReturns the greatest integer not greater than the current number.
    5remainderReturns the truncated remainder after dividing the two numbers.
    6RoundReturns the integer closest to the current numbers.
    7toDoubleReturns the double equivalent of the number.
    8toIntReturns the integer equivalent of the number.
    9toStringReturns the string equivalent representation of the number.
    10truncateReturns an integer after discarding any fractional digits.
  • Decision Making

    Decision making structures require that the programmer specifies one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.

    Following is the general from of a typical decision making structure found in most of the programming language −

    Decision Making

    Elixir provides if/else conditional constructs like many other programming languages. It also has a cond statement which calls the first true value it finds. Case is another control flow statement which uses pattern matching to control the flow of the program. Let’s have a deep look at them.

    Elixir provides the following types of decision making statements. Click the following links to check their detail.

    Sr.No.Statement & Description
    1if statementAn if statement consists of a Boolean expression followed by do, one or more executable statements and finally an end keyword. Code in if statement executes only if Boolean condition evaluates to true.
    2if..else statementAn if statement can be followed by an optional else statement(within the do..end block), which executes when the Boolean expression is false.
    3unless statementAn unless statement has the same body as an if statement. The code within unless statement executes only when the condition specified is false.
    4unless..else statementAn unless..else statement has the same body as an if..else statement. The code within unless statement executes only when the condition specified is false.
    5condA cond statement is used where we want to execute code on basis of several conditions. It kind of works like an if…else if….else construct in several other programming languages.
    6caseCase statement can be considered as a replacement for switch statement in imperative languages. Case takes a variable/literal and applies pattern matching to it with different cases. If any case matches, Elixir executes code associated with that case and exits case statement.
  • Pattern Matching

    Pattern matching is a technique which Elixir inherits form Erlang. It is a very powerful technique that allows us to extract simpler substructures from complicated data structures like lists, tuples, maps, etc.

    A match has 2 main parts, a left and a right side. The right side is a data structure of any kind. The left side attempts to match the data structure on the right side and bind any variables on the left to the respective substructure on the right. If a match is not found, the operator raises an error.

    The simplest match is a lone variable on the left and any data structure on the right. This variable will match anything. For example,

    x = 12
    x = "Hello"
    IO.puts(x)

    You can place variables inside a structure so that you can capture a substructure. For example,

    [var_1, _unused_var, var_2] = [{"First variable"}, 25, "Second variable" ]
    IO.puts(var_1)
    IO.puts(var_2)

    This will store the values, {“First variable”} in var_1 and “Second variable” in var_2. There is also a special _ variable(or variables prefixed with ‘_’) that works exactly like other variables but tells elixir, “Make sure something is here, but I don’t care exactly what it is.”. In the previous example, _unused_var was one such variable.

    We can match more complicated patterns using this technique. For example if you want to unwrap and get a number in a tuple which is inside a list which itself is in a list, you can use the following command −

    [_, [_, {a}]] = ["Random string", [:an_atom, {24}]]
    IO.puts(a)

    The above program generates the following result −

    24
    

    This will bind a to 24. Other values are ignored as we are using ‘_’.

    In pattern matching, if we use a variable on the right, its value is used. If you want to use the value of a variable on the left, you’ll need to use the pin operator.

    For example, if you have a variable “a” having value 25 and you want to match it with another variable “b” having value 25, then you need to enter −

    a = 25
    b = 25
    ^a = b

    The last line matches the current value of a, instead of assigning it, to the value of b. If we have a non-matching set of left and right hand side, the match operator raises an error. For example, if we try to match a tuple with a list or a list of size 2 with a list of size 3, an error will be displayed.

  • Decision Making

    A conditional/decision-making construct evaluates a condition before the instructions are executed.

    Decision Making

    Conditional constructs in Dart are classified in the following table.

    Sr.NoStatement & Description
    1if statementAn if statement consists of a Boolean expression followed by one or more statements.
    2If…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.
    3else…if LadderThe else…if ladder is useful to test multiple conditions. Following is the syntax of the same.
    4switch…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 −

    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.NoLoop & Description
    1for 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
    2for…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.NoLoop & Description
    1while 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.
    2do…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.NoControl Statement & Description
    1break 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.
    2continue 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

    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

    void main() { 
       outerloop: // This is the label name 
       
       for (var i = 0; i < 5; i++) { 
    
      print("Innerloop: ${i}"); 
      innerloop: 
      
      for (var j = 0; j &lt; 5; j++) { 
         if (j &gt; 3 ) break ; 
         
         // Quit the innermost loop 
         if (i == 2) break innerloop; 
         
         // Do the same thing 
         if (i == 4) break outerloop; 
         
         // Quit the outer loop 
         print("Innerloop: ${j}"); 
      } 
    } }

    The following output is displayed on successful execution of the above code.

    Innerloop: 0
    Innerloop: 0
    Innerloop: 1
    Innerloop: 2
    Innerloop: 3
    Innerloop: 1
    Innerloop: 0
    Innerloop: 1
    Innerloop: 2
    Innerloop: 3
    Innerloop: 2
    Innerloop: 3
    Innerloop: 0
    Innerloop: 1
    Innerloop: 2
    Innerloop: 3
    Innerloop: 4
    

    Example: Label with continue

    void main() { 
       outerloop: // This is the label name 
       
       for (var i = 0; i < 3; i++) { 
    
      print("Outerloop:${i}"); 
      
      for (var j = 0; j &lt; 5; j++) { 
         if (j == 3){ 
            continue outerloop; 
         } 
         print("Innerloop:${j}"); 
      } 
    } }

    The following output is displayed on successful execution of the above code.

    Outerloop: 0 
    Innerloop: 0 
    Innerloop: 1 
    Innerloop: 2 
    
    Outerloop: 1 
    Innerloop: 0 
    Innerloop: 1 
    Innerloop: 2 
    
    Outerloop: 2 
    Innerloop: 0 
    Innerloop: 1 
    Innerloop: 2 
    
  • Operators

    An expression is a special kind of statement that evaluates to a value. Every expression is composed of −

    • Operands − Represents the data
    • Operator − Defines how the operands will be processed to produce a value.

    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
    • Equality and Relational Operators
    • Type test Operators
    • Bitwise Operators
    • Assignment Operators
    • Logical Operators

    Arithmetic Operators

    The following table shows the arithmetic operators supported by Dart.

    Sr.NoOperators & Meaning
    1+Add
    2Subtract
    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
    9Decrement

    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.

    OperatorDescriptionExample
    >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

    Type test Operators

    These operators are handy for checking types at runtime.

    OperatorMeaning
    isTrue 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 −

    OperatorDescriptionExample
    Bitwise ANDa & bReturns a one in each bit position for which the corresponding bits of both operands are ones.
    Bitwise ORa | bReturns a one in each bit position for which the corresponding bits of either or both operands are ones.
    Bitwise XORa ^ bReturns a one in each bit position for which the corresponding bits of either but not both operands are ones.
    Bitwise NOT~ aInverts the bits of its operand.
    Left shifta ≪ bShifts a in binary representation b (< 32) bits to the left, shifting in zeroes from the right.
    Signpropagating right shifta ≫ bShifts 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.NoOperator & 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.

    OperatorDescriptionExample
    &&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 −

    void main() { 
       var a = 10; 
       var res = a > 12 ? "value greater than 10":"value lesser than or equal to 10"; 
       print(res); 
    } 

    It will produce the following output −

    value lesser than or equal to 10
    

    Example

    Let’s take another example −

    void main() { 
       var a = null; 
       var b = 12; 
       var res = a ?? b; 
       print(res); 
    }

    It will produce the following output −

    12
    
  • Operators

    An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. There are a LOT of operators provided by elixir. They are divided in the following categories −

    • Arithmetic operators
    • Comparison operators
    • Boolean operators
    • Misc operators

    Arithmetic Operators

    The following table shows all the arithmetic operators supported by Elixir language. Assume variable A holds 10 and variable B holds 20, then −

    Show Examples

    OperatorDescriptionExample
    +Adds 2 numbers.A + B will give 30
    Subtracts second number from first.A-B will give -10
    *Multiplies two numbers.A*B will give 200
    /Divides first number from second. This casts the numbers in floats and gives a float resultA/B will give 0.5.
    divThis function is used to get the quotient on division.div(10,20) will give 0
    remThis function is used to get the remainder on division.rem(A, B) will give 10

    AD

    https://delivery.adrecover.com/recover.html?siteId=18107&dataDogLoggingEnabled=false&dataDogLoggingVersion=1

    Comparison Operators

    The comparison operators in Elixir are mostly common to those provided in most other languages. The following table sums up comparison operators in Elixir. Assume variable A holds 10 and variable B holds 20, then −

    Show Examples

    OperatorDescriptionExample
    ==Checks if value on left is equal to value on right(Type casts values if they are not the same type).A == B will give false
    !=Checks if value on left is not equal to value on right.A != B will give true
    ===Checks if type of value on left equals type of value on right, if yes then check the same for value.A === B will give false
    !==Same as above but checks for inequality instead of equality.A !== B will give true
    >Checks if the value of left operand is greater than the value of right operand; if yes, then the condition becomes true.A > B will give false
    <Checks if the value of left operand is less than the value of right operand; if yes, then the condition becomes true.A < B will give true
    >=Checks if the value of left operand is greater than or equal to the value of right operand; if yes, then the condition becomes true.A >= B will give false
    <=Checks if the value of left operand is less than or equal to the value of right operand; if yes, then the condition becomes true.A <= B will give true

    Logical operators

    Elixir provides 6 logical operators: and, or, not, &&, || and !. The first three, and or not are strict Boolean operators, meaning that they expect their first argument to be a Boolean. Non Boolean argument will raise an error. While the next three, &&, || and ! are non strict, do not require us to have the first value strictly as a boolean. They work in the same way as their strict counterparts. Assume variable A holds true and variable B holds 20, then −

    Show Examples

    OperatorDescriptionExample
    andChecks if both values provided are truthy, if yes then returns the value of second variable. (Logical and).A and B will give 20
    orChecks if either value provided is truthy. Returns whichever value is truthy. Else returns false. (Logical or).A or B will give true
    notUnary operator which inverts the value of given input.not A will give false
    &&Non-strict and. Works same as and but does not expect first argument to be a Boolean.B && A will give 20
    ||Non-strict or. Works same as or but does not expect first argument to be a Boolean.B || A will give true
    !Non-strict not. Works same as not but does not expect the argument to be a Boolean.!A will give false

    NOTE −andor&& and || || are short circuit operators. This means that if the first argument of and is false, then it will not further check for the second one. And if the first argument of or is true, then it will not check for the second one. For example,

    false and raise("An error")  
    #This won't raise an error as raise function wont get executed because of short
    #circuiting nature of and operator

    Bitwise Operators

    Bitwise operators work on bits and perform bit by bit operation. Elixir provides bitwise modules as part of the package Bitwise, so in order to use these, you need to use the bitwise module. To use it, enter the following command in your shell −

    use Bitwise
    

    Assume A to be 5 and B to be 6 for the following examples −

    Show Examples

    OperatorDescriptionExample
    &&&Bitwise and operator copies a bit to result if it exists in both operands.A &&& B will give 4
    |||Bitwise or operator copies a bit to result if it exists in either operand.A ||| B will give 7
    >>>Bitwise right shift operator shifts first operand bits to the right by the number specified in second operand.A >>> B will give 0
    <<<Bitwise left shift operator shifts first operand bits to the left by the number specified in second operand.A <<< B will give 320
    ^^^Bitwise XOR operator copies a bit to result only if it is different on both operands.A ^^^ B will give 3
    ~~~Unary bitwise not inverts the bits on the given number.~~~A will give -6

    Misc Operators

    Other than the above operators, Elixir also provides a range of other operators like Concatenation Operator, Match Operator, Pin Operator, Pipe Operator, String Match Operator, Code Point Operator, Capture Operator, Ternary Operator that make it quite a powerful language.

  • Variables

    A variable provides us with named storage that our programs can manipulate. Each variable in Elixir has a specific type, which determines the size and layout of the variable’s memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.

    Types of Variables

    Elixir supports the following basic types of variables.

    Integer

    These are used for Integers. They are of size 32bit on a 32bit architecture and 64 bits on a 64-bit architecture. Integers are always signed in elixir. If an integer starts to expand in size above its limit, elixir convers it in a Big Integer which takes up memory in range 3 to n words whichever can fit it in memory.

    Floats

    Floats have a 64-bit precision in elixir. They are also like integers in terms of memory. When defining a float, exponential notation can be used.

    Boolean

    They can take up 2 values which is either true or false.

    Strings

    Strings are utf-8 encoded in elixir. They have a strings module which provides a lot of functionality to the programmer to manipulate strings.

    Anonymous Functions/Lambdas

    These are functions that can be defined and assigned to a variable, which can then be used to call this function.

    Collections

    There are a lot of collection types available in Elixir. Some of them are Lists, Tuples, Maps, Binaries, etc. These will be discussed in subsequent chapters.

    Variable Declaration

    A variable declaration tells the interpreter where and how much to create the storage for the variable. Elixir does not allow us to just declare a variable. A variable must be declared and assigned a value at the same time. For example, to create a variable named life and assign it a value 42, we do the following −

    life = 42
    

    This will bind the variable life to value 42. If we want to reassign this variable a new value, we can do this by using the same syntax as above, i.e.,

    life = "Hello world"
    

    Variable Naming

    Naming variables follow a snake_case convention in Elixir, i.e., all variables must start with a lowercase letter, followed by 0 or more letters(both upper and lower case), followed at the end by an optional ‘?’ OR ‘!’.

    Variable names can also be started with a leading underscore but that must be used only when ignoring the variable, i.e., that variable will not be used again but is needed to be assigned to something.

    Printing Variables

    In the interactive shell, variables will print if you just enter the variable name. For example, if you create a variable −

    life = 42 
    

    And enter ‘life’ in your shell, you’ll get the output as −

    42
    

    But if you want to output a variable to the console (When running an external script from a file), you need to provide the variable as input to IO.puts function −

    life = 42  
    IO.puts life 

    or

    life = 42 
    IO.puts(life) 

    This will give you the following output −

    42
    
  • 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 −

    • Identifiers cannot be keywords.
    • Identifiers can contain alphabets and numbers.
    • Identifiers cannot contain spaces and special characters, except the underscore (_) and the dollar ($) sign.
    • Variable names cannot begin with a number.

    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 −

    var name = 'Smith';
    

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

    Type Syntax

    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 −

    String name = 'Smith'; 
    int num = 10;
    

    Consider the following example −

    void main() { 
       String name = 1; 
    }

    The above snippet will result in a warning since the value assigned to the variable doesn’t match the variable’s data type.

    Output

    Warning: A value of type 'String' cannot be assigned to a variable of type 'int' 
    

    All uninitialized variables have an initial value of null. This is because Dart considers all values as objects. The following example illustrates the same −

    void main() { 
       int num; 
       print(num); 
    }

    Output

    Null 
    

    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.

    void main() { 
       dynamic x = "tom"; 
       print(x);  
    }

    Output

    tom
    

    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

    final variable_name
    

    OR

    final data_type  variable_name
    

    Syntax: const Keyword

    const variable_name
    

    OR

    const data_type variable_name
    

    Example – final Keyword

    void main() { 
       final val1 = 12; 
       print(val1); 
    }

    Output

    12
    

    Example – const Keyword

    void main() { 
       const pi = 3.14; 
       const area = pi*12*12; 
       print("The output is ${area}"); 
    }

    The above example declares two constants, pi and area, using the const keyword. The area variable’s value is a compile-time constant.

    Output

    The output is 452.15999999999997
    

    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 −

    void main() { 
       final v1 = 12; 
       const v2 = 13; 
       v2 = 12; 
    }

    The code given above will throw the following error as output −

    Unhandled exception: 
    cannot assign to final variable 'v2='.  
    NoSuchMethodError: cannot assign to final variable 'v2=' 
    #0  NoSuchMethodError._throwNew (dart:core-patch/errors_patch.dart:178) 
    #1      main (file: Test.dart:5:3) 
    #2    _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:261) 
    #3    _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:148)