Dart Programming – Concurrency

Dart Programming – Concurrency ”; Previous Next Concurrency is the execution of several instruction sequences at the same time. It involves performing more than one task simultaneously. Dart uses Isolates as a tool for doing works in parallel. The dart:isolate package is Dart’s solution to taking single-threaded Dart code and allowing the application to make greater use of the hard-ware available. Isolates, as the name suggests, are isolated units of running code. The only way to send data between them is by passing messages, like the way you pass messages between the client and the server. An isolate helps the program to take advantage of multicore microprocessors out of the box. Example Let’s take an example to understand this concept better. Live Demo import ”dart:isolate”; void foo(var message){ print(”execution from foo … the message is :${message}”); } void main(){ Isolate.spawn(foo,”Hello!!”); Isolate.spawn(foo,”Greetings!!”); Isolate.spawn(foo,”Welcome!!”); print(”execution from main1”); print(”execution from main2”); print(”execution from main3”); } Here, the spawn method of the Isolate class facilitates running a function, foo, in parallel with the rest of our code. The spawn function takes two parameters − the function to be spawned, and an object that will be passed to the spawned function. In case there is no object to pass to the spawned function, it can be passed a NULL value. The two functions (foo and main) might not necessarily run in the same order each time. There is no guarantee as to when foo will be executing and when main() will be executing. The output will be different each time you run. Output 1 execution from main1 execution from main2 execution from main3 execution from foo … the message is :Hello!! Output 2 execution from main1 execution from main2 execution from main3 execution from foo … the message is :Welcome!! execution from foo … the message is :Hello!! execution from foo … the message is :Greetings!! From the outputs, we can conclude that the Dart code can spawn a new isolate from running code like the way Java or C# code can start a new thread. Isolates differ from threads in that an isolate has its own memory. There’s no way to share a variable between isolates—the only way to communicate between isolates is via message passing. Note − The above output will be different for different hardware and operating system configurations. Isolate v/s Future Doing complex computational work asynchronously is important to ensure responsiveness of applications. Dart Future is a mechanism for retrieving the value of an asynchronous task after it has completed, while Dart Isolates are a tool for abstracting parallelism and implementing it on a practical high-level basis. Print Page Previous Next Advertisements ”;

Dart Programming – Packages

Dart Programming – Packages ”; Previous Next A package is a mechanism to encapsulate a group of programming units. Applications might at times need integration of some third-party libraries or plugins. Every language has a mechanism for managing external packages like Maven or Gradle for Java, Nuget for .NET, npm for Node.js, etc. The package manager for Dart is pub. Pub helps to install packages in the repository. The repository of packages hosted can be found at https://pub.dartlang.org/. The package metadata is defined in a file, pubsec.yaml. YAML is the acronym for Yet Another Markup Language. The pub tool can be used to download all various libraries that an application requires. Every Dart application has a pubspec.yaml file which contains the application dependencies to other libraries and metadata of applications like application name, author, version, and description. The contents of a pubspec.yaml file should look something like this − name: ”vector_victor” version: 0.0.1 description: An absolute bare-bones web app. … dependencies: browser: ”>=0.10.0 <0.11.0” The important pub commands are as follows − Sr.No Command & Description 1 ‘pub get’ Helps to get all packages your application is depending on. 2 ‘pub upgrade’ Upgrades all your dependencies to a newer version. 3 ‘pub build’ This s used for building your web application and it will create a build folder , with all related scripts in it. 4 ‘pub help’ This will give you help for all different pub commands. If you are using an IDE like WebStorm, then you can right-click on the pubspec.yaml to get all the commands directly − Installing a Package Consider an example where an application needs to parse xml. Dart XML is a lightweight library that is open source and stable for parsing, traversing, querying and building XML documents. The steps for achieving the said task is as follows − Step 1 − Add the following to the pubsec.yaml file. name: TestApp version: 0.0.1 description: A simple console application. #dependencies: # foo_bar: ”>=1.0.0 <2.0.0” dependencies: https://mail.google.com/mail/u/0/images/cleardot.gif xml: Right-click on the pubsec.yaml and get dependencies. This will internally fire the pub get command as shown below. The downloaded packages and its dependent packages can be verified under the packages folder. Since installation is completed now, we need to refer the dart xml in the project. The syntax is as follows − import ”package:xml/xml.dart” as xml; Read XML String To read XML string and verify the input, Dart XML uses a parse() method. The syntax is as follows − xml.parse(String input): Example : Parsing XML String Input The following example shows how to parse XML string input − import ”package:xml/xml.dart” as xml; void main(){ print(“xml”); var bookshelfXml = ”””<?xml version = “1.0”?> <bookshelf> <book> <title lang = “english”>Growing a Language</title> <price>29.99</price> </book> <book> <title lang = “english”>Learning XML</title> <price>39.95</price> </book> <price>132.00</price> </bookshelf>”””; var document = xml.parse(bookshelfXml); print(document.toString()); } It should produce the following output − xml <?xml version = “1.0”?><bookshelf> <book> <title lang = “english”>Growing a Language</title> <price>29.99</price> </book> <book> <title lang = “english”>Learning XML</title> <price>39.95</price> </book> <price>132.00</price> </bookshelf> Print Page Previous Next Advertisements ”;

