Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
208 views

Module 1 Introduction and Dart Programming

This document provides an overview of a mobile application development course using Flutter. The course covers: 1) Introduction to Flutter development tools and the Dart programming language 2) Creating user interfaces with Flutter widgets 3) Navigation between multiple screens 4) State management patterns in Flutter applications 5) Integrating Flutter apps with Firebase services The intended outcomes are for students to be able to use Flutter tools on macOS and Windows, understand Flutter architecture and widgets, make API calls and use Firebase features in their Flutter apps.

Uploaded by

trex revx
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
208 views

Module 1 Introduction and Dart Programming

This document provides an overview of a mobile application development course using Flutter. The course covers: 1) Introduction to Flutter development tools and the Dart programming language 2) Creating user interfaces with Flutter widgets 3) Navigation between multiple screens 4) State management patterns in Flutter applications 5) Integrating Flutter apps with Firebase services The intended outcomes are for students to be able to use Flutter tools on macOS and Windows, understand Flutter architecture and widgets, make API calls and use Firebase features in their Flutter apps.

Uploaded by

trex revx
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 282

Mobile Application

Development:
Flutter

Prof. Pradnya Bhangale


Course Overview
Syllabus Overview
1. Introduction to development with flutter
• Flutter Architecture
• Setting up Development Environment
• Dart Programming Language
2. Creating UI with Flutter
• Understanding Widgets (default project structure, Flutter
Basic Layouts, Adding custom images, fonts )
• TextFields, Buttons, Material App, Drawer, Navigation Bar,
Floating Action button, Snack bar, Handling user input
• Forms and validation with Flutter
Syllabus Overview
3. Navigation and multiple screens
• Named Routes & Passing Data With Named Routes, Screens &
Navigation
4. State Management
• What is State and How do we Manage it
• Flutter App Architecture Patterns
• Advanced Flutter Architecture – The Bloc Pattern
5. Integrating flutter apps with firebase
• Firebase console, Firebase services: Authentication, Realtime
Database.
• HTTP Requests with Flutter Photos API
• Working with JSON, The HTTP Package
Course Outcomes
• At the end of successful completion of the course the
student will be able to
CO1: Use development tools that support both mac OS and Windows.
CO2: Understand Flutter, Dart and the concept behind widgets
CO3: To make asynchronous API calls, store and retrieve data from a
remote server, and use the JSON format for server communication.
CO4: Firebase Database, Firebase Authentication integration for
Flutter App Firebase Authentication for our Flutter App to safely
handle changes to Firebase.
Introduction
• Mobile App Development
• Creation of software intended to run on mobile devices
• Optimized to take advantage of those products unique features
and hardware

• Creation of Mobile Applications


• Uses traditional software development
• Software intended to utilize the unique features and
hardware of mobile devices
• Developing Gaming applications
Mobile App Development Process
Idea

Design

Development

Testing

Launch

Marketing
Types of Mobile app development

 Native
 Web
 Hybrid

