String

2. Data Types

Dart String is a sequence of the character or UTF-16 code units. It is used to store the text value. The string can be created using single quotes or double-quotes. The multiline string can be created using the triple-quotes. Strings are immutable; it means you cannot modify it after creation. In Dart, The String keyword can be used to declare the string. The syntax of the string declaration is given below. Syntax: Printing String The print() function is used to print the string on the screen. The string can be formatted message, any expression, and any other object. Dart provides ${expression}, which is used to put the value inside a string. Let’ have at look at the following example. Example – Output: String Concatenation The + or += operator is used to merge the two string. The example is given below. Output: String Interpolation The string interpolation is a technique to manipulate the string and create the new string by adding another value. It can be used to evaluate the string including placeholders, variables, and interpolated expression. The ${expression} is used for string interpolation. The expressions are replaced with their corresponding values. Let’s understand by the following example. Output: Explanation – In the above code, we have declared two strings variable, created a new string after concatenation, and printed the result. We have created two variables that hold integer value then performed the mod operation and we printed the result using the string interpolation. We can use the string interpolation as a placeholder, as we have shown in the above example. String Properties The Dart provides the following string properties. Property Description codeUnits It returns an unmodified list of the UTF-16 code units of this string. isEmpty If the string is empty, it returns true. Length It returns the length of the string including whitespace. String Methods The Dart provides an extensive range of methods. The list of a few essential methods is given below. Methods Descriptions toLowerCase() It converts all characters of the given string in lowercase. toUpperCase() It converts all characters of the given string in uppercase. trim() It eliminates all whitespace from the given string. compareTo() It compares one string from another. replaceAll() It replaces all substring that matches the specified pattern with a given string. split() It splits the string at matches of the specified delimiter and returns the list of the substring. substring() It returns the substring from start index, inclusive to end index. toString() It returns the string representation of the given object. codeUnitAt() It returns the 16-bits code unit at the given index.

October 11, 2024 / 0 Comments
read more

Number

2. Data Types

The Number is the data type that is used to hold the numeric value. In Dart, It can be two types – Dart integer – Integer numbers are the whole numbers means that can be written without a fractional component. For example – 20, 30, -3215, 0, etc. An integer number can be signed or unsigned. The representation of the integer value is in between -263 to 263 non-decimal numbers. The int keyword is used to declare integer value in Dart. Dart Double – The Double number are the numbers that can be written with floating-point numbers or number with larger decimal points. The double keyword is used to declare Double value in Dart. Rules for the integer value Let’s have a look at following example – Example – Output: Dart parse() function The parse() function converts the numeric string to the number. Consider the following example – Example – Output: Explanation – In the above example, we converted the numeric strings into the numbers by using parse() method then stored in the variables. After the successful conversion, we performed add operation and printed the output to the screen. Number Properties Properties Description hashcode It returns the hash code of the given number. isFinite If the given number is finite, then it returns true. isInfinite If the number infinite it returns true. isNan If the number is non-negative then it returns true. isNegative If the number is negative then it returns true. sign It returns -1, 0, or 1 depending upon the sign of the given number. isEven If the given number is an even then it returns true. isOdd If the given number is odd then it returns true. Number Methods The commonly used methods of number are given below. Method Description abs() It gives the absolute value of the given number. ceil() It gives the ceiling value of the given number. floor() It gives the floor value of the given number. compareTo() It compares the value with other number. remainder() It gives the truncated remainder after dividing the two numbers. round() It returns the round of the number. toDouble() It gives the double equivalent representation of the number. toInt() Returns the integer equivalent representation of the number. toString() Returns the String equivalent representation of the number truncate() Returns the integer after discarding fraction digits.

October 11, 2024 / 0 Comments
read more

Constants

2. Data Types

Dart Constant is defined as an immutable object, which means it can’t be changed or modified during the execution of the program. Once we initialize the value to the constant variable, it cannot be reassigned later. Defining/Initializing Constant in Dart The Dart constant can be defined in the following two ways. It is beneficial when we want to keep the value unchanged in the whole program. The keywords final and const are used to create a constant variable. Both keywords final and const are used as a conjunction with the data-type. Dart will throw an exception if we try to modify the constant variable. A const keyword represents the compile-time constant, and the final variable can be set only once. Define Constant Using final Keyword We can define the constant by using the final keyword. The syntax is given below. Syntax: Let’s understand the following example. Example – Output: Define Constants Using const Keyword We can define constant using the const keyword. The syntax is given below. Syntax – Let’s understand the following example. Output:

October 11, 2024 / 0 Comments
read more

HTML DOM

1. Tutorial

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. 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 − 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. 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 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. 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 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. 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 − Let us now take an example to understand the concept of Event Handling in Dart. TestEvent.html TestEvent.dart Output

October 11, 2024 / 0 Comments
read more

Unit Testing

1. Tutorial

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 − 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 − Step 2: Importing the “test” package 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 The group() function can be used to group tests. Each group’s description is added to the beginning of its test’s descriptions. Syntax 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. It should produce the following output − Example 2: A Failing Test The subtract() method defined below has a logical mistake. The following test verifies the same. Output − The test case for the function add() passes but the test for subtract() fails as shown below. 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 Output − The output will append the group name for each test case as given below −

October 11, 2024 / 0 Comments
read more

Concurrency

1. Tutorial

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. 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 − 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 Output 2 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.

October 11, 2024 / 0 Comments
read more

Async

