Dart Programming
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.
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
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.
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. |
Dart Programming - Boolean
Dart provides an inbuilt support for the Boolean data type. The Boolean data type in DART supports only two values – true and false. The keyword bool is used to represent a Boolean literal in DART.
The syntax for declaring a Boolean variable in DART is as given below −
bool var_name = true; OR bool var_name = false
Example
void main() { bool test; test = 12 > 5; print(test); }
It will produce the following output −
true
Example
Unlike JavaScript, the Boolean data type recognizes only the literal true as true. Any other value is considered as false. Consider the following example −
var str = 'abc'; if(str) { print('String is not empty'); } else { print('Empty String'); }
The above snippet, if run in JavaScript, will print the message ‘String is not empty’ as the if construct will return true if the string is not empty.
However, in Dart, str is converted to false as str != true. Hence the snippet will print the message ‘Empty String’ (when run in unchecked mode).
Example
The above snippet if run in checked mode will throw an exception. The same is illustrated below −
void main() { var str = 'abc'; if(str) { print('String is not empty'); } else { print('Empty String'); } }
It will produce the following output, in Checked Mode −
Unhandled exception: type 'String' is not a subtype of type 'bool' of 'boolean expression' where String is from dart:core bool is from dart:core #0 main (file:///D:/Demos/Boolean.dart:5:6) #1 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:261) #2 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:148)
It will produce the following output, in Unchecked Mode −
Empty String
Note − The WebStorm IDE runs in checked mode, by default.
Dart Programming - Lists
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 Demovoid 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 Demovoid 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 Demovoid 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. |
Dart Programming - Map
The Map object is a simple key/value pair. Keys and values in a map may be of any type. A Map is a dynamic collection. In other words, Maps can grow and shrink at runtime.
Maps can be declared in two ways −
- Using Map Literals
- Using a Map constructor
Declaring a Map using Map Literals
To declare a map using map literals, you need to enclose the key-value pairs within a pair of curly brackets "{ }".
Here is its syntax −
var identifier = { key1:value1, key2:value2 [,…..,key_n:value_n] }
Declaring a Map using a Map Constructor
To declare a Map using a Map constructor, we have two steps. First, declare the map and second, initialize the map.
The syntax to declare a map is as follows −
var identifier = new Map()
Now, use the following syntax to initialize the map −
map_name[key] = value
Example: Map Literal
void main() { var details = {'Usrname':'tom','Password':'pass@123'}; print(details); }
It will produce the following output −
{Usrname: tom, Password: pass@123}
Example: Adding Values to Map Literals at Runtime
void main() { var details = {'Usrname':'tom','Password':'pass@123'}; details['Uid'] = 'U1oo1'; print(details); }
It will produce the following output −
{Usrname: tom, Password: pass@123, Uid: U1oo1}
Example: Map Constructor
void main() { var details = new Map(); details['Usrname'] = 'admin'; details['Password'] = 'admin@123'; print(details); }
It will produce the following output −
{Usrname: admin, Password: admin@123}
Note − A map value can be any object including NULL.
Map – Properties
The Map class in the dart:core package defines the following properties −
Sr.No | Property & Description |
---|---|
1 | Keys Returns an iterable object representing keys |
2 | Values Returns an iterable object representing values |
3 | Length Returns the size of the Map |
4 | isEmpty Returns true if the Map is an empty Map |
5 | isNotEmpty Returns true if the Map is an empty Map |
Map - Functions
Following are the commonly used functions for manipulating Maps in Dart.
Sr.No | Function Name & Description |
---|---|
1 | addAll() Adds all key-value pairs of other to this map. |
2 | clear() Removes all pairs from the map. |
3 | remove() Removes key and its associated value, if present, from the map. |
4 | forEach() Applies f to each key-value pair of the map. |
Comments
Post a Comment