Dart Programming – Discussion

Discuss Dart Programming ”; Previous Next Dart is an open-source general-purpose programming language. It is originally developed by Google and later approved as a standard by ECMA. Dart is a new programming language meant for the server as well as the browser. Introduced by Google, the Dart SDK ships with its compiler – the Dart VM. The SDK also includes a utility -dart2js, a transpiler that generates JavaScript equivalent of a Dart Script. This tutorial provides a basic level understanding of the Dart programming language. Print Page Previous Next Advertisements ”;

Dart Programming – Quick Guide

Dart Programming – Quick Guide ”; Previous Next Dart Programming – Overview Dart is an object-oriented language with C-style syntax which can optionally trans compile into JavaScript. It supports a varied range of programming aids like interfaces, classes, collections, generics, and optional typing. Dart can be extensively used to create single-page applications. Single-page applications apply only to websites and web applications. Single-page applications enable navigation between different screens of the website without loading a different webpage in the browser. A classic example is GMail ─ when you click on a message in your inbox, browser stays on the same webpage, but JavaScript code hides the inbox and brings the message body on screen. Google has released a special build of Chromium – the Dart VM. Using Dartium means you don’t have to compile your code to JavaScript until you’re ready to test on other browsers. The following table compares the features of Dart and JavaScript. Feature Dart JavaScript Type system Optional, dynamic Weak, dynamic Classes Yes, single inheritance Prototypical Interfaces Yes, multiple interfaces No Concurrency Yes, with isolates Yes, with HTML5 web workers This tutorial provides a basic level understanding of the Dart programming language. Dart Programming – Environment This chapter discusses setting up the execution environment for Dart on the Windows platform. Executing Script Online with DartPad You may test your scripts online by using the online editor at https://dartpad.dev/. The Dart Editor executes the script and displays both HTML as well as console output. The online editor is shipped with a set of preset code samples. A screenshot of the Dartpad editor is given below − Dartpad also enables to code in a more restrictive fashion. This can be achieved by checking the Strong mode option on the bottom right of the editor. Strong mode helps with − Stronger static and dynamic checking Idiomatic JavaScript code generation for better interoperability. You may try the following example using Dartpad Live Demo void main() { print(”hello world”); } The code will display the following output hello world Setting Up the Local Environment In this section, let us see how to set up the local environment. Using the Text Editor Examples of a few editors include Windows Notepad, Notepad++, Emacs, vim or vi, etc. Editors may vary from one Operating System to another. The source files are typically named with the extension “.dart”. Installing the Dart SDK The current stable version of Dart is 1.21.0. The dart sdk can be downloaded from − https://www.dartlang.org/install/archive http://www.gekorm.com/dart-windows/ A screenshot of the Dart SDK installation is given below − On completion of the SDK installation, set the PATH environment variable to − <dart-sdk-path>bin Verifying the Installation To verify if Dart has been successfully installed, open the command prompt and enter the following command − Dart If installation is successful, it will show the dart runtime. IDE Support A plethora of IDEs support scripting in Dart. Examples include Eclipse, IntelliJ, and WebStorm from Jet brains. Given below are the steps for configuring the Dart environment using WebStrom IDE. Installing WebStorm The installation file for WebStorm can be downloaded from https://www.jetbrains.com/webstorm/download/#section=windows-version. The WebStorm installation file is available for Mac OS, Windows and Linux. After downloading the installation files, follow the steps given below − Install the Dart SDK: Refer to the steps listed above Create a new Dart project and configure Dart support To create a new Dart project, Click Create New Project from the Welcome Screen In the next dialog box, click Dart If there is no value specified for the Dart SDK path, then provide the SDK path. For example, the SDK path may be <dart installation directory>/dart/dartsdk. Add a Dart File to the Project To add a Dart file to the Project − Right-click on the Project New → Dart File Enter the name of the Dart Script A screenshot of the WebStorm Editor is given below − The dart2js Tool The dart2js tool compiles Dart code to JavaScript. Compiling Dart code to JS enables running the Dart script on browsers that do not support the Dart VM. The dart2js tool is shipped as a part of the Dart SDK and can be found in the /dartsdk/bin folder. To compile Dart to JavaScript, type the following command in the terminal dart2js – – out = <output_file>.js <dart_script>.dart This command produces a file that contains the JavaScript equivalent of your Dart code. A complete tutorial on using this utility can be found on the official Dart website. Dart Programming – Syntax Syntax defines a set of rules for writing programs. Every language specification defines its own syntax. A Dart program is composed of − Variables and Operators Classes Functions Expressions and Programming Constructs Decision Making and Looping Constructs Comments Libraries and Packages Typedefs Data structures represented as Collections / Generics Your First Dart Code Let us start with the traditional “Hello World” example − Live Demo main() { print(“Hello World!”); } The main() function is a predefined method in Dart. This method acts as the entry point to the application. A Dart script needs the main() method for execution. print() is a predefined function that prints the specified string or value to the standard output i.e. the terminal. The output of the above code will be − Hello World! Execute a Dart Program You can execute a Dart program in two ways − Via the terminal Via the WebStorm IDE Via the Terminal To execute a Dart program via the terminal − Navigate to the path of the current project Type the following command in the Terminal window dart file_name.dart Via the WebStorm IDE To execute a Dart program via the WebStorm IDE − Right-click the Dart script file on the IDE. (The file should contain the main() function to enable execution) Click on the ‘Run <file_name>’ option. A screenshot of the same is given below − One can alternatively click the button or use the shortcut Ctrl+Shift+F10 to execute the Dart Script. Dart Command-Line Options Dart command-line options are