10
Native Apps
12
13
14
15
`

16
17
18
19
20
21
Web Apps
23
24
25
Comparing Native Apps with Web Apps

26
28
What is Flutter?
• Flutter is a free and open-source mobile UI framework
created by Google and released in May 2017
• Allows you to create a native mobile application with only one
codebase.
Use one programming language and one codebase to create
two different apps (for iOS and Android)

• To develop with Flutter, you will use a programming language


called Dart.
• The language was created by Google in October 2011
• Dart focuses on front-end development, and you can use it to
create mobile and web applications.
What is Flutter?(contd..)
• Flutter consists of two important parts:
• An SDK (Software Development Kit):
• A collection of tools that are going to help you develop
your applications.
• This includes tools to compile your code into native
machine code (code for iOS and Android).

• A Framework (UI Library based on widgets):


• A collection of reusable UI elements (buttons, text
inputs, sliders, and so on) that you can personalize for
your own needs
Flutter: Key Features
• Simple to learn and use
• Create a real native application without a bunch of code
• Quick compilation: maximum productivity
• Change your code and see the results in real-time termed as Hot-
Reload
• Ideal for startup MVPs
• Cheaper to develop a mobile application with Flutter because you
don’t need to create and maintain two mobile apps
• It’s performant – you won't notice the difference between a
native application and a Flutter app.
• It’s beautiful – you can easily use widgets provided by Flutter and
personalize it to create a valuable UI for your customers
Flutter: Key Features (contd..)
• Good documentation
• Flutter's documentation has everything is very detailed with easy
examples for basic use cases(https://flutter.dev/docs)
• A growing community
• Flutter has a robust community, and it’s only the
beginning!(https://flutter.dev/community)
• Supported by Android Studio and VS Code
• Android Studio is a complete software with everything already
integrated. You have to download Flutter and Dart plugins to
start.
• VS Code is a lightweight tool, and everything is configurable
through plugins from the marketplace.
Flutter Installation with Android Studio

• System requirements(minimum)
Operating System: Windows 7 SP1 or later (64-bit)
Disk Space: 400 Mb (Except disk space of IDE/tools)
RAM: 4 GB

Tools:
• Flutter depends on these tools being available in your environment
• Windows PowerShell
1. Get the Flutter SDK
• Step 1- Go to URL https://flutter.dev/docs/get-
started/install/windows and download the latest Flutter SDK.

• Step 2- Unzip the zip file and place the contained flutter in the
installation location for the Flutter SDK (For example,
C:/src/flutter; do not install Flutter in a directory like C:/Program
Files/ that requires relevant privileges).

• Step 3- Update your path


From the Start search bar, enter ‘env’ and select “Edit
environment variables for your account”.

• Under User variable check an entry called Path.


• Under Path click on the new tab and append the full path to
flutter/bin. (Your full path should be like C:/src/flutter/bin).
1. Get the Flutter SDK(update path of flutter SDK)
• Add path till C:/src/flutter/bin and click on ok off all windows
open and your path will be set
2. Android Setup
• Install Android Studio
• Download and install Android Studio
(https://developer.android.com/studio)
• Start Android Studio, and go through the ‘Android
Studio Setup Wizard’.
• This installs the latest Android SDK, Android SDK
Command-line Tools, and Android SDK Build-Tools,
which are required by Flutter when developing for
Android.
2. Android Setup(contd..)
• Install the Flutter and Dart plugins
1. Open Android Studio.
2. Click Configure>Plugins.
3. Select the Flutter plugin and click install.
4. Click yes when prompted to install the Dart plugin.
5. Restart Android Studio.
Flutter Installation with vscode
• Install VS Code
• VS Code is a light-weight editor with Flutter app execution and
debug support.
• https://code.visualstudio.com/download

• Install the Flutter and Dart plugins


• Start VS Code.
• Press Ctrl+Shift+x to go to Extensions and search for flutter.
• Click install and wait for the installation to be finished.
• Search for Dart and install the plugin.
• You might need to restart VS Code, just to make sure that both of
the extensions are installed.
Dart Plugin
Flutter Plugin
Dart Programming:
Basics
Outline
• Introduction to Dart
• Variables
• Collections
• Flow Control
• Functions
• Error Handling
Introduction to Dart
• Dart is an open-source, general-purpose, object-oriented
programming language with C-style syntax developed
by Google in 2011
• Dart is productive, fast, portable, approachable, and most of
all reactive.
• It supports most of the common concepts of programming
languages like classes, interfaces, functions
• Dart language does not support arrays directly.
It supports collection, which is used to replicate the data
structure such as arrays, generics, etc.
Dart Programming
• Pros of Dart
• Open-source
• Backed by Google and runs easily on Google Cloud Platform
• Dart is approximately two times faster than JavaScript
• Dart is type-safe and compiled with both AOT and JIT compilers

• Cons of Dart
• Dart is fairly new to the programmers and rarely used in the
market.
• Dart has very limited resources online and it's hard to find
solutions to problems.
Dart Basics: Variables
• Comments
• Booleans
• Numbers
• Strings
• Const Variables
Comments
• Help the readability of the code
• Used to describe the logic and dependencies of the app
• Non executable lines of code
• There are three types of comments:
• Single-line (add a short description) //…….
• Multiline (long descriptions that span multiple lines)/*….*/
• Documentation (fully document a piece of logic, usually
giving detailed explanations and sample code in the
comments /// []
Comments

Multiline comments
/*……..*/

Single Line
//
Variables
• Variables store references to a value
• Some of the built-in variable types are numbers, strings,
Booleans, lists, maps etc.
• You can use var to declare a variable without specifying the
type.
Dart infers the type of variable automatically
• Declaring the variable type makes for better code readability,
and it’s easier to know which type of value is expected.
Instead of using var, use the variable type expected:
double, String, and so on.
• An uninitialized variable has a value of null
• Use final or const keywords when the variable is not intended
to change the initial value
Declaring Variables
• In Dart, all variables are declared public (available to all) by
default
• Starting the variable name with an underscore (_), you can
declare it as private.
By declaring a variable private, you are saying it cannot
be accessed from outside classes/functions
• Note some built-in Dart variable types are lowercase like
double and some uppercase like String
• Use final keyword when the value is assigned at runtime
• Use const keyword when the value is known at compile time
(in code) and will not change at runtime.
Declaring Variables Rules
• Special characters are not allowed(@,&,#). There is an
exception for dollar sign($) and underscore (_)
• A keyword cannot be used as a variable name for example int ,
double cannot be used as a variable name.
• Variables are case sensitive
• First character of a variable should not be a digit and must
always be an alphabet.
• Blank spaces cannot be used
• A combination of numbers and alphabet can be used to name
a variable for example , name123 can be used as a variable
name.
Booleans
• 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
• bool var_name = false
Booleans
Booleans(contd..)

To retrieve(interpolate) value
stored in variable
{$var_name} or ${var_name}
Numbers
• Dart numbers can be classified as −
• int − Integer of arbitrary size used to represent whole
numbers.
• double − 64-bit (double-precision) floating-point numbers
used to represent fractional numbers
• The num type is inherited by the int and double types.
• The dart core library allows numerous operations on numeric
values.
• The syntax for declaring a number is as given below −
• int var_name; // declares an integer variable
• double var_name; // declares a double variable
Numbers(contd..)
Strings
• Declaring variables as String allows values to be entered as a
sequence of text characters.
• To add a single line of characters, you can use single or double
quotes like 'car' or "car".
Ex:
String defaultMenu = 'main';
String defaultMenu = “main”;

• To add multiline characters, use triple quotes, like "'car"'.


Ex:
String multilineAddress = '''
123 Any Street
City, State, Zip
''';
Strings(contd..)
• Strings can be concatenated (combined) by using the plus (+)
operator or by using adjacent single or double quotes.
Ex:
String combinedName = 'main' + ' ' + 'function';
String combinedNameNoPlusSign = 'main' ' ' 'function';
Strings
Strings(contd..)
Strings(contd..)
Const Variables
Collections
• Enum
• List
• Set
• Queue
• Map
Introduction: Collection
• Dart collections can be used to replicate data structures like
an array.

• The dart:core library and other classes


enable Collection support in Dart scripts
Enum
• An enumeration is used for defining named constant values
• An enumerated type is declared using the enum keyword
• Syntax
enum enum_name {
enumeration list
}
enum_name specifies the enumeration type name
enumeration list is a comma-separated list of identifiers
Enum
List
• Declaring variables as List (comparable to arrays) allows
multiple values to be entered
• List is an ordered group of objects.
• In programming, an array is an iterable (accessed
sequentially) collection of objects, with each element
accessible by the index position or a key.
To access elements, the List uses zero-based
indexing, where the first element index is at 0, and the last
element is at the List length (number of rows) minus 1
List(contd..)
• A List can be of fixed length or growable, depending on your
needs.
• By default, a List is created as growable by using List() or []
• To create a fixed-length List, you add the number of rows
required by using this format: List(25)
• Example:
// List Growable
List contacts = List();
// or
List contacts = [];
List contacts = ['Linda', 'John', 'Mary'];
// List fixed-length
List contact = List(25);
List(contd..)
Set
• Set is an unordered list of distinct values of same type
• Dart set are typed, once you declare type of set Dart infers all
elements of set to be of same data type
• Used when you want to hold distinct values of single data type
in a single variable and order of items is not important
• Add element into set:
set_name.add(<value>);
• To retrieve element at specific index:
set_name.elementAt(<index>);
Set (contd..)
• Set elements count:
set_name.length;

• Finding element in Set:


set_name.contains(<value>);

• Remove Set element:


set_name.remove(<value>);

• Remove all elements in Set:


set_name.clear();
Set(contd..)
• Similar to list but are unordered and do not contain duplicates
Queue
• A Queue is a collection that can be manipulated at both
ends.
• Queues are useful when you want to build a first-in, first-
out collection.
• Queue inserts data from one end and deletes from
another end.
• While using queue, it is required to import
“dart:collection” package for performing operations on
values stored in queue
Queue (contd..)
Map
• Map is an object that is used to represent a set of values as
key-value pairs
• In Map, key and value can be of any type of object(need not
be of same data type)
• In Map, each key can occur only once but same value can be
used multiple times
• Map can be defined using ({}) and values can be assigned and
accessed using ([])
Map (contd..)
Dart Operators(1)
Dart Operators(2)
Dart Operators(3)
Dart Operators(4)
Dart Operators(5)
Example: ternary operator
void main() {
var a = 25;
var res = a > 15 ? "value greater than 15" : "value lesser than or equal to 15";
print(res);
}

Output
value greater than 15
Flow Control
• Assert
• Selection Statements [If…else, Switch case]
• Iterations Statements [Loops: for, while,
do..while]
• Jump Statements [break, continue]
Flow Control
• Order in which instructions, statements and function calls
being executed or evaluated when a program is running
• In dart, statements inside code are generally executed
sequentially from top to bottom in order that they appear
• During program execution, you may execute or skip certain
set of instructions based on condition, jump to another
statement or execute a set of statement block repeatedly
Flow control statements are used to alter, redirect or
control flow of program execution based on application
logic
Assert
• Useful debugging tool, is used for testing boolean
conditions.
• An assert statement disrupt normal execution if a
boolean condition is false.
• If the boolean expression is true, then the code continues
to execute normally.
1. Selection Statements
• Allow you to control flow of program during the runtime on
the basis of outcome of an expression or state of a variable

• Referred to as decision making statements

• Evaluates single or multiple test expressions which result in


‘TRUE’ or ‘FALSE’

Outcome of expression determine which block of


statements to be executed
• In dart, following selection statements are available:
• If..else
• Switch case
If statement
• If Statement executes the statement block if and only if the
particular test condition is true.
If the test condition is False then the statement block is
skipped.
• Syntax in Dart:
If statement (contd..)
If statement (contd..)
If statement (contd..)
If…else
• If…else statement is similar to If Statement only additional
part is when the Test Condition is evaluated as False then it
executes another statement block
Unlike If Statement where the statement block will be
skipped if the test condition is evaluated as False.
• Syntax in Dart
If…else(contd..)
Nested if..else statement
Nested if…else(contd..)
Switch
• Switch Case Statement is used when
we have to evaluate a test condition
against multiple cases.
• The statement block of the particular
case which is evaluated as true is
executed.
• If all the case statements are
evaluated as False then the
statement block of the default case
will be executed.
Switch(contd..)
Switch(contd..)
Iterations Statements
• Used to execute block of code repeatedly for a specified
number of times or until it meets a specified condition

• Commonly known as loops or looping statements

• In dart, following iteration statements are available:

• for Loop (Definite Loop)

• while Loop ( Indefinite Loop)

• do..while Loop (Indefinte Loop)


for loop
• For Loop is a Definite Loop (One where the number of
iterations are constant) it checks for conditions specified and
used to execute the statements for a specified number of
times.
• The syntax in Dart is :
for loop(contd..)
forEach loop
while loop
• while Loop is a type of indefinite Loop which checks the test
expression based on a Boolean condition(True or False)
If the test expression is true it will execute the statement
block and it will evaluate again and again as long as the test
expression is true.
When the test expression is false it will exit from the loop
• Syntax while loop in dart:
while loop(contd..)
do..while loop
• do-while like while loop is a type of Indefinite Loop
• do-while loop executes the statement block once even if the
test expression or condition is false unlike while Loop which
does not execute statement block if the test expression is false
• Syntax for Do-While Loop:
do..while loop(contd..)
Jump Statements
• Used to alter or transfer the control to other section or
statements in your program from the current section
• In dart, following jump statements are available:
• Break statement
• Continue Statement
Break Statement
• Break statement is mainly used to terminate the execution of
that particular statement and transfers the control to the
following statement.
• It is mainly used in Switch case , Looping Statements and If
else statement
• Syntax:
Break Statement(contd..)
Continue Statement
• Continue statement is used mainly in Looping Statements and
Conditional Statements.
• It used when a particular iteration has to be skipped in a loop.
• It does not terminate or exit from the loop unlike break
statement which does when used.
• Syntax for Continue Statement:
Continue Statement(contd..)
Variable Scope
• Scope of variables is the lifetime of the variable
depending upon which a particular block of code is being
executed
• Variable scope can be decided using the type of
variables:
• Local Variable
• Global Variable
Variable Scope (contd..)
Local variable
• Variable type declared inside programming blocks(i.e., for loop, if
else, switch and many more) or functions.
• It can only be used inside that particular code of block or function in
which it is declared or defined.
Once that particular code of block or functions is executed, the
scope of a variable is finished or say that the local variable is destroyed
void main()
{
int x=1;
for(int i=0;i<2;i++)
{
print(i);
x++;
print(x); Output:
} 0213
}
Variable Scope (contd..) class Sample
{
int id=1;
String name=“abcdefg";
Global Variable: test()
• Global variables are defined {
print("Sample "+id.toString());
outside the function and used }
to access from anywhere. }
• The scope of global variable is
int a=10;
limited from the start of the
void main()
program to the end of the {
program. for(int i=0;i<2;i++)
{
print(i);
print(a);
}
Sample S=new Sample();
S.test();
}
Variable Scope (contd..)
Variable Scope (contd..)
Variable Scope (contd..)
Variable Scope (contd..)
Functions
• Basic functions
• Optional parameters
• Named parameters
• Anonymous Functions
• main () function
Function
• A function is a block of code that should be organized,
perform a single task, and should be related to the class we’re
working on.
• Function makes it easy to divide complete program into sub
units that perform a specific task for that program
• Advantages:
• Enhances modularity of program
• Enhances reusability
• Makes development easy as development can be shared in a
team
• Reduces duplication
Function(contd..)
Defining a function:
• A function must be defined prior to use else result into
compile time error
• Call to function cannot be made until it is defined
• In dart, function is defined as follows: int add(int n1, int n2)
return_type func_name (parameter_list) {
{
//Statement(s) int result;
return value; result = n1+n2;
} return result;
func_name : name of function }
parameter_list: list of parameters to pass when function call is made
return_type: return type of function which can be valid data type(void
keyword can be used when no return value)
Function(contd..)
Calling Function:
• In dart, once a function is defined, later you can invoke
or call this function inside main() function body
• Function can be invoked by its name with arguments list
if any
• Syntax:
fun_name(<argument_list>);
• Example:
add(10,20);
Function(contd..)
Passing arguments to the function:
• Number of values and data type of values passed must
match with number of parameters and data type of
parameters that are defined during function declaration
Function(contd..)
Return Value from Function:
• Sometimes we may want a function to return some value to
the point it where it is called from
• return keyword allows a function to return a value
• However, return statement is optional. If not specified
function returns null
• There can be only one return statement in function
• Syntax:
return <expression/value>;
Function(contd..)
• Complete function in action

void main(){
print("Dart Program To Add Two Numbers Using Function.");
var sum = add(10,20);
print("Sum Of Given No. Is : ${sum}");
}

int add(int n1, int n2){


int result;
result = n1+n2;
return result;
}
Basic Functions(contd..)
Basic Functions(contd..)
Basic Functions(contd..)
Basic Functions(contd..)
Basic Functions(contd..)
Optional Parameters
• In dart, we can set any parameter as optional; which
allows function with optional parameter(if any) to be
called/executed even if values for those parameters is
not being provided
• Optional parameters are declared after required
parameters of the function
• There are two types of optional parameters in dart:
• Optional positional parameter
• Optional named parameter
Optional positional parameter
• Can be specified by having individual parameter separated by
commas and enclosed within square [] bracket
• Calling a function having optional positional parameter defined
may specify variable number of arguments
• Syntax:
void function_name(param1, [optional_param_1,
optional_param_2]) { }
Optional positional parameter(contd..)
Optional positional parameter(contd.)
Optional positional parameter(contd.)
Optional Named Parameters
• Named positional parameters can be specified by having individual
parameter name separated by commas and enclosed within curly
brackets({})
• Syntax:
void function_name(param1, {optional_param1, optional_param2})
{}
• Calling a function having optional named parameter, individual
parameter name must be specified while value is being passed
• Syntax:
function_name(optional_param1:value,...);
Optional Named Parameters(contd..)
Optional Named Parameters(contd..)
Optional Named Parameters with
default values(contd..)
Optional Named Parameters with
default values(contd..)
Single-Line Functions
• Dart makes it possible to declare short functions more
compactly
• The syntax => is used for separating the return type, name,
and parameters of a single-line function from its
implementation
• As with regular functions, specifying the return type of a
single-line function is optional
Single-line functions do not use return statements.
Instead, the return value is implied
• The evaluated result of the expression on the right of the => is
the return value
Single-Line Functions(contd..)
Examples:
// just as valid as next version
• sayHello(String name) => print("Hello, $name");
// same as previous but with void
• void sayHello(String name) => print("Hello, $name");
// think of as return num1 * num 2;
• int multiply(int num1, int num2) => num1 * num2;
// return is implied
• int luckyNumber() => 7;

• Single-line functions are simply another way of defining the


same thing which is provided by the language for convenience
main function()
• Every dart program to have top-level main () function definition
• There can be only one main () function in dart program
• It serves as entry point for every dart program or app, execution of a
dart program or app start with main() function
• main() function is responsible for execution of all user defined
statements, functions and library functions
• main() function is further structured into variable declaration,
function declaration and user defined executable statements
• main() function return void and can have an optional parameter
List<String> as arguments
• Syntax:
void main() {
// main function body
}
Error Handling
• What is Exception and Exception Handling?
• How to handle Exceptions using:
• TRY
• CATCH
• ON
• FINALLY

• What is StackTrace?
• How to create our own exception handling class
Exception Handling
• Exception is a runtime unwanted event that disrupts the
flow of code execution or application crashes
It can be occurred because of programmer’s mistake
or by wrong user input.
• To handle such events at runtime is called Exception
Handling.
Types of Exceptions in Dart
Exception
try..catch..finally
• In Dart Exceptions can be handle via
Try: In the try block, we write the logical code that can produce
the exception
Catch: Catch block is written with try block to catch the general
exceptions: In other words, if it is not clear what kind of
exception will be produced. Catch block is used.
On: On block is used when it is 100% sure what kind of
exception will be thrown.
Finally: The finally part is always executed but it is not
mandatory.
try clause
Case 1: when you know exception to be thrown use On clause
try…catch clause
• Case 2: when you do not exception, use catch clause
try…catch clause
• Case 3: Using Stack Trace to know events occurred
before exception was thrown
try..catch..finally
• Case 4: Whether there is an exception or not, finally clause is
always executed
try..catch..finally
• Case 4: Whether there is an exception or not, finally clause is
always executed
Throwing Exception
• The throw keyword is used to explicitly raise an exception.
A raised exception should be handled to prevent the
program from exiting abruptly.
• The syntax for raising an exception explicitly is −
throw new Exception_name()
Throwing Exception
Throwing Exception
Custom Exceptions
• Every exception type in Dart is a subtype of the built-in
class Exception.
• Dart enables creating custom exceptions by extending the
existing ones.
• The syntax for defining a custom exception is as given below −
class Custom_exception_Name implements Exception
{ // can contain constructors, variables and methods }
Custom Exceptions(contd..)
Dart: Intermediate
• Dart is an object oriented programming language which
supports concepts like:
• Classes
• Scope
• Packages(Imports)
• Polymorphism
• Inheritance
• Generics
Classes
Dart Classes
• Dart is an object oriented programming language and
supports the concept of class, objects, interfaces, inheritance
etc.
• Class can be defined as blueprint or prototype of associated
objects
• Class is a wrapper that binds/encapsulates the data and
methods together, which can be later accessed by objects of
that class
Class can be user defined data type that describe
behavior and characteristics shared by all of its instances
• Once a class has been defined, we can create
objects(instances) of that class which has access to class
properties and methods
Dart Classes(contd..)
Declaring a Class in Dart
• In dart, class can be defined using class keyword followed by
class name; and class body enclosed by pair of curly braces {}

Fields

method
Dart Classes(contd..)
Creating Class objects in Dart
• Once class has been defined, we can create objects(instance)
of class which has access to class fields and function
• Syntax:
var objectName = new ClassName(<constructor_arguments>);

• Example:
var emp = new Employee();
Dart Classes(contd..)
Accessing Instance
class Employee {
Variables and Functions var empName;
• In dart, once instance of class var empAge;
is created, we can access var empSalary;
properties and methods of
class using property/method showEmpInfo(){
name separated by print("Employee Name Is : ${empName}");
print("Employee Age Is : ${empAge}");
dot(.)operator after instance
print("Employee Salary Is : ${empSalary}");
name
}
}
void main(){
var emp = new Employee();
emp.empName = "John";
emp.empAge = 30;
emp.empSalary = 45000;
print("Dart Access Class Property and Method");
emp.showEmpInfo();
}
Classes(1)

To create dart application in vscode


Classes(2)
Classes(3)
Classes(4){Multiple objects}
Class Constructor
• Special method that is used to initialize an object when it is
created
• Automatically called when an object is instantiated; to set
initial values for instance variables
• Has same name as of class it belongs to and has no explicit
return type
• Not mandatory to write constructor for class
Every class has default constructor which compiles and
assigns default values to all member variables
• If you define your own constructor then default constructor
will be ignored
Class Constructor(contd..)
Creating Constructors in Dart
• A constructor has same name as that of class and doesn't
return any value
Types of Constructor
• Following are constructor type available in dart:

1. Default Constructor or no-arg Constructor

2. Parameterized Constructor

3. Named Constructor
Default Constructor or no-arg Constructor
• As name specifies the constructor that has no parameters is
known as default constructor
• If you don’t create constructor for a class, compiler will
automatically create default constructor for the class
• If we create a constructor with no-arguments or arguments
then compiler will not create a default constructor
• Default constructor provide default values to member
variables
void main() {
Employee emp = new Employee();
}
class Employee{
Employee() {
print(“Default Constructor of Employee class ");
}
}
Default Constructor or no-arg Constructor(1)
Default Constructor or no-arg Constructor(2)
Parameterized Constructor
• Constructors can also take parameters which is used to
initialize instance variables
• A constructor that accepts parameter is called parameterized
constructor
• If we want to initialize instance variables with our own values,
then we are required to use parameterized constructor
void main() {
print("Dart Parameterized Constructor");
Employee emp = new Employee('EMP001');
}

class Employee{
Employee(String empCode) {
print(empCode);
}
}
Parameterized Constructor(1)
Parameterized Constructor(2)
Named Constructors
• In Dart, named constructor allows a class to define multiple
constructors void main() {

Employee emp1 = new Employee();


Employee emp2 = new
Employee.namedConst('EMP001');
}
class Employee{
Employee() {
print("Default Constructor Invoked");
}
Employee.namedConst(String empCode) {
print("Named Constructor Invoked");
print(empCode);
}
}
Named Constructor(1)
Named Constructor(2)
Dart this keyword
• this keyword represents an implicit object pointing to current
class object
• Refers to current instance of the class in a method or
constructor
• Mainly used to eliminate ambiguity between class attributes
and parameters with same name
Ambiguity is avoided by prefixing class attributes with
this keyword
• this keyword can be used to refer to any member of the
current object from within an instance method or constructor
Use of this keyword
this keyword(contd..)
Example
void main() {
Employee emp = new Employee('EMP001');
}

class Employee {
String emp_code;
Employee(String emp_code) {
this.emp_code = emp_code;
print("Dart this Keyword Example.");
print("The Employee Code is : ${emp_code}");
}
}
this keyword(contd..)
this keyword(contd..)

Output
Correct??
this keyword(contd..)
this keyword(contd..)
Variable Scope
Private and Public Variables
• Public variables
Variables that are visible to all classes

• Private variables
Variables that are visible only to the class to which they
belong
They are defined using underscore symbol(eg: int _age)
Private and Public Scope

Private variables
Private and Public Scope(contd..)
Private and Public Scope(contd..)
Private and Public Scope(private variable
modified)
Private and Public Scope(private method declared)
Private and Public Scope(private method
accessed)
Private and Public Scope(solution: private
method accessed through encapsulation)
Private and Public Scope(solution: private
method accessed through encapsulation)
Getters and Setters
• Getters and Setters are special class methods that is used to
initialize and retrieve the values of the class field respectively
• Setter method is used to initialize or set respective class fields
• Getter method is used to retrieve respective class fields
• All classes have default getter and setter method associated
with it
However, you are free to override default ones by
implementing getter and setter method explicitly
Default Getter and Setter
Custom Getters and Setters(contd..)
Custom Getters and Setters(contd..)
Custom Getters and Setters(contd..)
Static members
• Static keyword is used for memory management of global data
members
• Static keyword can be applied to fields and methods of a class
• Static variables and methods are part of class instead of
specific instance
• Static data members can be accessed without creating an
object of class
Simply put class_name before static variable or method
name to use them
Static members(contd..)
Static Variables
• Belongs to class instead of specific instance(objects)
• It is common to all instances of class
• Memory allocation to static variable happen only once in class
area at time of class loading
Static members(contd..)
Static Members(contd..)
Static Members(contd..)
Static Members(contd..)
Static Members(contd..)
Static Members(contd..)
Static Method
• Static method belong to class instead of class instances
• Static method is allowed to access static variables of class
and can invoke only static methods of the class
Static Members(contd..)
Static Members(contd..)
Packages
Dart Packages
• Set of dart program organized in an independent,
reusable unit

• Contain set of functions and classes for specific purpose


or utility along with compiled code and sample data

• Dart has rich set of default packages, loaded


automatically when dart console is started

• Any other package then default needs to be installed and


loaded explicitly first in order to use it
Dart Package Manager
• Dart has an inbuilt package manager known as pub package manager
• Used to install, organize and manage third party libraries, tools and
dependencies
• Every dart application has an pubspec.yaml file (track of all third
party libraries and application dependencies along with metadata of
application like application name, author, version and description)
• Most of dart IDEs have built in support for using pub that includes
creating, downloading, updating and publishing packages
Dart Package Manager(contd..)
• Installing a package:
• Add package name in dependency section of your projects
pubspec.yaml file.
• Run following command from your application directory to get
package installed in your project
>> pub get
Dart Package Manager(contd..)
Importing libraries from package:
• Once package is installed in our project, we need to
import required libraries from package in our project as:
import 'package:xml/xml.dart' as xml;
Polymorphism
• Derived from 2 greek words “poly” and “morph” where
poly means many and morph means form.
• Polymorphism means an object have different forms and
each different form performs same action/task in
multiple/different ways( speaking different languages)
• Inheritance
• Abstraction
• Interfaces
• Mixins
Inheritance
Inheritance
• The capability of a class to derive properties and
characteristics from another class is called Inheritance
It is ability of a program to create new class from an
existing class
• Parent Class
The class whose properties are inherited by child class is
called Parent Class. Parent class is also known as base
class or super class.
• Child Class
The class that inherits properties from another class is
called child class. Child class is also known as derived
class or base class.
Inheritance (contd..)

Inheritance
Inheritance (contd..)
• Syntax:
class child_class extends parent_class {
//body of child class
}

Child class inherits all the properties and methods except


constructor from parent class
Types of Inheritance
Mainly there are three types of inheritance:
• Single
• Multiple - Dart doesn’t support Multiple Inheritance
• Multi-level
Single Level Inheritance
Multi Level Inheritance
Inheritance(contd..)
Inheritance
Super keyword
• super keyword is a reference variable which is used to
refer immediate parent class object
• Using super keyword, we can access super class
properties and methods
• Instances of child class can refer to properties and
methods of super class using super keyword
• Use: to eliminate ambiguity between super class and sub
class that have variables and methods with same name
Super keyword(contd..)
Method overriding
• Declaring a method in sub class which already exist in parent
class with same name, same arguments, same return type is
termed as method overriding
Sub class provides its own implementation for the
method which already exist in super class

• Method defined in super class is called overridden method


and the method in subclass is called as overriding method
Method overriding(contd..)
Inheritance(contd..)
Inheritance(contd..){Method overriding}
Abstraction
Abstraction
• Real life example: ATM Machine
• Any class that contains one or more abstract methods is
known as abstract class which declared abstract using
“abstract” keyword followed by class declaration
• A class declared as abstract may or may not include
abstract methods
• An abstract class cannot be instantiated
• Abstract class only be extended where subclass needs to
provide implementation for all abstract methods from
super class
If subclass doesn't implement abstract methods
then it should also be declared as abstract
Abstraction(contd..)
Abstraction(contd..)
Abstraction(contd..)
Interfaces
Interfaces
• Blueprint of a class, that any class entity must adhere to
• Declares set of methods available on an object
• Contain only method signature, it does not provide
implementation details of method
• Class that uses interface needs to use implements keyword
to use interface method
Class must provide complete implementation details
for all methods that belong to interface
Interface(contd..)
Interface(contd..)
Interface(contd..)
Interface(contd..)
Interface(contd..)
Interface(contd..)
Interface(contd..)
Mixins
(Multiple Inheritance)
Mixins
• In object-oriented programming languages, a Mixin is a class
that contains methods for use by other classes without having
to be the parent class of those other classes
• Normal classes from which we can borrow methods(or
variables) from without extending the class
• In dart we can do this by using the keyword with
• A class that is providing a mixin must
• Have no declared constructors
• Not be a subclass of anything other than Object (no
extends)
• Make no calls using super
Mixins(contd..)
• Mixins enables a
programming language
to mimic an benefit
from features such as
• multiple inheritance
• code reuse
• reducing the risk of
running into
problems such as
the Deadly Diamond
of Death(DDD).
Mixins(contd..)
1

2 3

Output???
Mixins(contd..)

Output: from Singer Class {“lalaaa…lalaaa…lalaaa..”}


Mixins(contd..)
Mixins(contd..)
Mixins(contd..)

If this class contains any identical methods to mixins or super class then the
methods in this class would be called first
Functional Programming in Dart
• Lambda Expression

• Higher Order Functions

• Lexical Closures
Lambda Expressions
• A function without a name
• Also known as anonymous function or lambda

NOTE: A function in dart is an object


• int sum =2;
• String name=‘Pradnya’;
• Function addNumbers= //some value;

;
Lambda Expressions(contd..){1st way}
Lambda Expressions(contd..){2nd way}
Higher Order Functions
• Higher Order Functions:
• Can accept function as a parameter
• Can return a function
• Or can do both
Higher Order Functions (contd..)
Higher Order Functions (contd..)
Closures
• Closure is a special function
• Within a closure, you can mutate(modify) the values of
variables present in parent scope
• In Java 8, you are not allowed to modify parent scope
variables
Closure(contd..)
Closure(contd..)
Generics
• Introduction
• Examples of Generics
• Generic Class
• Generic Method
Generics
• Dart is an optionally typed language.
• Collections in Dart are heterogeneous by default.
In other words, a single Dart collection can host
values of various types
• However, a Dart collection can be made to hold
homogenous values with help of generics concept

• All Dart collections support type-safety implementation


via generics.
Generics(contd..)
• A pair of angular brackets containing the data type is used to
declare a type-safe collection
• Syntax
Collection_name <data_type> identifier= new
Collection_name<data_type>
• Advantages:
• Code Reuse: We can write a method/class/interface once and
use for any type we want.
• Type Safety : Generics make errors to appear compile time
than at run time
Generics(contd..)
List
Generics(contd..)
List
Generics(contd..)
Set
Generics(contd..)
Queue
Generics(contd..)
Map
Generic Class
• We use <> to specify parameter types in generic class
creation. To create objects of generic class,
Generic Method

You might also like