An enumeration is a set of values called as elements, members, etc. This is essential when we carried out the operation with the limited set of values available for variable. For example – you can think of the days of the month can only be one of the seven days – Sun, Mon, Tue, Wed, Thur, Fri, Sat.
Initializing an Enumeration
The enumeration is declared using the enum keyword, followed by the comma-separated list of the valid identifiers. This list is enclosed within the curly braces {}. The syntax is given below.
Here, the enum_name denotes the enum type name and list of the identifiers enclosed within the curly bracket.
Each of the identifier in the enumeration list has its index position. The index of the first enumeration is 0; the second enumeration is 1, and so on.
Example –
Let’s define an enumeration for months of the year.
enum EnumofYear {
January,
February,
March,
April,
May,
June,
July,
August,
September,
October,
November,
December,
}
As we discussed earlier, Dart String is a sequence of characters, letters, numbers, and unique characters. It is the sequence of UTF – 16 Unicode characters where Dart Runes are the sequence UTF – 32 Unicode code points. It is a UTF-32 string which is used to print the special symbol. For example – The theta (Θ) symbol is signified by using the corresponding Unicode equivalent \u0398; here ‘\u’ refers to Unicode, and the numbers are in the hexadecimal. Sometimes the hex digits are the more than 4 digits then it should be placed in curly brackets ({}). Let’s understand it by the following example.
Example –
void main() {
var heart_rune = '\u2665';
var theta_rune = '\u{1f600}';
print(heart_rune);
print(theta_rune);
}
Output:
♥
Θ
The Dart provides the dart: core library which has the Dart Runes. The String code unit can be retrieved in the following three methods.
Using String.codeUnitAt() Method
Using String.codeUnits property
Using String.runes property
String.codeUnitAt() Method
We can access the character’s code unit in the given string by using the codeUnitAt() method. It accepts the index position as an argument and returns the 16-bit UTF-16 code unit at the passed index position of the string. The syntax is the given below.
In the above code, the variable str holds string value “JavaTpoint”. We called the codeuUnitAt() function and passed index position. It returned the code unit of 0th index character.
String.codeUnits Property
The codeUnits property returns UTF-16 code units for given string in the form of a list. The syntax is given below.
Symbol object is used to specify an operator or identifier declared in a Dart programming language. Generally, we do not need to use symbols while Dart programming, but they are helpful for APIs. It usually refers to identifiers by name, because identifier names can vary but not identifier symbols.
Dart symbols are dynamic string name that is used to derive the metadata from a library. It mainly accumulates the connection between human-readable strings that are enhanced to be used by computers.
Symbols have a term which is called Reflection; it is a technique that used to the metadata of at run-time, for example – the number of methods used in class, a number of constructors in a class, or numbers of arguments in a function.
The dart:mirrors library has all of the reflection related classes. It can be used with the command-line applications as well as web applications.
Syntax –
The hash(#) symbol, followed by the name is used to define Symbol in Dart. The syntax is given below.
Syntax –
Symbol obj = new Symbol("name")
Here, the valid identifier such as function, valid class, public member name, or library name can be used in place of name value.
#radix
#bar
Let’s understand the following example.
Example –
library foo_lib;
// libarary name can be a symbol
class Foo {
// class name can be a symbol
m1() {
// method name can be a symbol
print("Inside m1");
}
m2() {
print("Inside m2");
}
m3() {
print("Inside m3");
}
}
In the above code, we have declared a class Foo in a library foo_lib. The class contains the methods m1, m2, and m3. We save the above file as foo.dart.
Now, we are creating new file FooSymbol.dart and run the following code.
FoolSystem.dart
import 'dart:core';
import 'dart:mirrors';
import 'Foo.dart';
main() {
Symbol lib = new Symbol("foo_lib");
//library name stored as Symbol
Symbol clsToSearch = new Symbol("Foo");
// class name stored as Symbol
if(checkIf_classAvailableInlibrary(lib, clsToSearch))
// searches Foo class in foo_lib library
print("class found..");
}
bool checkIf_classAvailableInlibrary(Symbol libraryName, Symbol className) {
MirrorSystem mirrorSystem = currentMirrorSystem();
LibraryMirror libMirror = mirrorSystem.findLibrary(libraryName);
if (libMirror != null) {
print("Found Library");
print("checkng...class details..");
print("No of classes found is : ${libMirror.declarations.length}");
libMirror.declarations.forEach((s, d) => print(s));
if (libMirror.declarations.containsKey(className)) return true;
return false;
}
}
</pre></div>
<p>The above code will show the following output.</p>
<p><strong>Output:</strong></p>
<div class="codeblock"><pre>
Found Library
checkng...class details..
No of classes found is : 1
Symbol("Foo") // Displays the class name
class found..
</pre></div>
<p><strong>Example - 2 : Print the number of instance methods of class</strong></p>
<p>In the following example, The Dart provides predefine class <strong>ClassMirror</strong> which helps us to display the number of instance methods of class.</p>
<p><strong>Example -</strong></p>
<div class="codeblock"><textarea name="code" class="java">
import 'dart:core';
import 'dart:mirrors';
import 'Foo.dart';
main() {
Symbol lib = new Symbol("foo_lib");
Symbol clsToSearch = new Symbol("Foo");
reflect_InstanceMethods(lib, clsToSearch);
}
void reflect_InstanceMethods(Symbol libraryName, Symbol className) {
MirrorSystem mirrorSystem = currentMirrorSystem();
LibraryMirror libMirror = mirrorSystem.findLibrary(libraryName);
if (libMirror != null) {
print("Found Library");
print("checkng...class details..");
print("No of classes found is : ${libMirror.declarations.length}");
libMirror.declarations.forEach((s, d) => print(s));
if (libMirror.declarations.containsKey(className)) print("found class");
ClassMirror classMirror = libMirror.declarations[className];
print("No of instance methods found is ${classMirror.instanceMembers.length}");
classMirror.instanceMembers.forEach((s, v) => print(s));
}
}
Output:
Found Library
checkng...class details..
No of classes found is : 1
Symbol("Foo")
found class
No of instance methods found is 8
Symbol("==")
Symbol("hashCode")
Symbol("toString")
Symbol("noSuchMethod")
Symbol("runtimeType")
Symbol("m1")
Symbol("m2")
Symbol("m3")
Dart Convert Symbol to String
We can convert the Dart symbol into the string by using a built-in class MirrorClass, which is provided by the dart:mirror package. Let’s understand the following example.
Example –
import 'dart:mirrors';
void main(){
Symbol lib = new Symbol("foo_lib");
String name_of_lib = MirrorSystem.getName(lib);
print(lib);
print(name_of_lib);
}
Dart Map is an object that stores data in the form of a key-value pair. Each value is associated with its key, and it is used to access its corresponding value. Both keys and values can be any type. In Dart Map, each key must be unique, but the same value can occur multiple times. The Map representation is quite similar to Python Dictionary. The Map can be declared by using curly braces {} ,and each key-value pair is separated by the commas(,). The value of the key can be accessed by using a square bracket([]).
Declaring a Dart Map
Dart Map can be defined in two methods.
Using Map Literal
Using Map Constructor
The syntax of declaring Dart Map is given below.
Using Map Literals
To declare a Map using map literal, the key-value pairs are enclosed within the curly braces “{}” and separated by the commas. The syntax is given below.
Syntax –
var map_name = {key1:value1, key2:value2 [.......,key_n: value_n]}
Example – 1:
void main() {
var student = {'name':'Tom','age':'23'};
print(student);
}
In the above example, we declared a Map of a student name. We added the value at runtime by using a square bracket and passed the new key as a course associated with its value.
Using Map Constructor
To declare the Dart Map using map constructor can be done in two ways. First, declare a map using map() constructor. Second, initialize the map. The syntax is given below.
{name: Tom, age: 23, course: B.tech, Branch: Computer Science}
Note – A map value can be any object including NULL.
Map Properties
The dart:core:package has Map class which defines following properties.
Properties
Explanation
Keys
It is used to get all keys as an iterable object.
values
It is used to get all values as an iterable object.
Length
It returns the length of the Map object.
isEmpty
If the Map object contains no value, it returns true.
isNotEmpty
If the Map object contains at least one value, it returns true.
Example –
void main() {
var student = new Map();
student['name'] = 'Tom';
student['age'] = 23;
student['course'] = 'B.tech';
student['Branch'] = 'Computer Science';
print(student);
// Get all Keys
print("The keys are : ${student.keys}");
// Get all values
print("The values are : ${student.values}");
// Length of Map
print("The length is : ${student.length}");
//isEmpty function
print(student.isEmpty);
//isNotEmpty function
print(student.isNotEmpty);
}
Output:
{name: Tom, age: 23, course: B.tech, Branch: Computer Science}
The keys are : (name, age, course, Branch)
The values are : (Tom, 23, B.tech, Computer Science)
The length is : 4
false
true
Map Methods
The commonly used methods are given below.
addAll() – It adds multiple key-value pairs of other. The syntax is given below.
Syntax –
Map.addAll(Map<Key, Value> other)
Parameter:
other – It denotes a key-value pair. It returns a void type.
The Dart Set is the unordered collection of the different values of the same type. It has much functionality, which is the same as an array, but it is unordered. Set doesn’t allow storing the duplicate values. The set must contain unique values.
It plays an essential role when we want to store the distinct data of the same type into the single variable. Once we declare the type of the Set, then we can have an only value of the same type. The set cannot keep the order of the elements.
Dart Initializing Set
Dart provides the two methods to declare/initialize an empty set. The set can be declared by using the {} curly braces proceeded by a type argument, or declare the variable type Set with curly braces {}. The syntax of declaring set is given below.
Syntax –
var setName = <type>{};
Or
Set<type> setname = {};
The setname refers to the name of the set variable, and type refers to the data type of the set.
Note – It should be remembered that the syntax of the set is much similar to the map literals. If we forget to define the type annotation with {} or with the variable it’s assigned to; then, Dart compiler will create Map object instead of Set.Let’s have a look at the following example of set declaration –Example –void main(){ print(“Initializing the Set”); var names = <String>{“James”,”Ricky”, “Devansh”,”Adam”}; print(names); } Output:Initializing the Set {James, Ricky, Devansh, Adam}
Add Element into Set
The Dart provides the two methods add() and addAll() to insert an element into the given set. The add() method is used to add the single item into the given set. It can add one at a time when the addAll() method is used to add the multiple elements to an existing set. The syntax is given below.
Syntax:
Set_name.add(<value>);
Or
Set_name.addAll(val1,val2....valN)
Consider the following example –
Example –
void main(){
print("Insert element into the Set");
var names = {"James","Ricky","Devansh","Adam"};
// Declaring empty set
var emp = <String>{};
emp.add("Jonathan");
print(emp);
// Adding multiple elements
emp.addAll(names);
print(emp);
}
Output:
Insert element into the Set
{Jonathan}
{Jonathan, James, Ricky, Devansh, Adam}
Explanation –
We have declared two sets of names and emp. The set names consisted of few elements, while emp is an empty set. We added the single element “Jonathan” by using the add() method then; we called the addAll() method and passed another set names as an argument. It added the multiple values to the emp set.
Access the Set Element
Dart provides the elementAt() method, which is used to access the item by passing its specified index position. The set indexing starts from the 0 and goes up to size – 1, where size is the number of the element exist in the Set. It will throw an error if we enter the bigger index number than its size. The syntax is given below.
Syntax:
Set_name.elementAt(index)
Consider the following example.
Example –
void main(){
print("Access element from the Set");
var names = {"James","Ricky","Devansh","Adam"};
print(names);
var x = names.elementAt(3);
print(x);
}
Output:
Access element from the Set
{James, Ricky, Devansh, Adam}
Adam
Explanation –
In the above example, we have set names. We applied the elementAt() method and passed index position 3 as an argument. We created a variable x, which holds the assessed value, and then we printed the result.
Dart Finding Element in Set
Dart provides the contains() method, which is used to find an element in the set. It accepts the single item as an argument ad return the result in Boolean type. If the given element present in the set, it returns true otherwise false. The syntax is given below.
Syntax:
set_name.contains(value);
Example –
void main() {
print("Example - Find Element in the given Set");
var names = <String>{"Peter","John","Ricky","Devansh","Finch"};
if(names.contains("Ricky")){
print("Element Found");
}
else {
print("Element not found");
}
}
Output:
Example - Find Element in the given Set
Element Found
Explanation –
In the above program, to find the element in the given set, we called contains() method and passed value “Ricky” as an argument. We used the conditional statement to find out whether an element belongs to the given set or not. The given element present in the set then condition became true, it printed if block statement.
Note – We will learn conditional statement in the next section.
Dart Remove Set Element
The remove() method is used to eliminate or remove an element from the given set. It takes the value as an argument; the value is to be removed in the given set. The syntax is given below.
Syntax –
set_names.contains(value)
Example –
void main() {
print("Example - Remove Element in the given Set");
var names = <String>{"Peter", "John", "Ricky", "Devansh", "Finch"};
print("Before remove : ${names}");
names.remove("Peter");
print("After remove : ${names}");
}
Output:
Example - Remove Element in the given Set
Before remove : {Peter, John, Ricky, Devansh, Finch}
After remove : {John, Ricky, Devansh, Finch}
Explanation –
In the above program, we removed the “Peter” from the given set by using the remove() method. It returned the newly modified set object.
Dart Iterating Over a Set Element
In Dart, the set element can be iterated using the forEach method as following –
Example –
void main() {
print("Example - Remove Element in the given Set");
var names = <String>{"Peter","John","Ricky","Devansh","Finch"};
names.forEach((value) {
print('Value: $value');
});
}
Output:
Example - Remove Element in the given Set
Value: Peter
Value: John
Value: Ricky
Value: Devansh
Value: Finch
Dart Remove All Set Element
We can remove entire set element by using the clear() methods. It deletes or removes all elements to the given set and returns an empty set. The syntax is as follow-
Syntax –
set_name.clear();
Example –
void main() {
print("Example - Remove All Element to the given Set");
var names = <String>{"Peter","John","Ricky","Devansh","Finch"};
names.clear();
print(names);
}
Output:
Example - Remove All Element to the given Set
{Peter, John, Ricky, Devansh, Finch}
{}
TypeCast Set to List
The Set object can convert into the List Object using the toList() method. The syntax is as follows.
Note – The type of List must be the same as the type of Set.
Syntax –
List<type> <list_name> = <set_name>. toList();
Dart Set Operations
Dart Set provides the facility to perform following set operations. These operations are given below.
Union – The union is set to combine the value of the two given sets a and b.
Intersection – The intersection of the two set a and b returns all elements, which is common in both sets.
Subtracting – The subtracting of two sets a and b (a-b) is the element of set b is not present in the set a.
Let’s understand the following example.
Example –
void main() {
var x = <int>{10,11,12,13,14,15};
var y = <int>{12,18,29,43};
var z = <int>{2,5,10,11,32};
print("Example - Set Operations");
print("x union y is -");
print(x.union(y));
print("x intersection y is - ");
print(x.intersection(y));
print("y difference z is - ");
print(y.difference(z));
}
Output:
Example - Set Operations
x union y is -
{10, 11, 12, 13, 14, 15, 18, 29, 43}
x intersection y is -
{12}
y difference z is -
{12, 18, 29, 43}
Dart Set Properties
The few properties of the Dart set as follows.
Properties
Explanations
first
It is used to get the first element in the given set.
isEmpty
If the set does not contain any element, it returns true.
isNotEmpty
If the set contains at least one element, it returns true
length
It returns the length of the given set.
last
It is used to get the last element in the given set.
hashcode
It is used to get the hash code for the corresponding object.
Single
It is used to check whether a set contains only one element.
Dart List is similar to an array, which is the ordered collection of the objects. The array is the most popular and commonly used collection in any other programming language. The Dart list looks like the JavaScript array literals. The syntax of declaring the list is given below.
var list1 = [10, 15, 20,25,25]
The Dart list is defined by storing all elements inside the square bracket ([]) and separated by commas (,).
Let’s understand the graphical representation of the list –
list1 – It is the list variable that refers to the list object.
Index – Each element has its index number that tells the element position in the list. The index number is used to access the particular element from the list, such as list_name[index]. The list indexing starts from 0 to length-1 where length denotes the numbers of the element present in the list. For example, – The length of the above list is 4.
Elements – The List elements refers to the actual value or dart object stored in the given list.
Types of Lists
The Dart list can be categorized into two types –
Fixed Length List
Growable List
Fixed Length List
The fixed-length lists are defined with the specified length. We cannot change the size at runtime. The syntax is given below.
Syntax – Create the list of fixed-size
var list_name = new List(size)
The above syntax is used to create the list of the fixed size. We cannot add or delete an element at runtime. It will throw an exception if any try to modify its size.
The syntax of initializing the fixed-size list element is given below.
In the above example, we have created a variable list1 that refers the list of fixed size. The size of the list is five and we inserted the elements corresponding to its index position where 0th index holds 10, 1st index holds 12, and so on.
Growable List
The list is declared without specifying size is known as a Growable list. The size of the Growable list can be modified at the runtime. The syntax of the declaring Growable list is given below.
Syntax – Declaring a List
// creates a list with values
var list_name = [val1, val2, val3]
Or
// creates a list of the size zero
var list_name = new List()
Syntax – Initializing a List
list_name[index] = value;
Consider the following example –
Example – 1
void main() {
var list1 = [10,11,12,13,14,15];
print(list1);
}
Output:
[10, 11, 12, 13, 14, 15]
In the following example, we are creating a list using the empty list or List() constructor. The add() method is used to add element dynamically in the given list.
Example – 2
void main() {
var list1 = new List();
list1.add(10);
list1.add(11);
list1.add(12);
list1.add(13);
print(list1);
}
Output:
[10, 11, 12, 13]
List Properties
Below are the properties of the list.
Property
Description
first
It returns the first element case.
isEmpty
It returns true if the list is empty.
isNotEmpty
It returns true if the list has at least one element.
length
It returns the length of the list.
last
It returns the last element of the list.
reversed
It returns a list in reverse order.
Single
It checks if the list has only one element and returns it.
Inserting Element into List
Dart provides four methods which are used to insert the elements into the lists. These methods are given below.
add()
addAll()
insert()
insertAll()
The add() Method
This method is used to insert the specified value at the end of the list. It can add one element at a time and returns the modified list object. Let’s understand the following example –
In the above example, we have a list named odd_list, which holds odd numbers. We inserted a new element 11 using add() function. The add() function appended the element at the end of the list and returned the modified list.
The addAll() Method
This method is used to insert the multiple values to the given list. Each value is separated by the commas and enclosed with a square bracket ([]). The syntax is given below.
In the above example, we don’t need to call the add() function multiple times. The addAll() appended the multiple values at once and returned the modified list object.
The insert() Method
The insert() method provides the facility to insert an element at specified index position. We can specify the index position for the value to be inserted in the list. The syntax is given below.
list_name.insert(index,value);
Let’s understand the following example –
void main(){
List lst = [3,4,2,5];
print(lst);
lst.insert(2,10);
print(lst);
}
Output:
[3, 4, 2, 5]
[3, 4, 10, 2, 5]
Explanation –
In the above example, we have a list of the random numbers. We called the insert() function and passed the index 2nd value 10 as an argument. It appended the value at the 2nd index and returned the modified list object.
The insertAll() Method
The insertAll() function is used to insert the multiple value at the specified index position. It accepts index position and list of values as an argument. The syntax is given below.
void main(){
List lst = [3,4,2,5];
print(lst);
lst.insertAll(0,[6,7,10,9]);
print(lst);
}
Output:
[3, 4, 2, 5]
[6, 7, 10, 9, 3, 4, 2, 5]
Explanation –
In the above example, we have appended the list of values at the 0th index position using the insertAll() function. It returned the modified list object.
Updating List
The Dart provides the facility to update the list and we can modify the list by simply accessing its element and assign it a new value. The syntax is given below.
Syntax –
list_name[index] = new_value;
Let’s understand the following example –
Example –
void main(){
var list1 = [10,15,20,25,30];
print("List before updation: ${list1}");
list1[3] = 55;
print("List after updation:${list1}");
}
Output:
List before updation: [10, 15, 20, 25, 30]
List after updation: [10, 15, 20, 55, 30]
Explanation –
In the above example, we have accessed the 3rd index and assigned the new value 55 then printed the result. The previous list updated with the new value 55.
replaceRange() – The Dart provides replaceRange() function which is used to update within the given range of list items. It updates the value of the elements with the specified range. The syntax is given below.
Syntax –
list_name.replaceRange(int start_val, int end_val, iterable);
Let’s understand the following example –
Example –
void main(){
var list1 = [10,15,20,25,30];
print("List before updation: ${list1}");
list1.replaceRange(0,4,[1,2,3,4]) ;
print("List after updation using replaceAll() function : ${list1}");
}
Output:
List before updation: [10, 15, 20, 25, 30]
List after updation using replaceAll() function : [1, 2, 3, 4, 30]
Explanation –
In the above example, we called the replaceRange() to the list which accepts the three arguments. We passed the starting index 0th, end index 4 and the list of the elements to be replaced as a third arguments. It returned the new list with the replaced element from the given range.
Removing List Elements
The Dart provides following functions to remove the list elements.
remove()
removeAt()
removeLast()
removeRange()
The remove() Method
It removes one element at a time from the given list. It accepts element as an argument. It removes the first occurrence of the specified element in the list if there are multiple same elements. The syntax is given below.
Syntax –
list_name.remove(value)
Let’s understand the following example –
Example –
void main(){
var list1 = [10,15,20,25,30];
print("List before remove element : ${list1}");
list1.remove(20) ;
print("List after removing element : ${list1}");
}
Output:
List before remove element : [10, 15, 20, 25, 30]
List after removing element : [10, 15, 25, 30]
Explanation –
In the above example, we called the remove() function to the list and passed the value 20 as an argument. It removed the 20 from the given list and returned the new modified list.
The removeAt() Method
It removes an element from the specified index position and returns it. The syntax is given below.
Syntax –
list_name.removeAt(int index)
Example –
void main(){
var list1 = [10,11,12,13,14];
print("List before remove element : ${list1}");
list1.removeAt(3) ;
print("List after removing element : ${list1}");
}
Output:
List before remove element : [10, 11, 12, 13, 14]
List after removing element : [10, 11, 12, 14]
Explanation –
In the above example, we passed the 3rd index position as an argument to the removeAt() function and it removed the element 13 from the list.
The removeLast() Method
The removeLast() method is used to remove the last element from the given list. The syntax is given below.
Syntax-
list_name.removeLast()
Let’s understand the following example.
Example –
void main(){
var list1 = [12,34,65,76,80];
print("List before removing element:${list1}");
list1.removeLast();
print("List after removed element:${list1}");
}
Output:
List before removing element:[12, 34, 65, 76, 80]
List after removed element:[12, 34, 65, 76]
In the above example, we called the removeLast() method, which removed and returned the last element 80 from the given list.
The removeRange() Method
This method removes the item within the specified range. It accepts two arguments – start index and end index. It eliminates all element which lies in between the specified range. The syntax is given below.
Syntax –
list_name. removeRange();
Example –
void main(){
var list1 = [12,34,65,76,80];
print("List before removing element:${list1}");
list1.removeRange(1,3);
print("List after removed element:${list1}");
}
Output:
List before removing element:[12, 34, 65, 76, 80]
List after removed element:[12, 76, 80]
Explanation –
In the above example, we called the removeRange() method and passed start index position 1 and end index position 3 as an arguments. It removed all elements which were belonging in between the specified position.
Dart Iterating List elements
The Dart List can be iterated using the forEach method. Let’s have a look at the following example.
Example –
void main(){
var list1 = ["Smith","Peter","Handscomb","Devansh","Cruise"];
print("Iterating the List Element");
list1.forEach((item){
print("${list1.indexOf(item)}: $item");
});
}
Output:
Iterating the List Element
0: Smith
1: Peter
2: Handscomb
3: Devansh
4: Cruise
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:
String msg = 'Welcome to JavaTpoint';
or
String msg1 = "This is double-quoted string example.";
or
String msg2 = ' ' ' line1
line2
line3'''
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 –
void main() {
String str1 = 'this is an example of a single-line string';
String str2 = "this is an example of a double-quotes multiline line string";
String str3 = """this is a multiline line
string using the triple-quotes""";
var a = 10;
var b = 20;
print(str1);
print(str2);
print(str3);
// We can add expression using the ${expression}.
print("The sum is = ${a+b}");
}
Output:
this is an example of a single-line string
this is an example of a double-quotes multiline line string
this is a multiline line
string using the triple-quotes
The sum is = 30
String Concatenation
The + or += operator is used to merge the two string. The example is given below.
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.
void main() {
String str1 = 'Hello ';
String str2 = "World!";
String str3 = str1+str2;
print(str3);
var x = 26;
var y = 10;
print("The result is = ${x%y}");
var name = "Peter";
var roll_nu = 101;
print("My name is ${name}, my roll number is ${roll_nu}");
}
Output:
Hello World!
The result is = 6
My name is Peter, my roll number is 101
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.
The Number is the data type that is used to hold the numeric value. In Dart, It can be two types –
Integer
Double
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.
int id = 501;
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.
double root = 1.41234;
or
double rupees = 100000;
Rules for the integer value
An integer value must be a digit.
The decimal points should not include in an integer number.
Unsigned numbers are always a positive number. Numbers can be either negative or positive.
The size of the integer value depends upon the platform, but integer value should no longer than 64 bit.
Let’s have a look at following example –
Example –
void main(){
int r = 5;
double pi = 3.14;
double res = 4*pi*r*r;
print("The area of sphere = ${(res)}");
}
Output:
The area of sphere 314
Dart parse() function
The parse() function converts the numeric string to the number. Consider the following example –
Example –
void main(){
var a = num.parse("20.56");
var b = num.parse("15.63");
var c = a+b;
print("The sum is = ${c}");
}
Output:
The sum is = 36.19
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.
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.
Using the final keyword
Using the const keyword
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:
final const_name;
or
final data_type const_name
Let’s understand the following example.
Example –
void main () {
final a = 10;
final b = 20;
print(a);
print(b);
}
Output:
10
20
Define Constants Using const Keyword
We can define constant using the const keyword. The syntax is given below.