Category: 6. Advance Topics

https://cdn3d.iconscout.com/3d/premium/thumb/3d-software-settings-icon-download-in-png-blend-fbx-gltf-file-formats–setting-configuration-preferences-printing-pack-science-technology-icons-8549424.png?f=webp

  • HTML DOM

    Every webpage can be considered as object and it exists inside a browser window. We can access the webpage using the web browser and it needed connected to the internet. The DOM is the acronyms of Document object model. A Document object denotes the HTML document that is displayed in that window. The document object model consists of several properties that refer to the other objects which give the facility to modify the document content.

    The process that a content of document is accessed is called the Document Object Model, or DOM. The Objects are organized in a hierarchy. The hierarchical structure uses to the organization of objects in a web document.

    • Window – It is the first in the hierarchy. It the outmost element of the object hierarchy.
    • Document – When a HTML document loads into a window that it becomes a window object. The document includes the contents of the page.
    • Elements – It denotes the content on the webpage. For example – Title, text box etc.
    • Nodes – These are often elements, but they also be attributes, comments, text and other DOM types.

    Below is the hierarchy of the few important DOM objects.

    Dart HTML DOM

    We can manipulate the objects and element in the DOM by using the dart:html library. Console-based application cannot use the dart:html library. In work with the HTML library in the web application, we need to import the dart:html.

    1. import ‘dart.html’;  

    Let’s understand the DOM operation in the following section.

    Finding DOM Elements

    A document can contain many attributes sometime we need to search particular attribute. The dart:html library provides the querySelector function to search element in the DOM.

    1. Element querySelector(String selector);  

    The querySelector() function returns the first element that matches the specified group of the selector. Let’s understand the.

    following syntax.

    var element1 = document.querySelector('.className');   
    
    var element2 = document.querySelector('#id');  

      Let’s understand the following example.

      Example –

      We create a HTML file name index.html and also create a dart file.

      <!DOCTYPE html>     
      
      <html>   
      
         <head>       
      
            <meta charset = "utf-8">       
      
            <meta http-equiv = "X-UA-Compatible" content = "IE = edge">       
      
            <meta name = "viewport" content = "width = device-width, initial-scale = 1.0">  
      
            <meta name = "scaffolded-by" content = "https://github.com/google/stagehand">  
      
            <title>DemoWebApp</title>       
      
            <link rel = "stylesheet" href = "styles.css">       
      
            <script defer src = "main.dart" type = "application/dart"></script>  
      
            <script defer src = "packages/browser/dart.js"></script>   
      
         </head>  
      
           
      
         <body>     
      
            <h1>  
      
               <div id = "output"></div>   
      
            </h1>    
      
         </body>   
      
      </html> 

        Main.dart

        import 'dart:html';    
        
        void main() {     
        
           querySelector('#output').text = 'Your Dart web dom app is running!!!.';   
        
        }  

          Event Handling

          The dart:html library provides the onClick event for DOM Elements. The syntax shows how an element could handle a stream of click events.

          querySelector('#Id').onClick.listen(eventHanlderFunction);   

          The querySelector() function returns the element from the given DOM and onClick.listen() will take an eventHandler method which will be invoked when a click event is raised. The syntax of eventHandler is given below ?

          void eventHanlderFunction (MouseEvent event){ }   

          Let us now take an example to understand the concept of Event Handling in Dart.

          TestEvent.html

          <!DOCTYPE html>   
          
          <html>   
          
             <head>   
          
                <meta charset = "utf-8">   
          
                <meta http-equiv = "X-UA-Compatible" content = "IE = edge">   
          
                <meta name = "viewport" content = "width = device-width, initial-scale = 1.0">   
          
                <meta name = "scaffolded-by" content ="https://github.com/google/stagehand">   
          
                <title>DemoWebApp</title>   
          
                <link rel = "stylesheet" href = "styles.css">   
          
                <script defer src = "TestEvent.dart" type="application/dart"></script>   
          
                <script defer src = "packages/browser/dart.js"></script>   
          
             </head>  
          
             <body>   
          
                <div id = "output"></div>   
          
                <h1>   
          
                   <div>   
          
                      Enter you name : <input type = "text" id = "txtName">   
          
                      <input type = "button" id = "btnWish" value="Wish">   
          
                   </div>   
          
                </h1>   
          
                <h2 id = "display"></h2>  

            TestEvent.dart

            import 'dart:html';   
            
            void main() {   
            
               querySelector('#btnWish').onClick.listen(wishHandler);   
            
            }    
            
            void wishHandler(MouseEvent event){   
            
               String name = (querySelector('#txtName')  as InputElement).value;   
            
               querySelector('#display').text = 'Hello Mr.'+ name;   
            
            } 
            1. What is Unit Testing?

              Unit testing is a part of the software development process where particular unit/components of an application are tested. Unit testing of each component is necessary to enhance the application performance. We can say that a unit is the smallest testable chunk of a program that can be logically isolated in a system. In various programming languages, the individual program, a subroutine, a function, a method, or a class can be represented as a Unit. There can be many individual units within the module. In object-oriented programming, the method that belongs to base class/superclass, an abstract class can be represented as smaller units. Below image displays the type of testing.

              Dart Unit Testing

              Unit Testing Task

              The unit testing task is given below.

              • Unit Test Plan
                Prepare
                Review
                Rework
                Baseline
              • Unit Test Cases/Scripts
                Prepare
                Review
                Rework
                Baseline
              • Unit Test
                Perform

              Advantage of Unit Testing

              Few advantages of unit testing are given below.

              1. We can maintain code easily
              2. It makes code more reusable.
              3. It makes development faster.
              4. The code can be easily debugged.
              5. It detects the cost of testing and fixing defects, because any error is captured in the early stage.

              Dart Unit Testing

              In Dart, we required to include an external library named “test”, which facilitates a standard way of writing and running individual unit test. Unit testing can be achieved using the following steps.

              Step – 1: Installing “test” package

              To include the unit testing in our project, we must install a third-party packages “test” in our current working project. Let’s open the pubspec.yaml in the our project and type the following statement.

              1. dependencies:  
              2. test:  

              Now, right-click on pubspec.yaml file and click on Pub: get dependencies. This will install the “test” package in our project.

              Dart Unit Testing

              We can also install it by using the following command.

              1. pub get  

              Step – 2: Importing “test” package

              Type the following line to import the “test” package in your project.

              import "package:test/test.dart";  

              Step – 3: Writing Test Cases

              The top-level test() function is added by the Test cases. In the test() function, we make the test assertion using the expect() function. The expert() function takes two arguments actualValue and MatchValue.

              Syntax:

              test("Test Description", () {  
              
                 expert(actualValue, matchingValue)  
              
              }); 

                Group of Test Cases

                We can create a group of multiple test cases using the group() function. It helps grouping of test cases based on some criteria. The description of each group is specified in the beginning of its test’s description.

                Syntax:

                The syntax is given below.

                group("Test_Group_Name", () {   
                
                   test("test_case_name_1", () {   
                
                      expect(actual, equals(exptected));   
                
                   });    
                
                   test("test_case_name_2", () {   
                
                      expect(actual, equals(expected));   
                
                   });   
                
                })  

                  Example – 1(Passing Test)

                  Here is the example where we define an add() method for unit test. It accepts two parameters as an integer values and returns an integer representing the sum. To test the add() method, understand the following example –

                  Step – 1: We import the test package.

                  Step -2: We define the test using the test() function and it uses the expert() function to impose an assertion.

                  import 'package:test/test.dart';        
                  
                  // Importing  the test package   
                  
                    
                  
                  int add(int x,int y)                    
                  
                  // this function to be tested {   
                  
                     return x+y;   
                  
                  }    
                  
                  void main() {   
                  
                     // Defining the test function   
                  
                     test("test to check add method",(){    
                  
                        // Arrange   
                  
                        var expected = 30;   
                  
                          
                  
                        // Act   
                  
                        var actual = add(10,20);   
                  
                          
                  
                        // Asset   
                  
                        expect(actual,expected);   
                  
                     });   
                  
                  }  

                    Output:

                    00:00 +0: test to check add method
                    00:00 +1: All tests passed!
                    

                    Example – 2 A unsuccessful Test

                    We define the sub() method which has a logical mistake. Let’s have a following example.

                    import 'package:test/test.dart';   
                    
                    int add(int x,int y){   
                    
                       return x+y;   
                    
                    }  
                    
                    int sub(int x,int y){   
                    
                       return x-y-1;   
                    
                    }    
                    
                    void main(){   
                    
                       test('test to check sub',(){   
                    
                          var expected = 10;     
                    
                          // Arrange   
                    
                            
                    
                          var actual = sub(30,20);    
                    
                          // Act   
                    
                            
                    
                          expect(actual,expected);    
                    
                          // Assert   
                    
                       });   
                    
                       test("test to check add method",(){   
                    
                          var expected = 30;     
                    
                          // Arrange   
                    
                            
                    
                          var actual = add(10,20);    
                    
                          // Act   
                    
                            
                    
                          expect(actual,expected);    
                    
                          // Asset   
                    
                       });   
                    
                    } 

                      Output:

                      00:00 +0: test to check sub
                      00:00 +0 -1: test to check sub
                      Expected: <10>
                      Actual: <9>
                      package:test expect
                      bin\Test123.dart 18:5 main.<fn>
                      
                      00:00 +0 -1: test to check add method
                      00:00 +1 -1: Some tests failed.
                      Unhandled exception:
                      Dummy exception to set exit code.
                      #0 _rootHandleUncaughtError.<anonymous closure> (dart:async/zone.dart:938)
                      #1 _microtaskLoop (dart:async/schedule_microtask.dart:41)
                      #2 _startMicrotaskLoop (dart:async/schedule_microtask.dart:50)
                      #3 _Timer._runTimers (dart:isolate-patch/timer_impl.dart:394)
                      #4 _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:414)
                      #5 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:148)
                      

                      In the above example, the add() function is tested successfully but the sub() function failed the unit test due to logical error.

                      Grouping Test Cases

                      We can write the multiple test cases in the form of group. The group() is used to grouped together these methods. It helps to write much cleaner code.

                      In the following example, we are writing a test case for the split() function and the trim() function. We grouped together these function and name it String.

                      Let’s understand the following example –

                      Example –

                      import "package:test/test.dart";   
                      
                      void main() {   
                      
                        
                      
                         group("String", () {   
                      
                           // First test case  
                      
                            test("testing on split() method of string class", () {   
                      
                               var string = "Hii,Hello,Hey";   
                      
                               expect(string.split(","), equals(["Hii", "Hello", "Hey"]));   
                      
                            });   
                      
                            // Second test case  
                      
                            test("testing on trim() method of string class", () {   
                      
                               var string = "  Hii ";   
                      
                               expect(string.trim(), equals("Hii"));   
                      
                            });   
                      
                         });   
                      
                      }

                      Output:

                      00:00 +0: String testing on split() method of string class
                      00:00 +1: String testing on trim() method of string class
                      00:00 +2: All tests passed
                      
                    1. What is Concurrency?

                      The Dart concurrency allows us to run multiple programs or multiple parts of a program simultaneously. It executes the several instructions at the same time. Dart provides the Isolates as a tool for doing works for parallel. The concurrency makes the program highly effective and throughput by utilizing the unused capabilities of essential operating system and machine hardware.

                      How to achieve concurrency?

                      In Dart, we can achieve concurrency by using the Isolates. We have discussed Dart isolates in previous tutorial. Here we will understand the brief introduction of it. Dart isolate is a version of the thread. But there is key difference between the common implementation of “Thread” or “Isolates”. The isolate works differently in comparison of Thread. The isolates are independent workers that do not share memory, but instead interconnect by passing message over channels. Since isolates completes its task by passing message thus it need a way to serialize a message.

                      The communication between the isolates is done by the message passing as a client and server. It helps the program to take advantage of multicore microprocessor out of the box.

                      Dart provides the dart:isolate package to apply the isolate in our program. It provides the solution to taking single-threaded Dart code and allowing application to make greater use of the hardware available.

                      Let’s understand the following example –

                      Example –

                      import 'dart:isolate';    
                      
                      void sayhii(var msg){   
                      
                         print('execution from sayhii ... the message is :${msg}');   
                      
                      }    
                      
                      void main(){   
                      
                         Isolate.spawn(sayhii,'Hello!!');   
                      
                         Isolate.spawn(sayhii,'Whats up!!');   
                      
                         Isolate.spawn(sayhii,'Welcome!!');   
                      
                           
                      
                         print('execution from main1');   
                      
                         print('execution from main2');   
                      
                         print('execution from main3');   
                      
                      }  

                        Output:

                        execution from main1
                        execution from main2
                        execution from main3
                        execution from sayhii ... the message is :Whats up!!
                        execution from sayhii ... the message is :Hello!!
                        

                        Output 2:

                        execution from main1
                        execution from main2
                        execution from main3
                        execution from sayhii ... the message is :Hello!!
                        execution from sayhii ... the message is :Welcome!!
                        

                        The concept of the above code is similar to the dart isolates. If we run the above program multiple times, then output will be varied every time.

                      1. Async

                        Dart Async is related to asynchronous programming. It executes the asynchronous operation in a thread. It ensures that the critical functions to be executed until completion. The asynchronous operation is executed, separately the main application thread. In Dart, one operation cannot interrupt the other operation; it means one operation can execute at a time no other part of the program can avert it. Let’s understand the following example –

                        Example –

                        import 'dart:io';   
                        
                        void main() {   
                        
                           print("Enter your favorite car :");              
                        
                             
                        
                           // prompt for user input   
                        
                           String car = stdin.readLineSync();    
                        
                             
                        
                           // this is a synchronous method that reads user input   
                        
                           print("The car is  ${car}");   
                        
                           print("End of main");   
                        
                        }  

                          Output

                          Enter your favorite car :
                          Renault Duster
                          The car is Renault Duster
                          End of main
                          

                          Explanation:

                          In the above code, we used the readLineSync(), which is synchronous method. It means; the execution of all instructions that follow the readLineSync() method call will be blocked until the readLineSync() method doesn’t complete its execution.

                          The stdin.readLineSync () executes nothing until it gets the input from the user. It waits for the user input for further execution.

                          Difference between Asynchronous and Synchronous

                          Let’s understand the difference between synchronous and asynchronous.

                          In computer science, if we say a particular program is synchronous, that means it waits for an event to execute further. This approach is driven with a demerit, if a part of the code takes much time to execute, the succeeding blocks through an unrelated block will be blocked from executing.

                          This is the main problem of the synchronous approach. A part of the program may require executing before the current part, but the synchronous approach doesn’t allow it.

                          This is not suitable for the webservers, where request must be independent of the others. It means, the webserver does not wait to finish the execution of the current request, it responds to the request from the other users.

                          The web server should accept the request from the other user before executing the previous requests.

                          This approach is called asynchronous programming. The asynchronous programming generally focuses on no waiting or non-blocking programming model. The dart: async is facilitated to implement the asynchronous programming block in a Dart script.

                          Example –

                          We create a file with the few names and save this file as names.txt and write a program to read this file without delaying the other part of the code.

                          1, Peter  
                          
                          2, John  
                          
                          3, Tom  
                          
                          4, Johnson  

                            Consider the following code.

                            import "dart:async";   
                            
                            import "dart:io";    
                            
                              
                            
                            void main(){   
                            
                               File file1 = new File("C:\Users\DEVANSH SHARMA\Desktop\contact.txt");   
                            
                               Future<String> fs = file1.readAsString();    
                            
                                
                            
                               // returns a future object, it is an async method   
                            
                               fs.then((data)=>print(data));    
                            
                                 
                            
                               // once file is read, call back method is invoked    
                            
                               print("End of main");    
                            
                               
                            
                            }

                            Output

                            End of main
                            1, Peter
                            2, John
                            3, Tom
                            4, Johnson
                            

                            Dart Future

                            The Dart Future is defined as getting a result sometime in the future. The Future object uses to facilitate asynchronous programming. Future objects are a tool to denote values returned by an expression whose execution will complete at a later point in time (In Future). In order to work with the future, we can use either async and await or the Future API.

                            Dart async and await

                            The async and await keywords are allowed to implement asynchronous programming without using the Future API. The async keyword is necessary to run function asynchronously; we need to add async after the function name. The syntax is given below:

                            Syntax:

                            func_name() async {  
                            
                               //function body  
                            
                            } 

                              When an async function is invoked, the Future object instantly returns and that indicates the async function will execute later. Once the body of the async function is executed, the function call returned the Future object. The function call will be completed with its result.

                              Dart await Keyword

                              The await keyword is also used to execute function asynchronously. It suspends the currently running function until the result is ready. When it returns the result, then it continues on to the next line of code. The await keyword can only be used with async functions. The syntax is given below.

                              Syntax:

                              await e;  

                              Here, e is an asynchronous expression, and it is expected to evaluate to a Future. The await expression evaluates e, and then suspends the currently running function until the result is ready.

                              Let’s understand the following example –

                              Example – 1

                              void hii() async {  
                              
                                       print("Hii Javatpoint");  
                              
                                
                              
                              }  
                              
                                
                              
                              void main() async {  
                              
                                       await hii();            // Using await keyword  
                              
                                       print("Task Complete");  
                              
                                
                              
                              }

                              Output

                              Hii JavaTpoint
                              Task Complete
                              

                              Explanation:

                              Here, we have declared the main() function asynchronous using the async keyword because we call the hii() method asynchronously. Then, we used await modifier to call hii() that executed asynchronously.

                            1. Isolates

                              Dart allows us to asynchronous programming which runs our program without getting blocked. The asynchronous programming is used to achieve concurrency. Dart isolate is a version of the thread. But there is key difference between the common implementation of “Thread” or “Isolates”. The isolate works differently in comparison of Thread. The isolates are independent workers that do not share memory, but instead interconnect by passing message over channels. Since isolates completes its task by passing message thus it need a way to serialize a message.

                              The communication between the isolates is done by the message passing as a client and server. It helps the program to take advantage of multicore microprocessor out of the box.

                              Dart provides the dart:isolate package to apply the isolate in our program. It provides the solution to taking single-threaded Dart code and allowing application to make greater use of the hardware available.

                              Create and Start an Isolate

                              Dart provides the spawn() method to create an isolate. It must be declared with an ‘entry point’ with a single parameter. This parameter displays a port which isolate use to refer back notification message.

                              Let’s understand the following example –

                              Example –

                              import 'dart:isolate';    
                              
                              void sayhii(var msg){   
                              
                                 print('execution from sayhii ... the message is :${msg}');   
                              
                              }    
                              
                              void main(){   
                              
                                 Isolate.spawn(sayhii,'Hello!!');   
                              
                                 Isolate.spawn(sayhii,'Whats up!!');   
                              
                                 Isolate.spawn(sayhii,'Welcome!!');   
                              
                                   
                              
                                 print('execution from main1');   
                              
                                 print('execution from main2');   
                              
                                 print('execution from main3');   
                              
                              } 

                                Output:

                                execution from main1
                                execution from main2
                                execution from main3
                                execution from sayhii ... the message is :Whats up!!
                                execution from sayhii ... the message is :Hello!!
                                

                                Output 2:

                                execution from main1
                                execution from main2
                                execution from main3
                                execution from sayhii ... the message is :Hello!!
                                execution from sayhii ... the message is :Welcome!!
                                

                                Explanation:

                                In the above program, the spawn method of the isolate class executed a function sayhii in parallel of remaining code. It takes two parameters.

                                • The function that we want to spawned and the string that will be passed to the spawned function.

                                We have two functions sayhii() and main() function might not run in the same order each time. If you run the above program, then the output will be different each time as we can see in second output.

                                Note – We can also pass NULL value if there is no object to pass in spawned function.

                                Let’s understand the another example –

                                Example – 2

                                void start() async {  
                                
                                         ReceivePort  receiverPort = ReceiverPort();   // Port for isolate to receive message.  
                                
                                         isolate = await Isolate.spawn(runTimer, receiverPort.sendPort);  
                                
                                         receivePort.listen((data){  
                                
                                               stdout.write('Receiving: '+ data + ', ');  
                                
                                  
                                
                                     });  
                                
                                  
                                
                                }  
                                
                                void runTimer(SendPort, sendPort) {  
                                
                                int coun = 0;  
                                
                                Timer.periodic(new Duration(seconds: 1), (Timer t) {  
                                
                                     count++;  
                                
                                     String msg = 'notification ' + count.toString();  
                                
                                     stdout.write('Sending: ' + msg + ' -');  
                                
                                     sendPort.send(msg);  
                                
                                  
                                
                                });  
                                
                                }

                                Explanation:

                                In the above code, we created an asynchronous method start() which creates a port and spawn an isolate. We signified the start method as async because of wan can await the response from the spawning of the isolates and to store a reference to the new isolate. It is essential when we want to kill the running isolates. We passed the two parameters in the spawn() method, the first parameter runTimer method, that is a callback function to execute runTimer() and second parameter sendPort which is a callback function and it will used to send message back to the caller. The start() method starts listening the receiverPort for message from isolate. Once it will receive the message then it will print as a console output.

                                The runTimer() method begins a timer that fires every second in order to update a counter. It sends a notification message via the port which it received when the isolate was spawned.

                                Stop an Isolate

                                The dart: isolates package provides the kill() method which is used to stop a running isolate.

                                Let’s understand the following example.

                                Example –

                                void stop() {    
                                
                                        If (isolate != null) {  
                                
                                        stdout.writeln('Stopping Isolate');  
                                
                                        isolate.kill(priority: Isolate.immediate);  
                                
                                        isolate = null;  
                                
                                        }  
                                
                                }  

                                  Explanation:

                                  In the above example, we have declared a stop() method that will destroy the running isolate and sets its reference to null. We defined the priority of isolate: immediate that will terminate the isolate as soon as.

                                  Complete Program

                                  import 'dart:io';  
                                  
                                  import 'dart:async';  
                                  
                                  import 'dart:isolate';  
                                  
                                    
                                  
                                  Isolate isolate;  
                                  
                                    
                                  
                                  // Start the isolate   
                                  
                                  void start() async {  
                                  
                                           ReceivePort  receiverPort = ReceiverPort();   // Port for isolate to receive message.  
                                  
                                           isolate = await Isolate.spawn(runTimer, receiverPort.sendPort);  
                                  
                                           receivePort.listen((data){  
                                  
                                                 stdout.write('Receiving: '+ data + ', ');  
                                  
                                    
                                  
                                       });  
                                  
                                    
                                  
                                  }  
                                  
                                  void runTimer(SendPort, sendPort) {  
                                  
                                  int coun = 0;  
                                  
                                  Timer.periodic(new Duration(seconds: 1), (Timer t) {  
                                  
                                       count++;  
                                  
                                       String msg = 'notification ' + count.toString();  
                                  
                                       stdout.write('Sending: ' + msg + ' -');  
                                  
                                       sendPort.send(msg);  
                                  
                                    
                                  
                                  });  
                                  
                                  }  
                                  
                                    
                                  
                                  // Stopping the isolate using the stop() function.  
                                  
                                  void stop() {  
                                  
                                      if (isolate != null) {  
                                  
                                            stdout.writeln('Stopping Isolate.....');  
                                  
                                            isolate.kill(priority:Isolate.immediate);  
                                  
                                            isolate = null;   
                                  
                                       }  
                                  
                                  }  
                                  
                                    
                                  
                                  void main() async {  
                                  
                                      stdout.writeln('Starting Isolate...');  
                                  
                                      await start();  
                                  
                                      std.writeln('Hit enter key to quit');  
                                  
                                      await stdin.first;  
                                  
                                      stop();  
                                  
                                      stdout.writeln('Bye!');  
                                  
                                      exit(0);  
                                  
                                  }  

                                    Output:

                                    Stating Isolate
                                    Hit enter key to quit
                                    Sending: notification 1 - Receiving: notification 1, Sending: notification 2 - Receiving: notification 2,
                                    Stopping Isolate
                                    
                                  1. Callable Classes

                                    Dart provides the facility to call class instances like a function. To make callable class, we need to implement a call() method in it. Let’s understand the following example –

                                    Example – 1

                                    class Student {  
                                    
                                      String call(String name, int age) {  
                                    
                                                  return('Student name is $name and Age is $age');  
                                    
                                      
                                    
                                               }  
                                    
                                    }  
                                    
                                    void main() {  
                                    
                                       Student stu = new Student();  
                                    
                                       var msg = stu('Sharma',18);     // Class instance called like a function.  
                                    
                                       print('Dart Callable class');  
                                    
                                       print(msg);  
                                    
                                    } 

                                      Output

                                      Dart Callable class
                                      Student name is Sharma and Age is 18
                                      

                                      Explanation:

                                      In the above code, We defined a call() function in the class Student that takes two arguments String name, integer age and return a message with this information. Then, we have created the object of class Student and called it like a function.

                                      var msg = stu('Sharma',18);       

                                      Let’s have a look at another example –

                                      Example – 2 Multiple callable class

                                      class Student {  
                                      
                                        String call(String name, int age) {  
                                      
                                                    return('Student name is $name and Age is $age');  
                                      
                                        
                                      
                                                 }  
                                      
                                      }  
                                      
                                        
                                      
                                      class Employee {  
                                      
                                        int call(int empid, int age) {  
                                      
                                                    return('Employee id is ${empid} and Age is ${age}');  
                                      
                                        
                                      
                                                 }  
                                      
                                      }  
                                      
                                        
                                      
                                      void main() {  
                                      
                                         Student stu = new Student();  
                                      
                                        
                                      
                                         Employee emp = new Employee();  
                                      
                                        
                                      
                                         var msg = stu('peter',18);  // Class instance called like a function.  
                                      
                                         var msg2 = emp(101,32);   // Class instance called like a function.  
                                      
                                         print('Dart Callable class');  
                                      
                                         print(msg);  
                                      
                                         print(msg2);  
                                      
                                      } 

                                        Output

                                        Dart Callable class
                                        Student name is peter and Age is 18
                                        Employee id is 101 and Age is 32
                                        

                                        Explanation:

                                        In the above code, we defined two callable functions in class Student and class Employee. The Employee class call() function accepts two parameters as String empid and int age. We called instances of both classes as callable functions.

                                        var msg = stu('peter',18);    
                                        
                                        var msg2 = emp(101,32); 
                                        1. Generators

                                          Dart Generator is a unique function that allows us to produce a sequence of values. Generators return values on demand; it means the value is generated when we try to iterate over the iterators. Dart provides built-in support for two types of generator functions.

                                          • Synchronous Generators
                                          • Asynchronous Generators

                                          Synchronous Generator

                                          It returns an iterable object which carries value synchronously. The yield keyword is used along with marking the synchronous generator function body as sync* to generator values.

                                          Let’s understand the following example of a synchronous generator.

                                          Example –

                                          main()  {  
                                          
                                              print("Dart Synchronous Generator Example.");  
                                          
                                              oddNumber(10).forEach(print);   
                                          
                                          }  
                                          
                                              // syn* functions returns an iterable  
                                          
                                            
                                          
                                             Iterable<int> oddNumber(int num) sync* {  
                                          
                                              int k = num;  
                                          
                                              while(k >= 0) {  
                                          
                                                   if(k%2 == 1) {  
                                          
                                                      // 'yield' statement  
                                          
                                                      yield k;  
                                          
                                            
                                          
                                                          }  
                                          
                                          k--;  
                                          
                                          }  
                                          
                                          }

                                          Output

                                          Dart Synchronous Generator Example.
                                          9
                                          7
                                          5
                                          3
                                          1
                                          

                                          Explanation:

                                          In the above program, we declared an oddNumber(10) function with the foreach loop without its body. The foreach loop will iterate the function. Now, we created oddNumber(10) function as synchronous generator function.

                                          In the function body, we initialized a new variable k, which assigns the argument n. Then, we applied while loop to iterate the function, and the loop body is iterated until the value of k is less than or equal to 0.

                                          We did modulus operation on k to find the odd numbers from the generators. We used the yield statement, which suspends the function’s execution and returns the value at a time. It will return the value of each execution of the generator function. When the while loop’s condition becomes false, then the loop terminated and prints the odd numbers.

                                          Asynchronous Generators

                                          It returns a stream object which carries value asynchronously. The yield keyword is used along with marking the asynchronous generator function body as async* to generator values.

                                          Let’s understand the following example –

                                          Example –

                                          main()  {  
                                          
                                              print("Dart Asynchronous Generator Example.");  
                                          
                                              asyncNaturalsTo(10).forEach(print);   
                                          
                                          }  
                                          
                                              // async* functions returns an stream object  
                                          
                                            
                                          
                                             Stream<int> asyncNaturalsTo(int num) async* {  
                                          
                                              int k = 0;  
                                          
                                              while(k < num) {  
                                          
                                             
                                          
                                                      // 'yield' statement  
                                          
                                                      yield k++;  
                                          
                                            
                                          
                                                          }  
                                          
                                          k--;  
                                          
                                          } 

                                            Output

                                            Dart Asynchronous Generator Example.
                                            0
                                            1
                                            2
                                            3
                                            4
                                            5
                                            6
                                            7
                                            8
                                            9
                                            

                                            Explanation:

                                            The above code generated values asynchronously. The asyncNaturalsTo(int num) function returns a stream objects in each execution of function body. Here, the yield keyword behaved the same as the previous example; it stopped the execution of the function, returned the value, and resumed the execution for the next iteration. It will happen again and again until the function body is terminated.

                                            Let’s understand the following concepts related to the generator function.

                                            The yield Keyword

                                            The yield returns the single value to the sequence at a time but does not stop the execution of the generator function completely. It returns a value for each execution of the generator function.

                                            The sync* Keyword –

                                            The sync* keyword is used to declare the synchronize generator function. It returns the value when we try to iterator the value not when it was created. Let’s have a look at the following example –

                                            Example –

                                            void main() {  
                                            
                                              print('creating iterator');  
                                            
                                              Iterable<int> numbers = getNumbers(4);  // Here we are creating iterator  
                                            
                                              print('Iteration starts...');  
                                            
                                              for (int i in numbers) {  
                                            
                                                print('$i');        // Iterate over the iterator  
                                            
                                              }  
                                            
                                              print('end of main function');  
                                            
                                            }  
                                            
                                            Iterable<int> getNumbers(int n) sync* {            // define generator synchronously  
                                            
                                              print('generator started');  
                                            
                                              for (int i = 0; i < n; i++) {  
                                            
                                                yield i;  
                                            
                                              }  
                                            
                                              print('generator function ended');  
                                            
                                            }  

                                              Output

                                              creating iterator
                                              Iteration starts...
                                              generator started
                                              0
                                              1
                                              2
                                              3
                                              generator function ended
                                              end of main function
                                              

                                              Explanation –

                                              The above generator function generated the value when we iterate over the iterator.

                                              The async* Keyword

                                              The async keyword is used to declare the asynchronous generators. It returns the stream object. Let’s understand the following example –

                                              Example –

                                              void main() {  
                                              
                                                print('creating iterator');  
                                              
                                                Stream<int> numbers = getNumbers(4);  
                                              
                                                print('starting to listen...');  
                                              
                                                numbers.listen((int k) {  
                                              
                                                  print('$k');  
                                              
                                                });  
                                              
                                                print('end of the main function');  
                                              
                                              }  
                                              
                                              Stream<int> getNumbers(int number) async* {   // declaring asynchronous generator function  
                                              
                                                print('waiting inside generator a 3 seconds :)');   
                                              
                                                await new Future.delayed(new Duration(seconds: 3)); //sleep 3s  
                                              
                                                print('started generating values...');  
                                              
                                                for (int i = 0; i < number; i++) {  
                                              
                                                  await new Future.delayed(new Duration(seconds: 1)); //sleep 1s  
                                              
                                                  yield i;  
                                              
                                                }  
                                              
                                                print('ended generating values...');  
                                              
                                              } 

                                                Output

                                                creating iterator
                                                starting to listen...
                                                end of the main function
                                                waiting inside generator a 3 seconds :)
                                                started generating values...
                                                0
                                                1
                                                2
                                                3
                                                ended generating values...
                                                
                                              1. Libraries

                                                In Dart, the library is the collection of the routine or set of programming instructions. Dart consists of many sets of built-in libraries that are beneficial to hold routines (functions, set of classes, etc.), and regularly used. A Dart library contains constants, functions, properties, exceptions, and typedefs, and set of classes.

                                                Importing a library

                                                To work with the library, we must import it into the current program. The Dart provides the import keyword, which is used to make the library available in the current file. We can use multiple libraries in a single file.

                                                For example – Dart built-in library URIs is used as dart scheme to refer to a library. Other libraries can use a file system path or the package: scheme to specify its URIs. The package manager pub in Dart provides the libraries and uses the package scheme.

                                                We are describing some commonly used libraries below.

                                                Sr.LibraryDescription
                                                1.dart:ioThis library consists of File, HTTP, socket, and other I/O support for server applications. This library is not suitable for browser-based applications. We don’t need to import explicitly because it is imported by default.
                                                2.Dart:coreThis library consists of Collection, built-in types, and other core functionality for each dart program. It is imported by default.
                                                3.Dart: mathThis library consists of the rich mathematical functions, constant, and random number generator.
                                                4.Dart: convertIt is used to Encoders and decoders for converting the different data representations such as JSON and UTF
                                                5.Dart: typed_dataIt represents the lists that store the fixed-sized data efficiently (for example – unsigned 8-byte integer).

                                                Let’s understand the following example of importing and using a library function.

                                                Example – Importing and using a Library

                                                import 'dart:math';   // Importing built-in library  
                                                
                                                void main() {   
                                                
                                                   print("Square root of 36 is: ${sqrt(36)}");   
                                                
                                                } 

                                                  Output:

                                                  Square root of 25 is: 5.0
                                                  

                                                  Explanation:

                                                  In the above code, we imported the built-in library ‘dart:math’. It provides the many built-in mathematical function, here we used the sqrt() function with number. It takes a number as an argument that we want to find its square root of. We passed an integer number 25 in sqrt() function, and it retuned an output as 5.

                                                  Encapsulation in Libraries

                                                  Dart provides the facility to encapsulate or restrict access the content of the dart library. It can be done by using the _(underscore), followed by the identifier. The _(underscore) symbol makes the library’s content completely private. The syntax is given below.

                                                  Syntax:

                                                  _identifier  

                                                  Example –

                                                  We define a library called Greetings that has a private function.

                                                  library Greetings;        
                                                  
                                                  // We define a function using the _underscore as a prefix.                        
                                                  
                                                  void _sayHi(msg) {  
                                                  
                                                     print("We will access this method in another program:${msg}");        
                                                  
                                                  }

                                                  The above file saves as greetings.dart, now we import the library.

                                                  import 'greetings.dart' as w;   
                                                  
                                                  void main() {   
                                                  
                                                     w._sayHi("Hello Javatpoint");   
                                                  
                                                  } 

                                                    Output:

                                                    After running the above code, it throws an error because we have declared the library with the private method and try to access it in other file.

                                                    Unhandled exception:
                                                    No top-level method 'w._sayHi' declared.
                                                    NoSuchMethodError: method not found: 'w._sayHi'
                                                    Receiver: top-level
                                                    Arguments: [...]
                                                    #0 NoSuchMethodError._throwNew (dart:core-patch/errors_patch.dart:184)
                                                    #1 main (file:///C:/Users/Administrator/WebstormProjects/untitled/Assertion.dart:6:3)
                                                    #2 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:261)
                                                    #3 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:148)
                                                    

                                                    Creating Custom Libraries (User-defined Library)

                                                    We can also use our own code as a library and import it when needed. This type of library is called a custom library. Below are the steps to create a custom library.

                                                    Step – 1: Declaring a Library

                                                    The library statement is used to create a library explicitly. The syntax is given below.

                                                    Syntax:

                                                    library library_name    
                                                    
                                                    // library contents go here   

                                                      Step – 2: Connecting a Library

                                                      We can connect a library in two ways.

                                                      • Within the same directory
                                                      import 'library_name'  
                                                      • From a different directory
                                                      import 'dir/library_name'  

                                                      Let’s understand the following example –

                                                      Example – Custom Library

                                                      library calculator_simple;    
                                                      
                                                      import 'dart:math';   
                                                      
                                                        
                                                      
                                                      //library content  
                                                      
                                                      int add(int num1,int num2){   
                                                      
                                                         print("inside add method of calculator_simple Library ") ;   
                                                      
                                                         return num1+num2;   
                                                      
                                                      }    
                                                      
                                                      int multiplication(int num1,int num2){   
                                                      
                                                         print("inside multiplication method of calculator_simple Library ") ;   
                                                      
                                                         return num1*num2;   
                                                      
                                                      }    
                                                      
                                                        
                                                      
                                                      int subtraction(int num1,int num2){   
                                                      
                                                         print("inside subtraction  method of calculator_simple Library ") ;   
                                                      
                                                         return num1-num2;   
                                                      
                                                      }    
                                                      
                                                        
                                                      
                                                      int modulus(int num1,int num2){   
                                                      
                                                         print("inside modulus  method of calculator_simple Library ") ;   
                                                      
                                                         return num1%num2;   
                                                      
                                                      }    

                                                        Now we import the above custom file in current file called ‘library.dart’.

                                                        import 'calculator.dart';    
                                                        
                                                        void main() {  
                                                        
                                                           var n1 = 30;   
                                                        
                                                           var n2 = 10;   
                                                        
                                                           var sum = add(n1,n2);   
                                                        
                                                           var mod = modulus(n1,n2);   
                                                        
                                                           var mul = multiplication(n1,n2);  
                                                        
                                                           var div = divide(n1,n2);  
                                                        
                                                           var sub = subtraction(n1,n2);  
                                                        
                                                             
                                                        
                                                             
                                                        
                                                           print("$n1 + $n2 = $sum");   
                                                        
                                                           print("$n1 %  $n2= $mod");   
                                                        
                                                           print("$n1 + $n2 = $mul");   
                                                        
                                                           print("$n1 - $n2 = $sub");  
                                                        
                                                             
                                                        
                                                        } 

                                                          Output:

                                                          inside add method of calculator_simple Library
                                                          inside modulus method of calculator_simple Library
                                                          inside multiplication method of calculator_simple Library
                                                          inside subtraction method of calculator_simple Library
                                                          30 + 10 = 40
                                                          30 % 10= 0
                                                          30 + 10 = 300
                                                          30 - 10 = 20
                                                          

                                                          Copy the above code and paste it into your dart editor and observe the result.

                                                          Note – The custom library must be imported by its saved file name such as we imported it in the current working file with the calculator_simple name.

                                                          Name Alias of Library

                                                          Dart allows us to import multiple libraries into the current working file, but if we create the same function name within the different libraries, it will create conflict while accessing these functions. The Dart compiler might be confused to identify the particular function in different library. To overcome this scenario, Dart provides the as keyword for specifying the prefix. The syntax is given below.

                                                          Syntax:

                                                          import 'library_uri' as prefix  

                                                          Let’s understand the following example –

                                                          Example –

                                                          First, we define a library: greeting.dart

                                                          library greetings;    
                                                          
                                                          void sayHi(msg){   
                                                          
                                                             print("Learn the Dart with ${msg}");  
                                                          
                                                          }

                                                          Next, we define the new library: hellogreetings.dart

                                                          library hellogreetings;   
                                                          
                                                          void sayHi(msg){   
                                                          
                                                             print("${msg} provides the tutorial on all technical retated topic");   
                                                          
                                                          }  

                                                            Now, we import the above libraries with the as prefix.

                                                            import 'greetings.dart';   
                                                            
                                                            import 'hellogreetings.dart' as gret;    
                                                            
                                                              
                                                            
                                                            // using as prefix avoids function name clashes   
                                                            
                                                            void main(){   
                                                            
                                                               sayHi("JavaTpoint");   
                                                            
                                                               gret.sayHi("JavaTpoint");   // To eliminate the name confliction  
                                                            
                                                            }

                                                            Output:

                                                            Learn the Dart with JavaTpoint
                                                            JavaTpoint provides the tutorial on all technical related topic
                                                            
                                                          1. Packages

                                                            Dart package is the collection of a well-organized, independent, and reusable code unit. Applications might be needed to implement third-party libraries or packages. The package generally contains a set of classes, functions, or unit of code for specific tasks along with the compiled program and sample data. Dart provides an extensive set of default packages that load automatically when the dart console starts. However, if we need packages other than the default packages then its need to installed and loaded explicitly in order to use. When a package is loaded, it can be used in the whole Dart environment.

                                                            Dart Package Manager

                                                            Every language provides the functionality for handling the external packages such as Nuget for .NET, Gradle or Maven for Java, npm for Node.js, etc. Dart has the inbuilt package manager, which is called a pub. It is basically used to organize, manage the third-party libraries, tools, dependencies, and also used to install the packages in the repository. Every Dart application consists of a pubspec.yaml file which includes the metadata of the file. The metadata of the package holds the author, version, application name, and description. The full form of the yaml is a Yet Another Markup Language. The pubspec.yaml is used to download the various libraries that application needs during programming. The pubspec.yaml file must look like as follows.

                                                            name: 'vector_victor'   
                                                            
                                                            version: 0.0.1   
                                                            
                                                            description: An absolute bare-bones web app.   
                                                            
                                                            ...   
                                                            
                                                            dependencies: browser: '>=0.10.0 <0.11.0'   

                                                              The Dart IDE’s provides the inbuilt support for using the pub that consist of creating, downloading, updating, and publishing packages, Otherwise we can use the pub command line. The following is the list of the few important pub commands.

                                                              Sr. NoDescription
                                                              pub getIt is used to get all packages of application dependent on.
                                                              pub upgradeIt is used to upgrade all application dependencies to the modern version.
                                                              pub buildIt is used to construct your web application, and it will create a build folder, with all related scripts in it.
                                                              pub helpIt is used to get help related to all pub commands or when we stuck while programming.

                                                              Installing a Package

                                                              The following steps are defining the installation of the package in the project.

                                                              Step – 1: Write the package name in the dependencies section of project’s pubspec.yaml file. Then run the below command to find the package installed in project.

                                                              pub get   

                                                              The above command will download the package under the packages folder in the application directory.

                                                              Example –

                                                              name: TestApp  
                                                              
                                                              version: 0.0.1  
                                                              
                                                              description: A simple dart application  
                                                              
                                                              dependencies:  
                                                              
                                                              xml:

                                                              We have added the xml to the project dependencies. Now we can use Dart XML package in the project by importing it. It can be imported as follows.

                                                              import 'package:xml/xml.dart' as xml;  

                                                              Read XML String

                                                              We can read XML string and authenticate the input; Dart XML provides a parse() method to read the string input. The syntax is given below.

                                                              xml. parse(String input):  

                                                              Let’s have a look at the following example:

                                                              Example – Parsing XML String Input

                                                              In the following example, we display the parsing XML string input.

                                                              import 'package:xml/xml.dart' as xml;   
                                                              
                                                              void main(){   
                                                              
                                                                 print("xml");   
                                                              
                                                                 var bookstoreXml = '''<?xml version = "1.0"?>   
                                                              
                                                                 <bookstore>   
                                                              
                                                                    <book>   
                                                              
                                                                       <title lang = "English">Who will cry when you die </title>   
                                                              
                                                                       <price>150.00</price>   
                                                              
                                                                    </book>   
                                                              
                                                                      
                                                              
                                                                    <book>   
                                                              
                                                                       <title lang = "English">The Alchemist </title>   
                                                              
                                                                       <price>90.00</price>   
                                                              
                                                                    </book>   
                                                              
                                                                    <price>200.00</price>   
                                                              
                                                                 </bookstore>''';   
                                                              
                                                                   
                                                              
                                                                 var document = xml.parse(bookstoreXml);   
                                                              
                                                                 print(document.toString());   
                                                              
                                                              } 

                                                                Output:

                                                                xml
                                                                
                                                                
                                                                
                                                                150.00
                                                                
                                                                
                                                                
                                                                
                                                                90.00
                                                                
                                                                200.00
                                                                
                                                                
                                                              1. Generics

                                                                Dart Generics are the same as the Dart collections, which are used to store the homogenous data. As we discussed in the Dart features, it is an optionally typed language.

                                                                By default, Dart Collections are the heterogeneous type. In other words, a single Dart collection can hold the values of several data types. However, a Dart collection can be also stored the homogenous values or same type values.

                                                                The Dart Generics provides the facility to enforce a limit on the data type of the values that can be stored by the collection. These collections can be referred to as the type-safe collections.

                                                                Type safety is a unique feature of the Dart programming, which makes sure that a memory block can only contain the data of a specific data type.

                                                                The generics are a way to support type-safety implementation for all Dart collections. The pair of the angular bracket is used to declare the type-safe collection. The angular bracket consists of the data-types of the collection. The syntax is given below.

                                                                Syntax –

                                                                Collection_name <data_type> identifier = new Collection_name<data_type>   

                                                                We can do the type-safe implementation of various Dart objects such as List, Queue, Map, and Set. It is also supported by all implementation of the above define collection types. The syntax is given below.

                                                                Example – Generics List

                                                                void main() {   
                                                                
                                                                   List <String> logStr = new List <String>();   
                                                                
                                                                   logStr.add("CHECK");   
                                                                
                                                                   logStr.add("ERROR");   
                                                                
                                                                   logStr.add("INFO");   
                                                                
                                                                    
                                                                
                                                                   //iterating across list   
                                                                
                                                                   for (String i in logStr) {   
                                                                
                                                                      print(i);   
                                                                
                                                                   }   
                                                                
                                                                } 

                                                                  Output

                                                                  CHECK
                                                                  ERROR
                                                                  INFO
                                                                  

                                                                  Explanation:

                                                                  We created a list that holds the string type-safe and used the add element into it by using add() function.

                                                                  If we try to insert the other than the specified value then it will through a compilation error. Let’s understand the following example –

                                                                  Example – 2

                                                                  void main() {   
                                                                  
                                                                     List <String> logStr = new List <String>();   
                                                                  
                                                                     logStr.add(511);   // Add integer value  
                                                                  
                                                                     logStr.add("ERROR");   
                                                                  
                                                                     logStr.add("INFO");   
                                                                  
                                                                      
                                                                  
                                                                     //iterating across list   
                                                                  
                                                                     for (String i in logTypes) {   
                                                                  
                                                                        print(i);   
                                                                  
                                                                     }   
                                                                  
                                                                  } 

                                                                    Output

                                                                    generics.dart:3:17: Error: The argument type 'int' can't be assigned to the parameter type 'String'.
                                                                    logTypes.add(511);
                                                                    

                                                                    Let’s understand another example –

                                                                    Example – Generic Set

                                                                    void main() {   
                                                                    
                                                                       Set <int>numberSet = new  Set<int>();   
                                                                    
                                                                       numberSet.add(10);   
                                                                    
                                                                       numberSet.add(20);   
                                                                    
                                                                       numberSet.add(30);   
                                                                    
                                                                       numberSet.add(40);  
                                                                    
                                                                       numberSet.add(50);   
                                                                    
                                                                         
                                                                    
                                                                       // numberSet.add("");   
                                                                    
                                                                      // compilation error;   
                                                                    
                                                                       print("Default implementation  :${numberSet.runtimeType}");    
                                                                    
                                                                         
                                                                    
                                                                       for(var i in numberSet) {   
                                                                    
                                                                          print(i);   
                                                                    
                                                                       }   
                                                                    
                                                                    } 

                                                                      Output

                                                                      10
                                                                      20
                                                                      30
                                                                      40
                                                                      50
                                                                      

                                                                      Example – Generics Queue

                                                                      import 'dart:collection';   
                                                                      
                                                                      void main() {   
                                                                      
                                                                         Queue<int> queue = new Queue<int>();   
                                                                      
                                                                         print("Default implementation ${queue.runtimeType}");    
                                                                      
                                                                         queue.addLast(100);   
                                                                      
                                                                         queue.addLast(205);   
                                                                      
                                                                         queue.addLast(315);   
                                                                      
                                                                         queue.addLast(470);   
                                                                      
                                                                         // Remove the first element of queue   
                                                                      
                                                                         queue.removeFirst();    
                                                                      
                                                                           
                                                                      
                                                                         for(int i in queue){   
                                                                      
                                                                            print(i);   
                                                                      
                                                                         }   
                                                                      
                                                                      } 

                                                                        Output

                                                                        Default implementation ListQueue<int>
                                                                        205
                                                                        315
                                                                        470
                                                                        

                                                                        Generic Map

                                                                        As we know that declaring map require the key and value. The syntax is given below.

                                                                        Syntax:

                                                                        Map <Key_type, value_type>  

                                                                        Example –

                                                                        void main() {   
                                                                        
                                                                           Map <String, String>m={'name':'Joseph','Rollno':'Std1001'};   
                                                                        
                                                                           print('Map :${m}');   
                                                                        
                                                                        }

                                                                        Output

                                                                        Map :{name: Joseph, Rollno: Std1001}