1. Tutorial

An asynchronous operation executes in a thread, separate from the main application thread. When an application calls a method to perform an operation asynchronously, the application can continue executing while the asynchronous method performs its task. Example Let’s take an example to understand this concept. Here, the program accepts user input using the IO library. The readLineSync() is a synchronous method. This means that the execution of all instructions that follow the readLineSync() function call will be blocked till the readLineSync() method finishes execution. The stdin.readLineSync waits for input. It stops in its tracks and does not execute any further until it receives the user’s input. The above example will result in the following output − In computing, we say something is synchronous when it waits for an event to happen before continuing. A disadvantage in this approach is that if a part of the code takes too long to execute, the subsequent blocks, though unrelated, will be blocked from executing. Consider a webserver that must respond to multiple requests for a resource. A synchronous execution model will block every other user’s request till it finishes processing the current request. In such a case, like that of a web server, every request must be independent of the others. This means, the webserver should not wait for the current request to finish executing before it responds to request from other users. Simply put, it should accept requests from new users before necessarily completing the requests of previous users. This is termed as asynchronous. Asynchronous programming basically means no waiting or non-blocking programming model. The dart:async package facilitates implementing asynchronous programming blocks in a Dart script. Example The following example better illustrates the functioning of an asynchronous block. Step 1 − Create a contact.txt file as given below and save it in the data folder in the current project. Step 2 − Write a program which will read the file without blocking other parts of the application. The output of this program will be as follows − The “end of main” executes first while the script continues reading the file. The Future class, part of dart:async, is used for getting the result of a computation after an asynchronous task has completed. This Future value is then used to do something after the computation finishes. Once the read operation is completed, the execution control is transferred within “then()”. This is because the reading operation can take more time and so it doesn’t want to block other part of program. Dart Future The Dart community defines a Future as “a means for getting a value sometime in the future.” Simply put, Future objects are a mechanism to represent values returned by an expression whose execution will complete at a later point in time. Several of Dart’s built-in classes return a Future when an asynchronous method is called. Dart is a single-threaded programming language. If any code blocks the thread of execution (for example, by waiting for a time-consuming operation or blocking on I/O), the program effectively freezes. Asynchronous operations let your program run without getting blocked. Dart uses Future objects to represent asynchronous operations.

October 11, 2024 / 0 Comments
read more

Libraries

1. Tutorial

A library in a programming language represents a collection of routines (set of programming instructions). Dart has a set of built-in libraries that are useful to store routines that are frequently used. A Dart library comprises of a set of classes, constants, functions, typedefs, properties, and exceptions. Importing a library Importing makes the components in a library available to the caller code. The import keyword is used to achieve the same. A dart file can have multiple import statements. Built in Dart library URIs use the dart: scheme to refer to a library. Other libraries can use a file system path or the package: scheme to specify its URI. Libraries provided by a package manager such as the pub tool uses the package: scheme. The syntax for importing a library in Dart is given below − Consider the following code snippet − If you want to use only part of a library, you can selectively import the library. The syntax for the same is given below − Some commonly used libraries are given below − Sr.No Library & Description 1 dart:ioFile, socket, HTTP, and other I/O support for server applications. This library does not work in browser-based applications. This library is imported by default. 2 dart:coreBuilt-in types, collections, and other core functionality for every Dart program. This library is automatically imported. 3 dart: mathMathematical constants and functions, plus a random number generator. 4 dart: convertEncoders and decoders for converting between different data representations, including JSON and UTF-8. 5 dart: typed_dataLists that efficiently handle fixed sized data (for example, unsigned 8 byte integers). Example : Importing and using a Library The following example imports the built-in library dart: math. The snippet calls the sqrt() function from the math library. This function returns the square root of a number passed to it. Output Encapsulation in Libraries Dart scripts can prefix identifiers with an underscore ( _ ) to mark its components private. Simply put, Dart libraries can restrict access to its content by external scripts. This is termed as encapsulation. The syntax for the same is given below − Syntax Example At first, define a library with a private function. Next, import the library The above code will result in an error. Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career. Creating Custom Libraries Dart also allows you to use your own code as a library. Creating a custom library involves the following steps − Step 1: Declaring a Library To explicitly declare a library, use the library statement. The syntax for declaring a library is as given below − Step 2: Associating a Library You can associate a library in two ways − Example: Custom Library First, let us define a custom library, calculator.dart. Next, we will import the library − The program should produce the following output − Library Prefix If you import two libraries with conflicting identifiers, then you can specify a prefix for one or both libraries. Use the ‘as’ keyword for specifying the prefix. The syntax for the same is given below − Syntax Example First, let us define a library: loggerlib.dart. Next, we will define another library: webloggerlib.dart. Finally, we will import the library with a prefix. It will produce the following output −

October 11, 2024 / 0 Comments
read more

Typedef

1. Tutorial

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. 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. Step 3: Invoking a Function The typedef variable can be used to invoke functions. Here is how you can invoke a function − 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. Next, let us define the functions. Define some functions with the same function signature as that of the ManyOperation typedef. Finally, we will invoke the function via typedef. Declare a variable of the ManyOperations type. Assign the function name to the declared variable. 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. The program should produce the following output − 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 − It will produce the following output −

October 11, 2024 / 0 Comments
read more

Debugging

1. Tutorial

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) 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 −

October 11, 2024 / 0 Comments
read more

Posts pagination

Previous 1 … 117 118 119 … 445 Next