Starting with Dart

1 Dart Basics

1.1 Comments

Types of Dart Comments:

  • Dart Single line Comment.

  • Dart Multiline Comment.

  • Dart Documentation Comment.

    void main()
    {
        // This is a single comment
        /*
        This is a multiline comment
        */
        /// This is a documentation comment.
    }

1.2 Variables

To declare a variable: type variable_name;

To declare multiple variables of the same type: type variable1_name, variable2_name, variable3_name, ....variableN_name;

Type of the variable can be among:

  • Static Variable

  • Dynamic Variable

  • Final Variables and Constants.

1.2.1 Example of Dart Variable

    void main()
    {
        
        int variable1 = 10;
        
        
        double variable2 = 0.2; 
    
        bool variable3 = false; 
        String variable4 = "0", variable5 = "Geeks for Geeks";
        
        print(variable1);
        print(variable2);
        print(variable3);
        print(variable4);
        print(variable5);
    }   
    void main()
    {
        // Declaring and initialising a variable
        int variable1 = 10;
        
        // Declaring another variable
        double variable2 = 0.2; // must declare double a value or it
        // will throw error
        bool variable3 = false; // must declare boolean a value or it
        // will throw error
        
        // Declaring multiple variable
        String variable4 = "0", variable5 = "Some text";
        
        // Printing values of all the variables
        print(variable1); // Print 10
        print(variable2); // Print 0.2
        print(variable3); // Print default string value
        print(variable4); // Print default bool value
        print(variable5); // Print Geeks for Geeks
    }   

1.2.2 Dynamic Type Variable in Dart

This is a special variable initialised with keyword dynamic. The variable declared with this data type can store implicitly any value during running the program. Syntax: dynamic variable_name;

    void main()
    {
        // Assigning value to variable
        dynamic variable = "Some text";
        
        // Printing variable 
        print(variable);
        
        // Reassigning the data to variable and printing it
        variable = 3.14157;
        print(variable);
    }       

If we use var instead of dynamic in the above code, it will show an error because var gets the type of the first initialized value.

1.2.3 Final and Const

These keywords are used to define constant variable in Dart i.e. once a variable is defined using these keyword then its value can’t be changed in the entire code. These keyword can be used with or without data type name. A final variable can only be set once and it is initialized when accessed. Syntax for Final: final variable_name (without datatype) or final data_type variable_name (with datatype).

    void main() 
    {
        // Assigning value to variable without datatype
        final variable1 = "Some text";
        // Printing variable1
        print(variable1);
        
        // Assigning value to variable2 with datatype
        final String variable2 = "Some other text";
        // Printing variable2
        print(variable2);
        
        // Now, if we try to reassign the variable1 we get an error
    }       

A constant variable is a compile-time constant and its value must be known before the program runs. Syntax for Const: const variable_name; (without datatype) or const data_type variable_name; (with datatype).

    void main() 
    {
        // Assigning value to variable1 without datatype
        const variable1 = "Some text";
        // Printing variable1
        print(variable1);
        
        // Assigning value to variable2 with datatype
        const variable2 = "Some text again!!";
        // Printing variable variable2
        print(variable2);
    }   

1.2.4 Null Safety in Dart

In Dart, by default a variable can’t be assigned Null value till it is defined that the variable can store Null value in it. This to avoid cases where user assign null value in Dart. To declare a variable as nullable, you append a ‘?’ to the type of the variable. The declared variable will by default store null as value.

1.3 Operators in Dart

The following are the most useful types of operators in Dart.

  • Arithmetic Operators.

  • Relational Operators.

  • Assignment Operators.

  • Logical Operators.

1.3.1 Arithmetic Operators

Symbol Name Description
+ Addition Use to add two operands
- Subtraction Use to subtract two operands
-expr Unary Minus It is Used to reverse the sign of the expression
* Multiply Use to multiply two operands
/ Division Use to divide two operands
 ~/ Division Use to divide two operands but give the result in integer