Dart Programming – HTML DOM

Dart Programming – HTML DOM ”; Previous Next Every webpage resides inside a browser window which can be considered as an object. A Document object represents the HTML document that is displayed in that window. The Document object has various properties that refer to other objects which allow access to and modification of document content. The way a document content is accessed and modified is called the Document Object Model, or DOM. The Objects are organized in a hierarchy. This hierarchical structure applies to the organization of objects in a Web document. Window − Top of the hierarchy. It is the outmost element of the object hierarchy. Document − Each HTML document that gets loaded into a window becomes a document object. The document contains the contents of the page. Elements − represent the content on a web page. Examples include the text boxes, page title etc. Nodes − are often elements, but they can also be attributes, text, comments, and other DOM types. Here is a simple hierarchy of a few important DOM objects − Dart provides the dart:html library to manipulate objects and elements in the DOM. Console-based applications cannot use the dart:html library. To use the HTML library in the web applications, import dart:html − import ”dart:html”; Moving on, we will discuss some DOM Operations in the next section. Finding DOM Elements The dart:html library provides the querySelector function to search for elements in the DOM. Element querySelector(String selectors); The querySelector() function returns the first element that matches the specified group of selectors. “selectors should be string using CSS selector syntax as given below var element1 = document.querySelector(”.className”); var element2 = document.querySelector(”#id”); Example: Manipulating DOM Follow the steps given below, in the Webstorm IDE − Step 1 − File NewProject → In the location, provide the project name as DemoWebApp. Step 1 − In the section “Generate sample content”, select SimpleWebApplication. It will create a sample project, DemoWebApp. There is a pubspec.yaml file containing the dependencies which need to be downloaded. name: ”DemoWebApp” version: 0.0.1 description: An absolute bare-bones web app. #author: Your Name <[email protected]> #homepage: https://www.example.com environment: sdk: ”>=1.0.0 <2.0.0” dependencies: browser: ”>=0.10.0 <0.11.0” dart_to_js_script_rewriter: ”^1.0.1” transformers: – dart_to_js_script_rewriter If you are connected to Web, then these will be downloaded automatically, else you can right-click on the pubspec.yaml and get dependencies. In the web folder, you will find three files: Index.html, main.dart, and style.css Index.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 = “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!!!.”; } Run the index.html file; you will see the following output on your screen. 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> </body> </html> 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; } Output Print Page Previous Next Advertisements ”;

Dart Programming – Generics

Dart Programming – Generics ”; Previous Next Dart is an optionally typed language. Collections in Dart are heterogeneous by default. In other words, a single Dart collection can host values of various types. However, a Dart collection can be made to hold homogenous values. The concept of Generics can be used to achieve the same. The use of Generics enforces a restriction on the data type of the values that can be contained by the collection. Such collections are termed as type-safe collections. Type safety is a programming feature which ensures that a memory block can only contain data of a specific data type. All Dart collections support type-safety implementation via generics. A pair of angular brackets containing the data type is used to declare a type-safe collection. The syntax for declaring a type-safe collection is as given below. Syntax Collection_name <data_type> identifier= new Collection_name<data_type> The type-safe implementations of List, Map, Set and Queue is given below. This feature is also supported by all implementations of the above-mentioned collection types. Example: Generic List Live Demo void main() { List <String> logTypes = new List <String>(); logTypes.add(“WARNING”); logTypes.add(“ERROR”); logTypes.add(“INFO”); // iterating across list for (String type in logTypes) { print(type); } } It should produce the following output − WARNING ERROR INFO An attempt to insert a value other than the specified type will result in a compilation error. The following example illustrates this. Example Live Demo void main() { List <String> logTypes = new List <String>(); logTypes.add(1); logTypes.add(“ERROR”); logTypes.add(“INFO”); //iterating across list for (String type in logTypes) { print(type); } } It should produce the following output − 1 ERROR INFO Example: Generic Set Live Demo void main() { Set <int>numberSet = new Set<int>(); numberSet.add(100); numberSet.add(20); numberSet.add(5); numberSet.add(60); numberSet.add(70); // numberSet.add(“Tom”); compilation error; print(“Default implementation :${numberSet.runtimeType}”); for(var no in numberSet) { print(no); } } It should produce the following output − Default implementation :_CompactLinkedHashSet<int> 100 20 5 60 70 Example: Generic Queue Live Demo import ”dart:collection”; void main() { Queue<int> queue = new Queue<int>(); print(“Default implementation ${queue.runtimeType}”); queue.addLast(10); queue.addLast(20); queue.addLast(30); queue.addLast(40); queue.removeFirst(); for(int no in queue){ print(no); } } It should produce the following output − Default implementation ListQueue<int> 20 30 40 Generic Map A type-safe map declaration specifies the data types of − The key The value Syntax Map <Key_type, value_type> Example Live Demo void main() { Map <String,String>m={”name”:”Tom”,”Id”:”E1001”}; print(”Map :${m}”); } It should produce the following output − Map :{name: Tom, Id: E1001} Print Page Previous Next Advertisements ”;

Dart Programming – Typedef

Dart Programming – Typedef ”; Previous Next A typedef, or a function-type alias, helps to define pointers to executable code within memory. Simply put, a typedef can be used as a pointer that references a function. Given below are the steps to implement typedefs in a Dart program. Step 1: Defining a typedef A typedef can be used to specify a function signature that we want specific functions to match. A function signature is defined by a function’s parameters (including their types). The return type is not a part of the function signature. Its syntax is as follows. typedef function_name(parameters) Step 2: Assigning a Function to a typedef Variable A variable of typedef can point to any function having the same signature as typedef. You can use the following signature to assign a function to a typedef variable. type_def var_name = function_name Step 3: Invoking a Function The typedef variable can be used to invoke functions. Here is how you can invoke a function − var_name(parameters) Example Let’s now take an example to understand more on typedef in Dart. At first, let us define a typedef. Here we are defining a function signature. The function will take two input parameters of the type integer. Return type is not a part of the function signature. typedef ManyOperation(int firstNo , int secondNo); //function signature Next, let us define the functions. Define some functions with the same function signature as that of the ManyOperation typedef. Add(int firstNo,int second){ print(“Add result is ${firstNo+second}”); } Subtract(int firstNo,int second){ print(“Subtract result is ${firstNo-second}”); } Divide(int firstNo,int second){ print(“Add result is ${firstNo/second}”); } Finally, we will invoke the function via typedef. Declare a variable of the ManyOperations type. Assign the function name to the declared variable. ManyOperation oper ; //can point to any method of same signature oper = Add; oper(10,20); oper = Subtract; oper(30,20); oper = Divide; oper(50,5); The oper variable can point to any method which takes two integer parameters. The Add function”s reference is assigned to the variable. Typedefs can switch function references at runtime Let us now put all the parts together and see the complete program. Live Demo typedef ManyOperation(int firstNo , int secondNo); //function signature Add(int firstNo,int second){ print(“Add result is ${firstNo+second}”); } Subtract(int firstNo,int second){ print(“Subtract result is ${firstNo-second}”); } Divide(int firstNo,int second){ print(“Divide result is ${firstNo/second}”); } Calculator(int a, int b, ManyOperation oper){ print(“Inside calculator”); oper(a,b); } void main(){ ManyOperation oper = Add; oper(10,20); oper = Subtract; oper(30,20); oper = Divide; oper(50,5); } The program should produce the following output − Add result is 30 Subtract result is 10 Divide result is 10.0 Note − The above code will result in an error if the typedef variable tries to point to a function with a different function signature. Example Typedefs can also be passed as a parameter to a function. Consider the following example − Live Demo typedef ManyOperation(int firstNo , int secondNo); //function signature Add(int firstNo,int second){ print(“Add result is ${firstNo+second}”); } Subtract(int firstNo,int second){ print(“Subtract result is ${firstNo-second}”); } Divide(int firstNo,int second){ print(“Divide result is ${firstNo/second}”); } Calculator(int a,int b ,ManyOperation oper){ print(“Inside calculator”); oper(a,b); } main(){ Calculator(5,5,Add); Calculator(5,5,Subtract); Calculator(5,5,Divide); } It will produce the following output − Inside calculator Add result is 10 Inside calculator Subtract result is 0 Inside calculator Divide result is 1.0 Print Page Previous Next Advertisements ”;

Dart Programming – Object

Dart Programming – Object ”; Previous Next Object-Oriented Programming defines an object as “any entity that has a defined boundary.” An object has the following − State − Describes the object. The fields of a class represent the object’s state. Behavior − Describes what an object can do. Identity − A unique value that distinguishes an object from a set of similar other objects. Two or more objects can share the state and behavior but not the identity. The period operator (.) is used in conjunction with the object to access a class’ data members. Example Dart represents data in the form of objects. Every class in Dart extends the Object class. Given below is a simple example of creating and using an object. Live Demo class Student { void test_method() { print(“This is a test method”); } void test_method1() { print(“This is a test method1”); } } void main() { Student s1 = new Student(); s1.test_method(); s1.test_method1(); } It should produce the following output − This is a test method This is a test method1 The Cascade operator (..) The above example invokes the methods in the class. However, every time a function is called, a reference to the object is required. The cascade operator can be used as a shorthand in cases where there is a sequence of invocations. The cascade ( .. ) operator can be used to issue a sequence of calls via an object. The above example can be rewritten in the following manner. Live Demo class Student { void test_method() { print(“This is a test method”); } void test_method1() { print(“This is a test method1″); } } void main() { new Student() ..test_method() ..test_method1(); } It should produce the following output − This is a test method This is a test method1 The toString() method This function returns a string representation of an object. Take a look at the following example to understand how to use the toString method. Live Demo void main() { int n = 12; print(n.toString()); } It should produce the following output − 12 Print Page Previous Next Advertisements ”;

Dart Programming – Resources

Dart Programming – Useful Resources ”; Previous Next The following resources contain additional information on Dart Programming. Please use them to get more in-depth knowledge on this topic. Useful Video Courses Dart Course for Beginners 45 Lectures 4.5 hours Sriyank Siddhartha More Detail Flutter With Dart: Course For Beginners 35 Lectures 4 hours Sriyank Siddhartha More Detail COMPLETE Google DART Programming- BOOTCAMP 23 Lectures 1.5 hours Pranjal Srivastava More Detail AWS Mobile with Google Dart 35 Lectures 3 hours Pranjal Srivastava More Detail Understand Concepts of DART Programming quickly and easily! 38 Lectures 5 hours Frahaan Hussain More Detail Job ready Flutter complete course with Firebase and Dart 86 Lectures 17 hours Rahul Agarwal More Detail Print Page Previous Next Advertisements ”;

Dart Programming – Unit Testing

Dart Programming – Unit Testing ”; Previous Next Unit Testing involves testing every individual unit of an application. It helps the developer to test small functionalities without running the entire complex application. The Dart external library named “test” provides a standard way of writing and running unit tests. Dart unit testing involves the following steps − Step 1: Installing the “test” package To installing third-party packages in the current project, you will require the pubspec.yaml file. To install test packages, first make the following entry in the pubspec.yaml file − dependencies: test: After making the entry, right-click the pubspec.yaml file and get dependencies. It will install the “test” package. Given below is a screenshot for the same in the WebStorm Editor. Packages can be installed from the command line too. Type the following in the terminal − pub get Step 2: Importing the “test” package import “package:test/test.dart”; Step 3 Writing Tests Tests are specified using the top-level function test(), while test assertions are made using the expect() function. For using these methods, they should be installed as a pub dependency. Syntax test(“Description of the test “, () { expect(actualValue , matchingValue) }); The group() function can be used to group tests. Each group”s description is added to the beginning of its test”s descriptions. Syntax group(“some_Group_Name”, () { test(“test_name_1”, () { expect(actual, equals(exptected)); }); test(“test_name_2″, () { expect(actual, equals(expected)); }); }) Example 1: A Passing Test The following example defines a method Add(). This method takes two integer values and returns an integer representing the sum. To test this add() method − Step 1 − Import the test package as given below. Step 2 − Define the test using the test() function. Here, the test() function uses the expect() function to enforce an assertion. import ”package:test/test.dart”; // Import the test package int Add(int x,int y) // Function to be tested { return x+y; } void main() { // Define the test test(“test to check add method”,(){ // Arrange var expected = 30; // Act var actual = Add(10,20); // Asset expect(actual,expected); }); } It should produce the following output − 00:00 +0: test to check add method 00:00 +1: All tests passed! Example 2: A Failing Test The subtract() method defined below has a logical mistake. The following test verifies the same. 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 − The test case for the function add() passes but the test for subtract() fails as shown below. 00:00 +0: test to check sub 00:00 +0 -1: test to check sub Expected: <10> Actual: <9> package:test expect binTest123.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) Grouping Test Cases You can group the test cases so that it adds more meaning to you test code. If you have many test cases this helps to write much cleaner code. In the given code, we are writing a test case for the split() function and the trim function. Hence, we logically group these test cases and call it String. Example import “package:test/test.dart”; void main() { group(“String”, () { test(“test on split() method of string class”, () { var string = “foo,bar,baz”; expect(string.split(“,”), equals([“foo”, “bar”, “baz”])); }); test(“test on trim() method of string class”, () { var string = ” foo “; expect(string.trim(), equals(“foo”)); }); }); } Output − The output will append the group name for each test case as given below − 00:00 +0: String test on split() method of string class 00:00 +1: String test on trim() method of string class 00:00 +2: All tests passed Print Page Previous Next Advertisements ”;