Dart Programming – String

Dart Programming – String ”; Previous Next The String data type represents a sequence of characters. A Dart string is a sequence of UTF 16 code units. String values in Dart can be represented using either single or double or triple quotes. Single line strings are represented using single or double quotes. Triple quotes are used to represent multi-line strings. The syntax of representing string values in Dart is as given below − Syntax String variable_name = ”value” OR String variable_name = ””value”” OR String variable_name = ”””line1 line2””” OR String variable_name= ””””””line1 line2”””””” The following example illustrates the use of String data type in Dart. Live Demo void main() { String str1 = ”this is a single line string”; String str2 = “this is a single line string”; String str3 = ”””this is a multiline line string”””; String str4 = “””this is a multiline line string”””; print(str1); print(str2); print(str3); print(str4); } It will produce the following Output − this is a single line string this is a single line string this is a multiline line string this is a multiline line string Strings are immutable. However, strings can be subjected to various operations and the resultant string can be a stored as a new value. String Interpolation The process of creating a new string by appending a value to a static string is termed as concatenation or interpolation. In other words, it is the process of adding a string to another string. The operator plus (+) is a commonly used mechanism to concatenate / interpolate strings. Example 1 Live Demo void main() { String str1 = “hello”; String str2 = “world”; String res = str1+str2; print(“The concatenated string : ${res}”); } It will produce the following output − The concatenated string : Helloworld Example 2 You can use “${}” can be used to interpolate the value of a Dart expression within strings. The following example illustrates the same. Live Demo void main() { int n=1+1; String str1 = “The sum of 1 and 1 is ${n}”; print(str1); String str2 = “The sum of 2 and 2 is ${2+2}”; print(str2); } It will produce the following output − The sum of 1 and 1 is 2 The sum of 2 and 2 is 4 String Properties The properties listed in the following table are all read-only. Sr.No Property & Description 1 codeUnits Returns an unmodifiable list of the UTF-16 code units of this string. 2 isEmpty Returns true if this string is empty. 3 Length Returns the length of the string including space, tab and newline characters. Methods to Manipulate Strings The String class in the dart: core library also provides methods to manipulate strings. Some of these methods are given below − Sr.No Methods & Description 1 toLowerCase() Converts all characters in this string to lower case. 2 toUpperCase() Converts all characters in this string to upper case. 3 trim() Returns the string without any leading and trailing whitespace. 4 compareTo() Compares this object to another. 5 replaceAll() Replaces all substrings that match the specified pattern with a given value. 6 split() Splits the string at matches of the specified delimiter and returns a list of substrings. 7 substring() Returns the substring of this string that extends from startIndex, inclusive, to endIndex, exclusive. 8 toString() Returns a string representation of this object. 9 codeUnitAt() Returns the 16-bit UTF-16 code unit at the given index. Print Page Previous Next Advertisements ”;

Dart Programming – Lists

Dart Programming – Lists ”; Previous Next A very commonly used collection in programming is an array. Dart represents arrays in the form of List objects. A List is simply an ordered group of objects. The dart:core library provides the List class that enables creation and manipulation of lists. The logical representation of a list in Dart is given below − test_list − is the identifier that references the collection. The list contains in it the values 12, 13, and 14. The memory blocks holding these values are known as elements. Each element in the List is identified by a unique number called the index. The index starts from zero and extends up to n-1 where n is the total number of elements in the List. The index is also referred to as the subscript. Lists can be classified as − Fixed Length List Growable List Let us now discuss these two types of lists in detail. Fixed Length List A fixed length list’s length cannot change at runtime. The syntax for creating a fixed length list is as given below − Step 1 − Declaring a list The syntax for declaring a fixed length list is given below − var list_name = new List(initial_size) The above syntax creates a list of the specified size. The list cannot grow or shrink at runtime. Any attempt to resize the list will result in an exception. Step 2 − Initializing a list The syntax for initializing a list is as given below − lst_name[index] = value; Example Live Demo void main() { var lst = new List(3); lst[0] = 12; lst[1] = 13; lst[2] = 11; print(lst); } It will produce the following output − [12, 13, 11] Growable List A growable list’s length can change at run-time. The syntax for declaring and initializing a growable list is as given below − Step 1 − Declaring a List var list_name = [val1,val2,val3] — creates a list containing the specified values OR var list_name = new List() — creates a list of size zero Step 2 − Initializing a List The index / subscript is used to reference the element that should be populated with a value. The syntax for initializing a list is as given below − list_name[index] = value; Example The following example shows how to create a list of 3 elements. Live Demo void main() { var num_list = [1,2,3]; print(num_list); } It will produce the following output − [1, 2, 3] Example The following example creates a zero-length list using the empty List() constructor. The add() function in the List class is used to dynamically add elements to the list. Live Demo void main() { var lst = new List(); lst.add(12); lst.add(13); print(lst); } It will produce the following output − [12, 13] List Properties The following table lists some commonly used properties of the List class in the dart:core library. Sr.No Methods & Description 1 first Returns the first element in the list. 2 isEmpty Returns true if the collection has no elements. 3 isNotEmpty Returns true if the collection has at least one element. 4 length Returns the size of the list. 5 last Returns the last element in the list. 6 reversed Returns an iterable object containing the lists values in the reverse order. 7 Single Checks if the list has only one element and returns it. 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 ”;