% Modulus Use to give remainder of two operands
    void main()
    {
        int a = 2;
        int b = 3;
        
        // Adding a and b
        var c = a + b;
        print("Sum  ($a + $b) = $c");
        
        // Subtracting a and b
        var d = a - b;
        print("Difference ($a - $b) = $d");
        
        // Using unary minus
        var e = -d;
        print("Negation -($a - $b) = $e");
        
        // Multiplication of a and b
        var f = a * b;
        print("Product ($a * $b) = $f");
        
        // Division of a and b
        var g = b / a;
        print("Division ($b / $a) = $g");
        
        // Using ~/ to divide a and b
        var h = b ~/ a;
        print("Quotient ($b ~/ $a) = $h");
        
        // Remainder of a and b
        var i = b % a;
        print("Remainder ($b % $a) = $i");
    }   

1.3.2 Relational Operators

Symbol Name Description
> Greater than Check which operand is bigger and give result as boolean expression.
< Less than Check which operand is smaller and give result as boolean expression.
>= Greater than or equal to Check which operand is greater or equal to each other and give result as boolean expression.
<= less than equal to Check which operand is less than or equal to each other and give result as boolean expression.
== Equal to Check whether the operand are equal to each other or not and give result as boolean expression.
!= Not Equal to Check whether the operand are not equal to each other or not and give result as boolean expression.
    void main()
    {
        int a = 2;
        int b = 3;
        
        // Greater between a and b
        var c = a > b;
        print("a is greater than b ($a > $b) : $c");
        
        // Smaller between a and b
        var d = a < b;
        print("a is smaller than b ($a < $b) : $d");
        
        // Greater than or equal to between a and b
        var e = a >= b;
        print("a is greater than b ($a >= $b) : $e");
        
        // Less than or equal to between a and b
        var f = a <= b;
        print("a is smaller than b ($a <= $b) : $f");
        
        // Equality between a and b
        var g = b == a;
        print("a and b are equal ($b == $a) : $g");
        
        // Unequality between a and b
        var h = b != a;
        print("a and b are not equal ($b != $a) : $h");
    }

Note that the == operator can’t be used to check if the object is same. So, to check if the object are same we use identical() function.

1.3.3 Assignment Operators

Symbol Name Description
= Assignment operator Use to assign values to the expression or variable
??= Assignment operator for null Assign the value only if it is null.
    void main()
    {
        int a = 5;
        int b = 7;
        
        // Assigning value to variable c
        var c = a * b;
        
        print("assignment operator used c = $a*$b so now c = $c\n");
        
        // Assigning value to variable d
        var d;
        
        // Value is assign as it is null
        d ??= a + b;
        
        print("Assigning value only if d is null");
        print("d ??= $a+$b so d = $d \n");
        
        // Again trying to assign value to d
        d ??= a - b;
        // Value is not assign as it is not null
        
        print("Assigning value only if d is null");
        print("d ??= a-b so d = $d");
        print("As d was not null value was not updated");
    }

There also compound assignment operators such as +=, -=, *=, /=,  /=, %=, =̂, &=, and |=.

1.3.4 Logical Operators

Symbol Name Description
&& And Operator Use to add two conditions and if both are true than it will return true.
|| Or Operator Use to add two conditions and if even one of them is true than it will return true.
! Not Operator It is use to reverse the result.
    void main()
    {
        int a = 5;
        int b = 7;
        
        // Using And Operator
        bool c = a > 10 && b < 10;
        print(c);
        
        // Using Or Operator
        bool d = a > 10 || b < 10;
        print(d);
        
        // Using Not Operator
        bool e = !(a > 10);
        print(e);
    }

Logical operator can only be application to boolean expression and in dart.

1.4 Standard Input/Output

1.4.1 Standard Input in Dart

In Dart programming language, you can take standard input from the user through the console via the use of .readLineSync() function. To take input from the console you need to import a library, named dart:io from libraries of Dart.

    void main()
    {
        print("Enter your name?");
        // Reading name 
        String? name = stdin.readLineSync(); // null safety in name string
        
        // Printing the name
        print("Hello, $name! \nWelcome!!");
    }

Taking integer value as input:

    // Importing dart:io file
    import 'dart:io';
    void main()
    {
        print("Enter your name?");
        // Reading name 
        String? name = stdin.readLineSync(); // null safety in name string
        
        // Printing the name
        print("Hello, $name! \nWelcome!!");
    }
    // Importing dart:io file
    import 'dart:io';
    void main()
    {
        // Asking for favourite number
        print("Enter your favourite number:");
        
        // Scanning number
        int n = int.parse(stdin.readLineSync()!);
        // Here ! is for null safety
        
        // Printing that number
        print("Your favourite number is $n");
    }

