MOBILE PROGRAMMING
Chapitre II : Programming with Flutter
I. Introduction to Dart
Dart is a client-optimized, object-oriented, modern programming language to build
apps fast for many platforms like android, iOS, web, desktop, etc. Client optimized means
optimized for crafting a beautiful user interface and high-quality experiences. Google
developed Dart as a programming language. If you know languages
like C, Java, C#, Javascript, etc. Dart will be easy for you. Below is a simple dart program that
prints Hello World on screen.
void main() {
print("Hello World!");
}
• void main() is the starting point where the execution of your program begins.
• The curly braces {} represent the beginning and the ending of a block of code.
• print(“Hello World!”); prints Hello World! on screen.
• Each code statement must end with a semicolon
II. Dart Data type
Data types help you to categorize all the different types of data you use in your code. it
specifies what type of value will be stored by the variable. Each variable has its data type. Dart
supports the following built-in data types:
• Numbers (int, double)
• Strings (String)
• Booleans (bool)
• Records ((value1, value2))
• Lists (List, also known as arrays)
• Sets (Set)
• Maps (Map)
• Runes (Runes; often replaced by the characters API)
• Symbols (Symbol)
• The value null (Null)
Mr. NZE FOMEKONG 1
MOBILE PROGRAMMING
Because every variable in Dart refers to an object (an instance of a class) you can usually
use constructors to initialize variables. Some of the built-in types have their own constructors.
For example, you can use the Map() constructor to create a map.
A. Numbers
Dart numbers come in two flavors:
int: Integer values no larger than 64 bits, depending on the platform. On native platforms,
values can be from -263 to 263 - 1. On the web, integer values are represented as JavaScript
numbers (64-bit floating-point values with no fractional part) and can be from -253 to 253 - 1.
Integers are numbers without a decimal point. Example:
int x = 1;
int hex = 0xDEADBEEF;
double: 64-bit (double-precision) floating-point numbers, as specified by the IEEE 754
standard. If a number includes a decimal, it is a double. Example:
double y = 1.1;
double exponents = 1.42e5;
Both int and double are subtypes of num. The num type includes basic operators such as +, -,
/, and *, and is also where you’ll find abs(), ceil(), and floor(), among other methods.
B. Strings
A Dart string (String object) holds a sequence of UTF-16 code units. String helps you to
store text data. You can store values like IAI IS THE BEST in String. You can use either
single or double quotes to create a string:
void main() {
String schoolName = "IAI-CAMEROUN";
String address = "Yaounde,awae-Nkolanga";
print("School name is $schoolName and address is $address");
}
Mr. NZE FOMEKONG 2
MOBILE PROGRAMMING
C. Booleans
In Dart, boolean holds either true or false value. You can write the bool keyword to define
the boolean data type.
void main() {
bool isConnected = false;
print("Device Status: $isConnected ");
}
D. Lists
The list holds multiple values in a single variable. It is also called arrays. If you want to
store multiple values without creating multiple variables, you can use a list.
void main() {
List<String> schools = ["IAI", "IFTIC", "ISIC"];
print("Value of schools is $ schools ");
print("Value of schools [0] is ${ schools [0]}"); // index 0
print("Value of schools [1] is ${ schools [1]}"); // index 1
print("Value of schools [2] is ${ schools [2]}"); // index 2
// Finding Length of List
int length = schools.length;
print("The Length of schools is $length");
}
E. Sets
A set in Dart is an unordered collection of unique items. Dart support for sets is provided
by set literals and the Set type.
Mr. NZE FOMEKONG 3
MOBILE PROGRAMMING
Here is a simple Dart set, created using a set literal:
void main() {
Set<String> weekday = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
print(weekday);
}
To create an empty set, use {} preceded by a type argument, or assign {} to a variable of
type Set:
Set<String> months = <String>{};
F. Maps
In general, a map is an object that associates keys and values. Both keys and values can
be any type of object. Each key occurs only once, but you can use the same value multiple
times. Dart support for maps is provided by map literals and the Map type.
void main() {
Map<String, String> myDetails = {
'name': 'Steph',
'email': ''[email protected]”,
'password': 'ty7gCtt0'
};
print(myDetails['name']);
}
Mr. NZE FOMEKONG 4
MOBILE PROGRAMMING
III. Dart Variables and functions
A. Variables
Variables are containers used to store value in the program. There are different types of
variables where you can keep different kinds of values. Here is the syntax used for creating a
variable and initializing it.
type variableName = value;
Example:
// here variable age contains value 15.
int age = 15;
Rules For Creating Variables In Dart
• Variable names are case sensitive, i.e., a and A are different.
• A variable name can consist of letters and numbers.
• A variable name cannot start with a number.
• Keywords are not allowed to be used as a variable name.
• Blank spaces are not allowed in a variable name.
• Special characters are not allowed except for the underscore (_) and the dollar ($) sign.
Naming Convention For Variables In Dart
It is a good habit to follow the naming convention. In Dart Variables, the variable name should
start with lower-case, and every second word’s first letter will be upper-case like num1,
fullName, isMarried, etc. Technically, this naming convention is called lowerCamelCase.
B. Functions
Functions are the block of code that performs a specific task. They are created when
some statements are repeatedly occurring in the program. The function helps reusability of the
code in the program.
Mr. NZE FOMEKONG 5
MOBILE PROGRAMMING
returntype functionName(parameter1,parameter2, ...){
// function body
}
Return type: It tells you the function output type. It can be void, String, int, double, etc. If the
function doesn’t return anything, you can use void as the return type.
Function Name: You can name functions by almost any name. Always follow a
lowerCamelCase naming convention like void updateName().
Parameters: Parameters are the input to the function, which you can write inside the bracket
().
Example:
// Here value is a parameter
void displayText(String value){
print($value);
}
void main(){
String text = “HELLO WORLD”;
// Here text is an argument
displayText (text);
}
Ø Named Parameter In Dart
Dart allows you to use named parameters to clarify the parameter’s meaning in function
calls. Curly braces {} are used to specify named parameters.
Mr. NZE FOMEKONG 6
MOBILE PROGRAMMING
// Here value is a parameter
void displayText({String value}){
print($value);
}
void main(){
String text = “HELLO WORLD”;
// Here text is an argument
displayText (value: text);
}
Ø Optional Parameter In Dart
Dart allows you to use optional parameters to make the parameter optional in function
calls. Square braces [] are used to specify optional parameters.
// Here value is a parameter
void displayText(String value,[String? value1]){
print(“$value $value1”);
}
void main(){
String text = “HELLO WORLD”;
// Here text is an argument
displayText (text);
displayText (text,”good”);
}
Mr. NZE FOMEKONG 7
MOBILE PROGRAMMING
Ø Anonymous Function In Dart
But not every function needs a name. If you remove the return type and the function name, the
function is called anonymous function.
Syntax
(parameterList){
// statements
}
Example:
void main() {
// Anonymous function
var cube = (int number) {
return number * number * number;
};
print("The cube of 2 is ${cube(2)}");
print("The cube of 3 is ${cube(3)}");
}
Ø Arrow Function In Dart
Dart has a special syntax for the function body, which is only one line. The arrow function is
represented by => symbol. It is a shorthand syntax for any function that has only one
expression.
Syntax
returnType functionName(parameters...) => expression;
Example:
double calculateInterest(double principal, double rate, double time) =>
principal * rate * time / 100;
Mr. NZE FOMEKONG 8
MOBILE PROGRAMMING
IV. Dart Comments
Comments are the set of statements that are ignored by the dart compiler during
program execution. They are used to explain the code so that you or other people can
understand it easily.
Types Of Comments
• Single-Line Comment: For commenting on a single line of code.
void main() {
// This is single-line comment.
print("Welcome to Technology Channel.");
}
• Multi-Line Comment: For commenting on multiple lines of code.
void main(){
/*
This is a multi-line comment.
*/
print("Welcome to Technology Channel.");
}
• Documentation Comment: For generating documentation or reference for a
project/software package. Documentation comments are helpful when you are writing
documentation for your code. Documentation comments start with /// in dart.
void main(){
/// This is documentation comment
print("Welcome to Technology Channel.");
}
Mr. NZE FOMEKONG 9
MOBILE PROGRAMMING
V. Decision making and loops
A. Decision making
Here we will talk of the if and switch.
1. If statement
The easy and most common way of controlling the flow of a program is through the use of an if
statement. If statement allow us to execute a code block when the given condition is true.
Conditions evaluate boolean values.
Syntax:
if(condition) {
Statement 1;
Statement 2;
.
.
Statement n;
}
Example
void main(){
var age = 20;
if(age >= 18){
print("You are voter.");
}
}
Ø If-Else Condition
If the result of the condition is true, then the body of the if-condition is executed. Otherwise,
the body of the else-condition is executed.
Syntax:
Mr. NZE FOMEKONG 10
MOBILE PROGRAMMING
if(condition){
statements;
}else{
statements;
}
Ø If-Else-If Condition
When you have multiple if conditions, then you can use if-else-if else in dart.
if(condition1){
statements1;
}else if(condition2){
statements2;
}else if(condition3){
statements3;
}
.
.
.
else(conditionN){
statementsN;
}
Mr. NZE FOMEKONG 11
MOBILE PROGRAMMING
2. Switch statement
A Switch case is used to execute the code block based on the condition.
Syntax:
switch(expression) {
case value1:
// statements
break;
case value2:
// statements
break;
default:
// default statements
}
How does switch-case statement work in dart
• The expression is evaluated once and compared with each case value.
• If expression matches with case value1, the statements of case value1 are executed.
Similarly, case value 2 will be executed if the expression matches case value2.
• The break keywords tell dart to exit the switch statement because the statements in the
case block are finished.
• If there is no match, default statements are executed.
Note: You can use a Switch case as an alternative to the if-else-if condition.
B. loops
In Programming, loops are used to repeat a block of code until certain conditions are
met. e.g., if you want to print your name 100 times, then rather than typing print(“your name”);
100 times, you can use a loop.
1. For Loop
Mr. NZE FOMEKONG 12
MOBILE PROGRAMMING
This is the most common type of loop. You can use for loop to run a code block multiple
times according to the condition. The syntax of for loop is:
for(initialization; condition; expression){
statements;
}
• Initialization is executed (one time) before the execution of the code block.
• Condition defines the condition for executing the code block.
• expression is executed (every time) after the code block has been executed
Example:
void main() {
for (int i = 0; i < 10; i++) {
print("John Doe");
}
}
2. For Each Loop
The for each loop iterates over all list elements or variables. It is useful when you want to
loop through list/collection. The syntax of for-each loop is:
collection.forEach(void f(value));
Example:
void main(){
List<String> footballplayers=[‘eto\’o’,'Ronaldo','Messi','Neymar'];
footballplayers.forEach( (names)=>print(names));
}
3. While Loop
Mr. NZE FOMEKONG 13
MOBILE PROGRAMMING
In while loop, the loop’s body will run until condition is false. This loop checks conditions
on every iteration. If the condition is true, the code inside {} is executed, if the condition is
false, then the loop stops. The syntax is:
while(condition){
//statement(s);
// Increment (++) or Decrement (--) Operation;
}
Example:
void main() {
int i = 1;
while (i <= 10) {
print(i);
i++;
}
}
4. Do While Loop
Do while loop is used to run a block of code multiple times. The loop’s body will be executed
first, and then the condition is tested. The syntax of do while loop is:
do{
statement1;
statement2;
.
.
.
statementN;
}while(condition);
Mr. NZE FOMEKONG 14
MOBILE PROGRAMMING
Example:
void main() {
int i = 1;
do {
print(i);
i++;
} while (i <= 10);
}
VI. Continue and break
While working on loops, we need to skip some elements or terminate the loop immediately
without checking the condition. In such a situation, you can use the break and continue
statement.
A. Break Statement
Sometimes you will need to break out of the loop immediately without checking the
condition. You can do this using break statement. The break statement is used to exit a loop.
It stops the loop immediately, and the program’s control moves outside the loop.
Example:
void main() {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break;
}
print(i);
}
}
Mr. NZE FOMEKONG 15
MOBILE PROGRAMMING
B. Continue Statement
Sometimes you will need to skip an iteration for a specific condition. You can do this utilizing
continue statement. The continue statement skips the current iteration of a loop. It will bypass
the statement of the loop. It does not terminate the loop but rather continues with the next
iteration.
Example:
void main() {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
continue;
}
print(i);
}
}
VII. Final and const keyword
Dart is a versatile programming language known for its simplicity and strong typing system.
Two keywords, final and const, play a crucial role in Dart when it comes to declaring variables.
A. Final Variables
In Dart, a final variable represents a single-assignment variable. Once assigned a value, you
cannot change it. Here's how you declare a final variable:
final String appName = "MyApp";
B. Const Variables
On the other hand, const variables are compile-time constants. They are essentially values that
are known at compile time and cannot change during runtime. You declare a const variable like
this:
const double piValue = 3.14159;
Mr. NZE FOMEKONG 16
MOBILE PROGRAMMING
G. Differences between Final and Const
1. Assignment Time:
- final: You can assign a value to a final variable at runtime, but once assigned, it cannot be
changed.
- const: const variables must be assigned a value at compile time and cannot be changed at
runtime.
2. Use Cases:
- final: Use final when you need a variable that cannot be reassigned but can be calculated at
runtime. For example, defining constants that are computed based on user input or system
parameters.
- const: Use const for values that are known at compile time, like mathematical constants (e.g.,
π), string literals, and instances of classes that have a const constructor. This helps improve
performance as the value is determined at compile time and doesn't change during execution.
3. Performance:
- final: final variables have slightly lower overhead compared to const because their values are
determined at runtime and can change once.
- const: const variables are evaluated at compile time and are more efficient in terms of
performance.
VIII. Object Oriented Programming
Object-oriented programming (OOP) is a programming method that uses objects and their
interactions to design and program applications. It is one of the most popular programming
paradigms and is used in many programming languages, such as Dart, Java, C++, Python, etc.
Mr. NZE FOMEKONG 17
MOBILE PROGRAMMING
In OOP, an object can be anything, such as a person, a bank account, a car, or a house. Each
object has its attributes (or properties) and behavior (or methods). For example, a person object
may have the attributes name, age and height, and the behavior walk and talk.
A. Class In Dart
In object-oriented programming, a class is a blueprint for creating objects. A class defines
the properties and methods that an object will have. For example, a class called Dog might
have properties like breed, color and methods like bark, run.
Declaring Class In Dart
You can declare a class in dart using the class keyword followed by class name and braces {}.
It’s a good habit to write class name in PascalCase. For
example, Employee, Student, QuizBrain, etc.
Syntax
class ClassName {
// properties or fields
// methods or functions
}
B. Object In Dart
In object-oriented programming, an object is a self-contained unit of code and data. Objects
are created from templates called classes. An object is made up of properties(variables) and
methods(functions). An object is an instance of a class.
Instantiation
In object-oriented programming, instantiation is the process of creating an instance of a class.
In other words, you can say that instantiation is the process of creating an object of a class. For
example, if you have a class called Bicycle, then you can create an object of the class
called bicycle.
Syntax
ClassName objectName = ClassName();
Mr. NZE FOMEKONG 18
MOBILE PROGRAMMING
C. Constructor In Dart
A constructor is a special method used to initialize an object. It is called automatically
when an object is created, and it can be used to set the initial values for the object’s properties.
For example, the following code creates a Person class object and sets the initial values for
the name and age properties.
class ClassName {
// Constructor declaration: Same as class name
ClassName() {
// body of the constructor
}
}
1. Named Constructor In Dart
In most programming languages like java, c++, c#, etc., we can create multiple constructors
with the same name. But in Dart, this is not possible. Well, there is a way. We can create
multiple constructors with the same name using named constructors.
class Mobile {
String? name;
String? color;
int? prize;
Mobile(this.name, this.color, this.prize);
Mobile.namedConstructor(this.name, this.color, [this.prize = 0]);
void displayMobileDetails() {
print("Mobile name: $name.");
print("Mobile color: $color.");
print("Mobile prize: $prize");
}
}
void main() {
var mobile1 = Mobile("Samsung", "Black", 20000);
var mobile2 = Mobile.namedConstructor("Apple", "White");
}
Mr. NZE FOMEKONG 19
MOBILE PROGRAMMING
2. Constant Constructor In Dart
Constant constructor is a constructor that creates a constant object. A constant object is an
object whose value cannot be changed. A constant constructor is declared using the
keyword const.
Rule For Declaring Constant Constructor In Dart
• All properties of the class must be final.
• It does not have any body.
• Only class containing const constructor is initialized using the const keyword.
class Student {
final String? name;
final int? age;
final int? rollNumber;
// Constant Constructor
const Student({this.name, this.age, this.rollNumber});
}
void main() {
// Here student is object of Student.
const Student student = Student(name: "John", age: 20, rollNumber: 1);
print("Name: ${student.name}");
print("Age: ${student.age}");
print("Roll Number: ${student.rollNumber}");
}
Mr. NZE FOMEKONG 20