Dart Programming – Exceptions

Dart Programming – Exceptions ”; Previous Next An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally. Built-in Dart exceptions include − Sr.No Exceptions & Description 1 DeferredLoadException Thrown when a deferred library fails to load. 2 FormatException Exception thrown when a string or some other data does not have an expected format and cannot be parsed or processed. 3 IntegerDivisionByZeroException Thrown when a number is divided by zero. 4 IOException Base class for all Inupt-Output related exceptions. 5 IsolateSpawnException Thrown when an isolate cannot be created. 6 Timeout Thrown when a scheduled timeout happens while waiting for an async result. Every exception in Dart is a subtype of the pre-defined class Exception. Exceptions must be handled to prevent the application from terminating abruptly. The try / on / catch Blocks The try block embeds code that might possibly result in an exception. The on block is used when the exception type needs to be specified. The catch block is used when the handler needs the exception object. The try block must be followed by either exactly one on / catch block or one finally block (or one of both). When an exception occurs in the try block, the control is transferred to the catch. The syntax for handling an exception is as given below − try { // code that might throw an exception } on Exception1 { // code for handling exception } catch Exception2 { // code for handling exception } Following are some points to remember − A code snippet can have more than one on / catch blocks to handle multiple exceptions. The on block and the catch block are mutually inclusive, i.e. a try block can be associated with both- the on block and the catch block. The following code illustrates exception handling in Dart − Example: Using the ON Block The following program divides two numbers represented by the variables x and y respectively. The code throws an exception since it attempts division by zero. The on block contains the code to handle this exception. Live Demo main() { int x = 12; int y = 0; int res; try { res = x ~/ y; } on IntegerDivisionByZeroException { print(”Cannot divide by zero”); } } It should produce the following output − Cannot divide by zero Example: Using the catch Block In the following example, we have used the same code as above. The only difference is that the catch block (instead of the ON block) here contains the code to handle the exception. The parameter of catch contains the exception object thrown at runtime. Live Demo main() { int x = 12; int y = 0; int res; try { res = x ~/ y; } catch(e) { print(e); } } It should produce the following output − IntegerDivisionByZeroException Example: on…catch The following example shows how to use the on…catch block. Live Demo main() { int x = 12; int y = 0; int res; try { res = x ~/ y; } on IntegerDivisionByZeroException catch(e) { print(e); } } It should produce the following output − IntegerDivisionByZeroException The Finally Block The finally block includes code that should be executed irrespective of an exception’s occurrence. The optional finally block executes unconditionally after try/on/catch. The syntax for using the finally block is as follows − try { // code that might throw an exception } on Exception1 { // exception handling code } catch Exception2 { // exception handling } finally { // code that should always execute; irrespective of the exception } The following example illustrates the use of finally block. Live Demo main() { int x = 12; int y = 0; int res; try { res = x ~/ y; } on IntegerDivisionByZeroException { print(”Cannot divide by zero”); } finally { print(”Finally block executed”); } } It should produce the following output − Cannot divide by zero Finally block executed Throwing an Exception The throw keyword is used to explicitly raise an exception. A raised exception should be handled to prevent the program from exiting abruptly. The syntax for raising an exception explicitly is − throw new Exception_name() Example The following example shows how to use the throw keyword to throw an exception − Live Demo main() { try { test_age(-2); } catch(e) { print(”Age cannot be negative”); } } void test_age(int age) { if(age<0) { throw new FormatException(); } } It should produce the following output − Age cannot be negative Custom Exceptions As specified above, every exception type in Dart is a subtype of the built-in class Exception. Dart enables creating custom exceptions by extending the existing ones. The syntax for defining a custom exception is as given below − Syntax: Defining the Exception class Custom_exception_Name implements Exception { // can contain constructors, variables and methods } Custom Exceptions should be raised explicitly and the same should be handled in the code. Example The following example shows how to define and handle a custom exception. Live Demo class AmtException implements Exception { String errMsg() => ”Amount should be greater than zero”; } void main() { try { withdraw_amt(-1); } catch(e) { print(e.errMsg()); } finally { print(”Ending requested operation…..”); } } void withdraw_amt(int amt) { if (amt <= 0) { throw new AmtException(); } } In the above code, we are defining a custom exception, AmtException. The code raises the exception if the amount passed is not within the excepted range. The main function encloses the function invocation in the try…catch block. The code should produce the following output − Amount should be greater than zero Ending requested operation…. Print Page Previous Next Advertisements ”;

Dart Programming – Debugging

Dart Programming – Debugging ”; Previous Next Every now and then, developers commit mistakes while coding. A mistake in a program is referred to as a bug. The process of finding and fixing bugs is called debugging and is a normal part of the development process. This section covers tools and techniques that can help you with debugging tasks. The WebStorm editor enables breakpoints and step-by-step debugging. The program will break at the point where the breakpoint is attached. This functionality is like what you might expect from Java or C# application development. You can watch variables, browse the stack, step over and step into method and function calls, all from the WebStorm Editor. Adding a Breakpoint Consider the following code snippet. (TestString.dart) Live Demo void main() { int a = 10, b = 20, c = 5; c = c * c * c; print(“$a + $b = ${a+b}”); print(“$a%$b = ${a%b}”); // Add a break point here print(“$a*$b = ${a*b}”); print(“$a/$b = ${a/b}”); print(c); } To add a breakpoint, click on the left margin to. In the figure given below, line number 7 has a break point. Run the program in debug mode. In the project explorer right click on the dart program in our case TestString.dart. Once the program runs in debug mode, you will get the Debugger window as shown in the following screenshot. The variables tab shows the values of variables in the current context. You can add watchers for specific variables and listen to that values changes using watches window. Step Into (F7) arrow icon on debug menu helps to Executes code one statement at a time. If main methods call a subroutine, then this will go into the subroutine code also. Step over (F8): It is similar to Step Into. The difference in use occurs when the current statement contains a call to a subroutine. If the main method calls a subroutine, step over will not drill into the subroutine. it will skip the subroutine. Step Out (Shift+F8): Executes the remaining lines of a function in which the current execution point lies. The next statement displayed is the statement following the subroutine call. After running in debug mode, the program gives the following output − 10 + 20 = 30 10 % 20 = 10 10 * 20 = 200 10 / 20 = 0.5 125 Print Page Previous Next Advertisements ”;

Dart Programming – Decision Making

Dart Programming – Decision Making ”; Previous Next A conditional/decision-making construct evaluates a condition before the instructions are executed. Conditional constructs in Dart are classified in the following table. Sr.No Statement & Description 1 if statement An if statement consists of a Boolean expression followed by one or more statements. 2 If…Else Statement An if can be followed by an optional else block. The else block will execute if the Boolean expression tested by the if block evaluates to false. 3 else…if Ladder The else…if ladder is useful to test multiple conditions. Following is the syntax of the same. 4 switch…case Statement The switch statement evaluates an expression, matches the expression’s value to a case clause and executes the statements associated with that case. Print Page Previous Next Advertisements ”;

Dart Programming – Classes

Dart Programming – Classes ”; Previous Next Dart is an object-oriented language. It supports object-oriented programming features like classes, interfaces, etc. A class in terms of OOP is a blueprint for creating objects. A class encapsulates data for the object. Dart gives built-in support for this concept called class. Declaring a Class Use the class keyword to declare a class in Dart. A class definition starts with the keyword class followed by the class name; and the class body enclosed by a pair of curly braces. The syntax for the same is given below − Syntax class class_name { <fields> <getters/setters> <constructors> <functions> } The class keyword is followed by the class name. The rules for identifiers must be considered while naming a class. A class definition can include the following − Fields − A field is any variable declared in a class. Fields represent data pertaining to objects. Setters and Getters − Allows the program to initialize and retrieve the values of the fields of a class. A default getter/ setter is associated with every class. However, the default ones can be overridden by explicitly defining a setter/ getter. Constructors − responsible for allocating memory for the objects of the class. Functions − Functions represent actions an object can take. They are also at times referred to as methods. These components put together are termed as the data members of the class. Example: Declaring a class class Car { // field String engine = “E1001”; // function void disp() { print(engine); } } The example declares a class Car. The class has a field named engine. The disp() is a simple function that prints the value of the field engine. Creating Instance of the class To create an instance of the class, use the new keyword followed by the class name. The syntax for the same is given below − Syntax var object_name = new class_name([ arguments ]) The new keyword is responsible for instantiation. The right-hand side of the expression invokes the constructor. The constructor should be passed values if it is parameterized. Example: Instantiating a class var obj = new Car(“Engine 1”) Accessing Attributes and Functions A class’s attributes and functions can be accessed through the object. Use the ‘.’ dot notation (called as the period) to access the data members of a class. //accessing an attribute obj.field_name //accessing a function obj.function_name() Example Take a look at the following example to understand how to access attributes and functions in Dart − Live Demo void main() { Car c= new Car(); c.disp(); } class Car { // field String engine = “E1001″; // function void disp() { print(engine); } } The output of the above code is as follows − E1001 Dart Constructors A constructor is a special function of the class that is responsible for initializing the variables of the class. Dart defines a constructor with the same name as that of the class. A constructor is a function and hence can be parameterized. However, unlike a function, constructors cannot have a return type. If you don’t declare a constructor, a default no-argument constructor is provided for you. Syntax Class_name(parameter_list) { //constructor body } Example The following example shows how to use constructors in Dart − Live Demo void main() { Car c = new Car(”E1001”); } class Car { Car(String engine) { print(engine); } } It should produce the following output − E1001 Named Constructors Dart provides named constructors to enable a class define multiple constructors. The syntax of named constructors is as given below − Syntax : Defining the constructor Class_name.constructor_name(param_list) Example The following example shows how you can use named constructors in Dart − Live Demo void main() { Car c1 = new Car.namedConst(”E1001”); Car c2 = new Car(); } class Car { Car() { print(“Non-parameterized constructor invoked”); } Car.namedConst(String engine) { print(“The engine is : ${engine}”); } } It should produce the following output − The engine is : E1001 Non-parameterized constructor invoked The this Keyword The this keyword refers to the current instance of the class. Here, the parameter name and the name of the class’s field are the same. Hence to avoid ambiguity, the class’s field is prefixed with the this keyword. The following example explains the same − Example The following example explains how to use the this keyword in Dart − Live Demo void main() { Car c1 = new Car(”E1001”); } class Car { String engine; Car(String engine) { this.engine = engine; print(“The engine is : ${engine}”); } } It should produce the following output − The engine is : E1001 Dart Class ─ Getters and Setters Getters and Setters, also called as accessors and mutators, allow the program to initialize and retrieve the values of class fields respectively. Getters or accessors are defined using the get keyword. Setters or mutators are defined using the set keyword. A default getter/setter is associated with every class. However, the default ones can be overridden by explicitly defining a setter/ getter. A getter has no parameters and returns a value, and the setter has one parameter and does not return a value. Syntax: Defining a getter Return_type get identifier { } Syntax: Defining a setter set identifier { } Example The following example shows how you can use getters and setters in a Dart class − Live Demo class Student { String name; int age; String get stud_name { return name; } void set stud_name(String name) { this.name = name; } void set stud_age(int age) { if(age<= 0) { print(“Age should be greater than 5″); } else { this.age = age; } } int get stud_age { return age; } } void main() { Student s1 = new Student(); s1.stud_name = ”MARK”; s1.stud_age = 0; print(s1.stud_name); print(s1.stud_age); } This program code should produce the following output − Age should be greater than 5 MARK Null Class Inheritance Dart supports the concept of Inheritance which is the ability of a program to create new classes from an existing

Dart Programming – Lists

Dart Programming – Lists (Basic Operations) ”; Previous Next In this chapter, we will discuss how to carry out some basic operations on Lists, such as − Sr.No Basic Operation & Description 1 Inserting Elements into a List Mutable Lists can grow dynamically at runtime. The List.add() function appends the specified value to the end of the List and returns a modified List object. 2 Updating a list Lists in Dart can be updated by − Updating The Index Using the List.replaceRange() function 3 Removing List items The following functions supported by the List class in the dart:core library can be used to remove the item(s) in a List. Print Page Previous Next Advertisements ”;

Dart Programming – Runes

Dart Programming – Runes ”; Previous Next Strings are a sequence of characters. Dart represents strings as a sequence of Unicode UTF-16 code units. Unicode is a format that defines a unique numeric value for each letter, digit, and symbol. Since a Dart string is a sequence of UTF-16 code units, 32-bit Unicode values within a string are represented using a special syntax. A rune is an integer representing a Unicode code point. The String class in the dart:core library provides mechanisms to access runes. String code units / runes can be accessed in three ways − Using String.codeUnitAt() function Using String.codeUnits property Using String.runes property String.codeUnitAt() Function Code units in a string can be accessed through their indexes. Returns the 16-bit UTF-16 code unit at the given index. Syntax String.codeUnitAt(int index); Example Live Demo import ”dart:core”; void main(){ f1(); } f1() { String x = ”Runes”; print(x.codeUnitAt(0)); } It will produce the following output − 82 String.codeUnits Property This property returns an unmodifiable list of the UTF-16 code units of the specified string. Syntax String. codeUnits; Example Live Demo import ”dart:core”; void main(){ f1(); } f1() { String x = ”Runes”; print(x.codeUnits); } It will produce the following output − [82, 117, 110, 101, 115] String.runes Property This property returns an iterable of Unicode code-points of this string.Runes extends iterable. Syntax String.runes Example Live Demo void main(){ “A string”.runes.forEach((int rune) { var character=new String.fromCharCode(rune); print(character); }); } It will produce the following output − A s t r i n g Unicode code points are usually expressed as uXXXX, where XXXX is a 4-digit hexadecimal value. To specify more or less than 4 hex digits, place the value in curly brackets. One can use the constructor of the Runes class in the dart:core library for the same. Example Live Demo main() { Runes input = new Runes(” u{1f605} ”); print(new String.fromCharCodes(input)); } It will produce the following output − Print Page Previous Next Advertisements ”;

Dart Programming – Interfaces

Dart Programming – Interfaces ”; Previous Next An interface defines the syntax that any entity must adhere to. Interfaces define a set of methods available on an object. Dart does not have a syntax for declaring interfaces. Class declarations are themselves interfaces in Dart. Classes should use the implements keyword to be able to use an interface. It is mandatory for the implementing class to provide a concrete implementation of all the functions of the implemented interface. In other words, a class must redefine every function in the interface it wishes to implement. Syntax: Implementing an Interface class identifier implements interface_name Example In the following program, we are declaring a class Printer. The ConsolePrinter class implements the implicit interface declaration for the Printer class. The main function creates an object of the ConsolePrinter class using the new keyword. This object is used to invoke the function print_data defined in the ConsolePrinter class. Live Demo void main() { ConsolePrinter cp= new ConsolePrinter(); cp.print_data(); } class Printer { void print_data() { print(“__________Printing Data__________”); } } class ConsolePrinter implements Printer { void print_data() { print(“__________Printing to Console__________”); } } It should produce the following output − __________Printing to Console__________ Implementing Multiple Interfaces A class can implement multiple interfaces. The interfaces are separated by a comma. The syntax for the same is given below − class identifier implements interface-1,interface_2,interface_4……. The following example shows how you can implement multiple interfaces in Dart − Live Demo void main() { Calculator c = new Calculator(); print(“The gross total : ${c.ret_tot()}”); print(“Discount :${c.ret_dis()}”); } class Calculate_Total { int ret_tot() {} } class Calculate_Discount { int ret_dis() {} } class Calculator implements Calculate_Total,Calculate_Discount { int ret_tot() { return 1000; } int ret_dis() { return 50; } } It should produce the following output − The gross total: 1000 Discount:50 Print Page Previous Next Advertisements ”;