1.4.2 Standard Output in Dart

In dart, there are two ways to display output in the console:

  • Using print() statement.

  • Using stdout.write() statement.

    import 'dart:io';
        
    void main()
    {
        // Printing in first way
        print("Welcome!"); // printing from print statement
        
        // Printing in second way
        stdout.write("Welcome!\n");  // printing from stdout.write()
    }

The print() statement brings the cursor to next line while stdout.write() does not bring the cursor to the next line, it remains in the same line.

2 Datatypes in Dart

2.1 Numbers

  • int: The int data type is used to represent whole numbers. Syntax: int var_name;

  • double: The double data type is used to represent 64-bit floating-point numbers. Syntax: double var_name;

  • num: The num type is an inherited data type of the int and double types.

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

The parse() function is used parsing a string containing numeric literal and convert to the number.

    void main()
    {       
        var a1 = num.parse("1");  
        var b1 = num.parse("3.14");         
        var c1 = a1+b1;   
        print("Product = ${c1}");  
        
        num a2 = num.parse("2");  
        num b2 = num.parse("2.73");         
        num c2 = a2+b2;   
        print("Product = ${c2}"); 
        
        int a3 = int.parse("3");  
        double b3 = double.parse("1.6");        
        num c3 = a3+b3;   
        print("Product = ${c3}"); 
    }

Some methods:

  • abs(): This method gives the absolute value of the given number.

  • ceil(): This method gives the ceiling value of the given number.

  • floor(): This method gives the floor value of the given number.

  • compareTo(): This method compares the value with other numbers.

  • remainder(): This method gives the truncated remainder after dividing the two numbers.

  • round(): This method returns the round of the number.

  • toDouble(): This method gives the double equivalent representation of the number.

  • toInt(): This method returns the integer equivalent representation of the number.

  • toString(): This method returns the String equivalent representation of the number

  • truncate(): This method returns the integer after discarding fraction digits.

2.2 Strings

Strings can be defined usinge either single or double quotes, e.g. String str = "I love food"; and String str = ’I love food’;.

You can put the value of an expression inside a string by using $expression. This is called interpolation. Strings can also be concatenated using +.

    void main()
    {       
        String str1 = 'dart';
        String str2 = 'c';
        // interpolation
        print ("I prefer $str1 to $str2.");
        // concatenation
        print ("I prefer " + str1 + " to " + str2 + ".");
    }

2.3 Lists

In Dart programming, the List data type is similar to arrays in other programming languages. List is used to representing a collection of objects. It is an ordered group of objects.

    void main()
    {
        List<String> fruits = ["apple", "orange", "banana"];
        var vegetables  = ["potato", "onion"];
        
        // Printing all the values in List
        print("fruits = $fruits.");
        print("vegetables = $vegetables.");
        
        // Adding new value in List and printing it
        fruits.add("pineapple");
        print("fruits = $fruits.");
        
        // Adding multiple values
        vegetables.addAll(["carrot", "lettuce"]);
        print("vegetables = $vegetables.");
        
        // Insert at a specific index
        fruits.insert(2, 'kiwi'); 
        print("fruits = $fruits.");
        
        // Insert many at a specific index
        fruits.insertAll(1, ['melon', 'peach']); 
        print("fruits = $fruits.");
        
        // Remove item
        fruits.remove("banana");
        print("fruits = $fruits.");
        
        // Remove item at index
        fruits.removeAt(3);
        print("fruits = $fruits.");
        
        // Remove all
        fruits.clear();
        print("fruits = $fruits.");
        
        // Multidimentional Lists
        List<List<String>> table = [];
        List<String> row1 = ["item11", "item12"];
        List<String> row2 = ["item21", "item22"];
        List<String> row3 = ["item23", "item23"];
        table.add(row1);
        table.add(row2);
        table.add(row3);
        print("table = $table.");
        
        table[0].remove("item11");
        print("table = $table.");
        
        List<List<List<String>>> hyperTable = [];
        hyperTable.addAll([table, [["item31", "item32"],["item41", "item42"]]]);
        print("hyperTable = $hyperTable.");
    }

