Introduction To Dart Programming Language
- Overview
- Environment
- Variables
- Operators
String
As you have seen in the previous week's lectures, string data types are represented in a single or double quote.
Examples
String name = "Godwin Ashong";
String town = "Teshie";
String country = "Ghana";
Joining strings
Two or more strings can be joined using the + operator
Examples
String firstname = "Godwin";
String lastname = "Ashong";
String fullname = firstname+lastname;
NOTE: If fullname is printed out, it will output GodwinAshong. In order to leave a space between the first name and last name, there must be an empty string with space in between the two strings. Thus:
String fullname = firstname+" "+lastname;
If the above fullname is printed out, it will output Godwin Ashong
As you have observed, ${} can be used to do computation within a string and the result displayed. You can refer to our previous examples which has that. The computation if there is any in the {} is perform and the result is output.
Example
Write a program which takes the first name and last name of a user and outputs the full name.
Code
// Importing dart:io file
import 'dart:io';
void main()
{
print("Enter your first name");
String fn = stdin.readLineSync();
print("Enter your last name");
String ln = stdin.readLineSync();
String fname = fn+" "+ln;
print("Your full name is ${fname}");
}
Result
Enter your first name
Michael
Enter your last name
Essien
Your full name is Michael Essien
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. |
The isEmpty method can be handy when checking if an input field is empty or not
The Length method can be handy when checking the length of a password for password validation.
Methods to Manipulate Strings
Methods to Manipulate Strings
The String class in the dart: core library also provides methods to manipulate strings.
toLowerCase()
Converts all characters in this string to lower case.
Example
void main() {
String name = "Abigal Adjei";
print('Name before toLowerCase() is called: ${name}');
print('Name when toLower() is called: ${name.toLowerCase()}');
}
Output
Name before toLowerCase() is called: Abigal Adjei
Name when toLowerCase() is called: abigal adjei
toUpperCase()
Converts all characters in this string to upper case.
Example
void main() {
String name = "Abigal Adjei";
print('Name before toUpperCase() is called: ${name}');
print('Name when toUpperCase() is called: ${name.toUpperCase()}');
}
Output
Name before toUpperCase() is called: Abigal Adjei
Name when toUpperCase() is called: ABIGAL ADJEI
trim()
Returns the string without any leading and trailing whitespace.
Example
void main() {
String fn = " Abigal Atwei ";
String ln = "Adjei";
print('Before trim() is called on fn: Full name - ${fn+ln}');
print('When trim() is called on fn: ${fn.trim()+ln}');
}
Output
Before trim() is called on fn: Full name - Abigal Atwei Adjei
When trim() is called on fn: Abigal AtweiAdjei
compareTo()
Compares this object to another.
Return Type
Returns an integer representing the relationship between two strings.
0 − when the strings are equal.
1 − when the first string is greater than the second
-1 − when the first string is smaller than the second
Example
void main() {
String fruit = "Mango";
String A = "A";
String B = "B";
String a = "a";
print("When ${fruit} compared to Orange:${fruit.compareTo("Orange")}");
print("When ${fruit} compared to orange:${fruit.compareTo("orange")}");
print("When ${fruit} compared to pear:${fruit.compareTo("pear")}");
print("When ${fruit} compared to Mango:${fruit.compareTo("Mango")}");
print("When ${fruit} compared to mAnGo:${fruit.compareTo("mAnGo")}");
print("When ${B} compared to ${A}:${B.compareTo(A)}");
print("When ${a} compared to ${A}:${a.compareTo(A)}");
}
Output
When Mango compared to Orange:-1
When Mango compared to orange:-1
When Mango compared to pear:-1
When Mango compared to Mango:0
When Mango compared to mAnGo:-1
When B compared to A:1
When a compared to A:1
replaceAll()
Replaces all substrings that match the specified pattern with a given value.
Example
void main(){
String text = "My name is Adjei. Adjei is a name of a person in Ghana";
print("Text before replaceAll is called:${text}");
print("Text when replaceAll('Adjei','Ama') is called: ${text.replaceAll('Adjei','Ama')}");
}
Output
Text before replaceAll is called:My name is Adjei. Adjei is a name of a person in Ghana
Text when replaceAll('Adjei','Ama') is called: My name is Ama. Ama is a name of a person in Ghana
split()
Splits the string at matches of the specified delimiter and returns a list of substrings.
Example
void main(){
String date = "2020-07-31";
print("When split by the pattern - is ${date.split("-")}");
}
Output
When split by the pattern - is [2020, 07, 31]
substring()
Returns the substring of this string that extends from start Index, inclusive, to end Index, exclusive.
Example
void main(){
String text = "I am a text";
print("When part of the text is extracted ${text.substring(0,4)}");
print("When part of the text is extracted ${text.substring(5,8)}");
}
Output
When part of the text is extracted I am
When part of the text is extracted a t
toString()
Returns a string representation of this object.
Example
void main(){
int age = 12;
print("You are ${age.toString()} years old");
}
Output
You are 12 years old
List
If you know other programming languages you may had come across an Array. Dart programming represents an array in a form of a
list. A List is simply an ordered group of objects. The dart:core library provides the List class that enables creation and manipulation of lists.
Figure: A List
The position of each of the content is known as index and the content is known as an element
The list position starts from 0. Hence the last index of a list is 1 less than the size of the list.
Thus:
last index = size of list - 1
As you can see the size of the list (array) above is 10. Hence the last index will be:
last index = 10 - 1 = 9
Lists classifications
Fixed Length List
A fixed length list cannot change at runtime. The programmer specifies the length(size) of the list at the time of declaration.
Syntax
var list_name = new List(size_of_the_list);
Examples
var names = new List(4);
var ages = new List(20);
Assigning value to list index
list_name[index] = value;
Using the names list example above, we could write
names[0] = "Kofi Agyenum";
names[1] = "Adjei Mensah";
names[2] = "Davida Agbedo";
names[3] = "Joseph Anum";
It is illegal to write:
names[4], names[5] etc because our list is of the size 4 which ends at index 3, thus last index = 4 - 1 = 3. Hence any index more than 3 is illegal.
Growable List
A growable list's length can change at run-time. Thus the size is unlimited. You declare a list as growable if you don't know how many elements will the list contain.
Syntax
var list_name = [value_1,value_2,value_3];
or
var list_name = new List();
You can add new element(s) to the growable list by using the add() method.
NOTE: You can't use list_name[index] = value for a growable list.
You can access the value of the element in the list by using the index of the list.
Thus value = list_name[index]
You can use the length method to get the size of growable list.
The size of the list will be nameOfList.length
You can use a for loop to loop through each index of the list as shown below:
Examples
void main(){
var names = new List(3);
/*
names.add("Kofo Agyenum");
names.add("Atwei Adjetey");
*/
names[0] = "Kofo Agyenum";
names[1] = "Atwei Adjetey";
names[2] = "Etonam Adjovi";
print("*********** Names ****************");
for(int i=0;i<names.length;i++){
print(names[i]);
}
print("Growable List Method 1");
var ages = [10,11];
print("Adding new value to list");
ages.add(23);
print("*********** Ages ****************");
for(int i=0;i<ages.length;i++){
print(ages[i]);
}
print("Growable List Method 2");
var courses = new List();
courses.add("Maths");
courses.add("English");
courses.add("Science");
print("*********** Courses ****************");
for(int i=0;i<courses.length;i++){
print(courses[i]);
}
}
Output
*********** Names ****************
Kofo Agyenum
Atwei Adjetey
Etonam Adjovi
Growable List Method 1
Adding new value to list
*********** Ages ****************
10
11
23
Growable List Method 2
*********** Courses ****************
Maths
English
Science
Example
Write a program which asks a user to enter favorite fruits. The user should enter q when he wants to quit entering or any other letter to continue entering. Store the entered fruits in a list and show the content after a user enters q
Code
// importing dart:io file
import 'dart:io';
void main(){
var fruits = new List();
String q = "c";
while(q.toLowerCase() !="q"){
print("Enter your favorite fruit");
String fruit = stdin.readLineSync();
fruits.add(fruit);
print("Enter q to quit or any other letter to add more");
q= stdin.readLineSync();
}
//Print out the content of the list
print("********* Your favorite fruits ***********");
for(int i=0;i<fruits.length;i++){
print(fruits[i]);
}
}
Output
Enter your favorite fruit
Apple
Enter q to quit or any other letter to add more
c
Enter your favorite fruit
Mango
Enter q to quit or any other letter to add more
c
Enter your favorite fruit
Pineapple
Enter q to quit or any other letter to add more
q
********* Your favorite fruits***********
Apple
Mango
Pineapple
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 case. |
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. |
Example
import 'dart:io';
void main(){
var fees = new List();
if(fees.isEmpty){
print("No one paid yesterday");
fees.add(1200);
fees.add(1000);
fees.add(800);
print("${fees.length} paid today");
print("First amount paid:${fees.first}");
print("Last amount paid:${fees.last}");
print("Reverse payment order");
print("First amount paid:${fees.reversed.first}");
print("Last amount paid:${fees.reversed.last}");
}
print("Test isNotEmpty Method");
var sick = new List();
sick.add("Kofi");
if(sick.isNotEmpty){
print("${sick.length} is(are) sick");
}
if(sick.length==1){
print("Only one person is sick and the student is ${sick.single}");
}
}
Output
No one paid yesterday
3 paid today
First amount paid:1200
Last amount paid:800
Reverse payment order
First amount paid:800
Last amount paid:1200
Test isNotEmpty Method
1 is(are) sick
Only one person is sick and the student is Kofi
Updating List
Replacing by range
List.replaceRange(int start_index,int end_index,Iterable )
Where,
Start_index − an integer representing the index position to start replacing.
End_index − an integer representing the index position to stop replacing.
− an iterable object that represents the updated values.
Example
import 'dart:io';
void main(){
var fees = new List();
fees.add(1000);
fees.add(800);
fees.add(1500);
fees.add(700);
fees.replaceRange(1,2,[1400,800]);
print("Fees amount at 1 is :${fees[1]}");
print("Fees amount at 2 is :${fees[2]}");
}
Outcome
Fees amount at 1 is :1400
Fees amount at 2 is :800
Replacing by index
To replace the element of an index, simply assign new value to that index like the way assignment is done for fixed list.
Thus:
list[index] = value;
Example
import 'dart:io';
void main(){
var fees = new List();
fees.add(1000);
fees.add(800);
fees.add(1500);
fees.add(700);
fees[1] = 1400;
fees[2] = 800;
print("Fees amount at 1 is :${fees[1]}");
print("Fees amount at 2 is :${fees[2]}");
}
Output
Fees amount at 1 is :1400
Fees amount at 2 is :800
Removing element from list
List.remove()
The List.remove() function removes the first occurrence of the specified item in the list. This function returns true if the specified value is removed from the list.
Syntax
List.remove(Object value)
Where,
value − represents the value of the item that should be removed from the list.
Example
import 'dart:io';
void main(){
var fees = new List();
fees.add(1000);
fees.add(800);
fees.add(1500);
fees.add(700);
fees.remove(700);
print(fees);
}
Output
[1000, 800, 1500]
List.removeAt()
The List.removeAt function removes the value at the specified index and returns it.
Syntax
List.removeAt(int index)
Where,
index − represents the index of the element that should be removed from the list.
Example
import 'dart:io';
void main(){
var fees = new List();
fees.add(1000);
fees.add(800);
fees.add(1500);
fees.add(700);
print("Starting list");
print(fees);
fees.remove(700);
print("After removing 700");
print(fees);
fees.removeAt(1);
print("After removing index 1");
print(fees);
}
Output
Starting list
[1000, 800, 1500, 700]
After removing 700
[1000, 800, 1500]
After removing index 1
[1000, 1500]
List.removeLast()
The List.removeLast() function removes the last element and returns the new list
Example
import 'dart:io';
void main(){
var fees = new List();
fees.add(1000);
fees.add(800);
fees.add(1500);
fees.add(700);
print("Before removing last element");
print(fees);
fees.removeLast();
print("After removing last element");
print(fees);
}
Output
Before removing last element
[1000, 800, 1500, 700]
After removing last element
[1000, 800, 1500]
List.removeRange()
The List.removeRange() function removes the items within the specified range.
List.removeRange(int start, int end)
Where,
Start − represents the starting position for removing the items.
End − represents the position in the list to stop removing the items.
Example
import 'dart:io';
void main(){
var fees = new List();
fees.add(1000);
fees.add(800);
fees.add(1500);
fees.add(700);
fees.add(750);
fees.add(900);
print("Before removing range from 1,4");
print(fees);
fees.removeRange(1,4);
print("After removing");
print(fees);
}
Output
Before removing range from 1,4
[1000, 800, 1500, 700, 750, 900]
After removing
[1000, 750, 900]
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
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 "{ }".
Thus
var identifier = { key1:value1, key2:value2,...,key_n:value_n}
Example
var login = {'username':'admin','password':'root'}
Declaring a Map using a Map Constructor
To declare a Map using a Map constructor, you have to follow two steps.
First, declare the map and second, initialize the map.
Thus:
var identifier = new Map()
Now, assign values to map keys
map_name[key] = value
Example
var login = new Map();
login['username'] = "admin";
login['password'] = "root";
Adding value to map
Syntax
identifier[key] = value;
Example
login['email'] = 'test@example.com';
Note − A map value can be any object including NULL.
Example
import 'dart:io';
void main(){
var login = {"username":"admin","password":"root"};
print("Map Content");
print(login);
print("Accessing content");
print("Username:${login['username']}");
print("Password:${login['password']}");
print("Adding new field");
login['email'] = "test@example.com";
print("Print new content");
print(login);
print("Constructor Method");
var details = new Map();
details['firstname'] = "Joseph";
details['lastname'] = "Mensah";
details['age'] = 20;
print(details);
print("Adding new field");
details['pic'] = "https://kuulchat.com/images/pic.jpg";
print("Print new content");
print(details);
}
Outcome
Map Content
{username: admin, password: root}
Accessing content
Username:admin
Password:root
Adding new field
Print new content
{username: admin, password: root, email: test@example.com}
Constructor Method
{firstname: Joseph, lastname: Mensah, age: 20}
Adding new field
Print new content
{firstname: Joseph, lastname: Mensah, age: 20, pic: https://kuulchat.com/images/pic.jpg}
Map – Properties
The Map class in the dart:core package defines the following properties −
Keys
Returns an iterable object representing keys
Values
Returns an iterable object representing values
Length
Returns the size of the Map
isEmpty
Returns true if the Map is an empty Map
isNotEmpty
Returns true if the Map is an empty Map
Example
import 'dart:io';
void main(){
var details = new Map();
details['firstname'] = "Joseph";
details['lastname'] = "Mensah";
details['age'] = 20;
print(details);
print("Adding new field");
details['pic'] = "https://kuulchat.com/images/pic.jpg";
print("Print new content");
print(details);
print("Map Properties");
print("Map keys");
print(details.keys);
print("Map values");
print(details.values);
print("Map Size");
print(details.length);
if(details.isNotEmpty){
print("Details map is not empty");
}
var emptyMap = new Map();
if(emptyMap.isEmpty){
print("Empty Map is empty");
}
}
Output
{firstname: Joseph, lastname: Mensah, age: 20}
Adding new field
Print new content
{firstname: Joseph, lastname: Mensah, age: 20, pic: https://kuulchat.com/images/pic.jpg}
Map Properties
Map keys
(firstname, lastname, age, pic)
Map values
(Joseph, Mensah, 20, https://kuulchat.com/images/pic.jpg)
Map Size
4
Details map is not empty
Empty Map is empty
Map - Functions
Following are the commonly used functions for manipulating Maps in Dart.
addAll()
Adds all key-value pairs of other to this map.
clear()
Removes all pairs from the map.
remove()
Removes key and its associated value, if present, from the map.
forEach()
Applies f to each key-value pair of the map.
Applies the specified function on every Map entry. In other words, forEach enables iterating through the Map’s entries.
Syntax
Map.forEach(void f(K key, V value));
Parameters
f(K key, V value) − Applies f to each key-value pair of the map.
Calling f must not add or remove keys from the map
Return Type − void.
Example
void main(){
var details = new Map();
details['firstname'] = "Joseph";
details['lastname'] = "Mensah";
details['age'] = 20;
print(details);
print("Adding new field");
details['pic'] = "https://kuulchat.com/images/pic.jpg";
print("Print new content");
print(details);
var address = new Map();
address['street'] = "12 B Mango Street";
address['town'] = "Teshie";
address['city'] = "Accra";
address['country'] = "Ghana";
print("Address Map");
print(address);
details.addAll(address);
print("After adding address to details");
print(details);
print("Remove country from details");
details.remove("country");
print("After removing country from details");
print(details);
print("Calling foreach to loop through each key and value");
details.forEach((k,v) => print('${k}: ${v}'));
print("Calling clear to clear all keys and values");
details.clear();
print("After clearing details map");
print(details);
}
Output
{firstname: Joseph, lastname: Mensah, age: 20}
Adding new field
Print new content
{firstname: Joseph, lastname: Mensah, age: 20, pic: https://kuulchat.com/images/pic.jpg}
Address Map
{street: 12 B Mango Street, town: Teshie, city: Accra, country: Ghana}
After adding address to details
{firstname: Joseph, lastname: Mensah, age: 20, pic: https://kuulchat.com/images/pic.jpg, street: 12 B Mango Street, town: Teshie, city: Accra, country: Ghana}
Remove country from details
After removing country from details
{firstname: Joseph, lastname: Mensah, age: 20, pic: https://kuulchat.com/images/pic.jpg, street: 12 B Mango Street, town: Teshie, city: Accra}
Calling foreach to loop through each key and value
firstname: Joseph
lastname: Mensah
age: 20
pic: https://kuulchat.com/images/pic.jpg
street: 12 B Mango Street
town: Teshie
city: Accra
Calling clear to clear all keys and values
After clearing details map
{}