3 Control Flow in Dart

Decision-making statements are those statements that allow the programmers to decide which statement should run in different conditions.

3.1 Conditional Statements

3.1.1 If Statement

There are four ways to achieve this:

  • if Statement

  • if-else Statement

  • else-if Ladder

  • Nested if Statement

    void main()
    {
        int val = 10;
        if (val < 9) 
        {
            print("Condition 1 is true");
            val++;
        }
        else if (val < 10) 
        {
            print("Condition 2 is true");
        }
        else if (val >= 10) 
        {
            print("Condition 3 is true");
        }       
        else 
        {
            print("All the conditions are false");
        }
    }

3.1.2 Switch Statement

Switch-case statements are a simplified version of the nested if-else statements. Its approach is the same as that in Java. Rules to follow in switch case:

  • There can be any number of cases. But values should not be repeated.

  • The case statements can include only constants. It should not be a variable or an expression.

  • There should be a flow control i.e break within cases. If it is omitted than it will show error.

  • The default case is optional.

  • Nested switch is also there thus you can have switch inside switch.

    void main() 
    { 
        int val = 1; 
        switch (val) 
        { 
            case 1: 
            { 
                print("GeeksforGeeks number 1"); 
            } break; 
            case 2: 
            { 
                print("GeeksforGeeks number 2"); 
            } break; 
            case 3: 
            { 
                print("GeeksforGeeks number 3"); 
            } break; 
            default: 
            { 
                print("This is default case"); 
            } break; 
        } 
    } 

3.2 Loop Statements

A looping statement in Dart or any other programming language is used to repeat a particular set of commands until certain conditions are not completed. There are different ways to do so. They are:

  • for loop

  • for… in loop

  • for each loop

  • while loop

  • do-while loop

3.2.1 for loop

    void main()
    {
        for (int i = 0; i < 5; i++) 
        {
            print('Hello!');
        }
    }

3.2.2 for .. in loop

    void main()
    {
        var list = [ 1, 2, 3, 4, 5 ];
        for (int i in list) 
        {
            print(i);
        }
    }

3.2.3 for each ... loop

    void main() 
    {
        var list = [1,2,3,4,5];
        list.forEach((var num)=> print(num)); 
    }

3.2.4 while loop

    void main()
    {
        var val = 4;
        int i = 1;
        while (i <= val) 
        {
            print('Hello!');
            i++;
        }
    }

3.2.5 do .. while loop

    void main()
    {
        var val = 4;
        int i = 1;
        do 
        {
            print('Hello!');
            i++;
        } while (i <= val);
    }

3.2.6 Break Statement

This statement is used to break the flow of control of the loop i.e if it is used within a loop then it will terminate the loop whenever encountered. It will bring the flow of control out of the nearest loop.

    void main() 
    { 
        int count = 1; 
        
        while (count <= 10) 
        { 
            print("You are inside loop $count"); 
            count++; 
            
            if (count == 4) 
            { 
                break; 
            } 
        } 
        print("You are out of while loop"); 
    }

3.2.7 Continue Statement

While the break is used to end the flow of control, continue on the other hand is used to continue the flow of control. When a continue statement is encountered in a loop it doesn’t terminate the loop but rather jump the flow to next iteration.

    void main() 
    { 
        int count = 0; 
        
        while (count <= 10) 
        { 
            count++; 
            
            if (count == 4) 
            { 
                print("Number 4 is skipped"); 
                continue; 
            } 
            
            print("You are inside loop $count"); 
        } 
        
        print("You are out of while loop"); 
    } 

4 Functions

The function has the following.

  • function_name: defines the name of the function.

  • return_type: defines the datatype in which output is going to come.

  • return value: defines the value to be returned from the function.

    int add(int a, int b)
    {
        // Creating function
        int result = a + b;
        // returning value result
        return result;
    }
    
    void main(){
        // Calling the function
        var output = add(10, 20);
        
        // Printing output
        print(output);
    }

Dart allows functions with optional parameters, and lambda functions or arrow functions. But you should note that with lambda functions you can return value for only one expression.

5 Classes + Summary

    import "dart:collection";
    import "dart:math" as math;
    void main()
    {       

        // Single line comment
        /**
        * Multi-line comment
        * Can comment several lines
        */
        /// Code doc comment
        /// It uses markdown syntax to generate code docs when making an API.
        /// Code doc comment is the recommended choice when documenting your APIs, classes and methods.     
        
        /// Constants are variables that are immutable cannot be change or altered.
        const myConst = "I CANNOT CHANGE";
        myConst = "DID I?"; //Error
        
        /// Final is another variable declaration that cannot be change once it has been instantiated. Commonly used in classes and functions
        /// `final` can be declared in pascalCase.
        final myVar = "value cannot be changed once instantiated";
        myVar = "Seems not"; //Error
        
        /// `var` is another variable declaration that is mutable and can change its value. Dart will infer types and will not change its data type
        var myVar = "Variable string";
        myVar = "this is valid";
        myVar = false; // Error.
        
        /// `dynamic` is another variable declaration in which the type is not evaluated by the dart static type checking.
        /// It can change its value and data type.      
        dynamic myVar = "I'm a string";
        myVar = false; // false     
        
        /// Functions can be declared in a global space
        /// Function declaration and method declaration look the same. 
        /// Dart will execute a function called `main()` anywhere in the dart project.
        myFun1() 
        {                       
            myFun2();
        }
        
        myFun2() 
        {
            // ...
        }
                
        /// Functions have closure access to outer variables.

        /// In this example dart knows that this variable is a String.
        var myVar = "An external variable";
        fun3() 
        {
            print(myVar);
        }
        
        /// Class declaration takes the form of class name { [classBody] }.
        /// Where classBody can include instance methods and variables, but also
        /// class methods and variables.
        class MyClass
        {
            String myVar1 = "I am a public variable";
            String _myVar2 = "I am a private variable"; // to a file
            
            MyClass(String myVar1, String myVar2)
            {
                this.myVar1 = myVar1;
                this._myVar2 = myVar2;
            }
            
            String getVar1()
            {
                return myVar1;
            }
            String get getVar1Ugly
            {
                return myVar1;
            }
            void setVar1(String someVar)
            {
                this.myVar1 = someVar;
            }
            void set setVar1Ugly(String someVar)
            {
                this.myVar1 = someVar;
            }
        }
        
        main()
        {
            MyClass myClass = new MyClass("1", "2");
            print("myClass.myVar1 = ${myClass.getVar1Ugly}");
            myClass.setVar1Ugly = "5";
            print("myClass.myVar1 = ${myClass.getVar1Ugly}");
        }   
    
        /// Inheritance
        // Base class
        class Animal {
            String name = "";
            
            // Constructor
            Animal(String name)
            {
                this.name = name;
            }
            
            // Method in the base class
            void makeSound()
            {
                print('$name makes a sound.');
            }
        }
        
        // Derived class Cat
        class Cat extends Animal {
            Cat(String name) : super(name);  // Passing name to the Animal constructor
            
            // Overriding the makeSound method
            @override
            void makeSound()
            {
                print('$name says Meow.');
            }
        }
        
        // Derived class Dog
        class Dog extends Animal {
            Dog(String name) : super(name);  // Passing name to the Animal constructor
            
            // Overriding the makeSound method
            @override
            void makeSound()
            {
                print('$name says Woof.');
            }
        }
        
        void main() {
            // Creating an instance of Cat
            Cat cat = Cat('Tom');
            cat.makeSound();  // Output: Tom says Meow.
            
            // Creating an instance of Dog
            Dog dog = Dog('Spike');
            dog.makeSound();  // Output: Spike says Woof.
        }
        
                
        /// Loops in Dart take the form of standard for () {} or while () {} loops,

        String myList = ["a", "b"];
        main() 
        {
            for (int i = 0; i < myList.length; i++) 
            {
                print("${myList[i]}");
            }
            int i = 0;
            while (i < myList.length) 
            {
                print("${myList[i]}");
                i++;
            }
            for (String item in myList) 
            {
                print("$item");
            }
            
            myList.forEach((item) => print("${item}"));
            
        }       
    }
Last modified: Tuesday, 3 December 2024, 3:36 AM