FLutter Course Inter
FLutter Course Inter
(Intermediate)
TTKS
Course Outline
Continue
Beginner’s Project
State Database (Firebase)
03 06 - FireStore
- State Management
-App Distribution
- Must include API (mock ok) , Structure(BLOC or MVVM) TTKS
Dart (OOP)-I
Object-oriented programming (OOP)
programming paradigm
Features Of OOP
1. Class
2. Object
3. Encapsulation
4. Inheritance
5. Polymorphism
6. Abstraction
OOP is based on objects, which are data structures containing data and methods.
Class
A class defines the properties and methods that an object will have. Phone
Properties
● Model
● Color
● Size
Method(action)
● callingPhone()
● usingInternet()
● photoshooting()
● Properties are used to store the data. It is also known as
fields or attributes.
● Functions are used to perform the operations. It is also
known as methods.
Properties /Attributes
Example
class Person {
String? name;
String? phone;
bool? isMarried;
int? age;
void displayInfo() {
print("Person name: $name.");
print("Phone number: $phone.");
print("Married: $isMarried.");
print("Age: $age.");
}
}
Methods / Functions
Object
An object is an instance of a class.
class Animal {
String? name;
int? numberOfLegs;
int? lifeSpan;
void display() {
print("Animal name: $name.");
print("Number of Legs: $numberOfLegs.");
print("Life Span: $lifeSpan.");
}
}
void main(){
// Here animal is object of class Animal.
Animal animal = Animal();
animal.name = "Lion";
animal.numberOfLegs = 4;
animal.lifeSpan = 10;
animal.display();
}
Person
Constructor Methods
● display()
A constructor is a special method used to initialize an object.
Properties
● name
● age
Without Constructor
Syntex
Default Constructor In Dart
class Laptop {
String? brand;
int? prize;
// Constructor
Laptop() {
print("This is a default constructor");
}
}
void main() {
// Here laptop is object of class Laptop.
Laptop laptop = Laptop();
}
class Student {
String? name;
int? age;
int? rollNumber;
// Constructor
Student(String name, int age, int rollNumber) {
print(
"Constructor called"); // this is for checking the constructor is called or not.
this.name = name;
this.age = age;
this.rollNumber = rollNumber;
}
}
void main() {
// Here student is object of class Student.
Student student = Student("John", 20, 1);
print("Name: ${student.name}");
print("Age: ${student.age}");
print("Roll Number: ${student.rollNumber}");
}
class Person{
String? name;
int? age;
String? subject;
double? salary;
// display method
void display(){
print("Name: ${this.name}");
print("Age: ${this.age}");
print("Subject: ${this.subject}");
print("Salary: ${this.salary}");
}
}
void main(){
Person person = Person("John", 30, "Maths", 50000.0);
person.display();
}
class Employee {
String? name;
int? age;
String? subject;
double? salary;
// Constructor
Employee(this.name, this.age, [this.subject = " ", this.salary=0]);
// Method
void display() {
print("Name: ${this.name}");
print("Age: ${this.age}");
print("Subject: ${this.subject}");
print("Salary: ${this.salary}");
}
}
void main(){
Employee employee = Employee("John", 30);
employee.display();
}
class Chair {
String? name;
String? color;
// Constructor
Chair({this.name, this.color});
// Method
void display() {
print("Name: ${this.name}");
print("Color: ${this.color}");
}
}
void main(){
Chair chair = Chair(name: "Chair1", color: "Red");
chair.display();
}
Assignment
Create a class Book with three properties: name, author, and prize. Also, create a method called display, which prints out the values of
the three properties.
Create a Class Camera with properties: name, color, megapixel. Create a method called display which prints out the values of the
three properties. Create two objects of the class Camera and call the method display.
Create a class Patient with three properties name, age, and disease. The class has one constructor. The constructor is used to
initialize the values of the three properties. Also, create an object of the class Patient called patient. Print the values of the three
properties using the object.
Dart (OOP)-II
Inheritance
Inheritance is a sharing of behaviour between two classes. The extend keyword is used for inheriting from
parent class.
Child Class
Parent Class
Parent Class
Null safety is a feature in the Dart programming language that helps developers to avoid null
errors.
Nullable Non-Nullable
void main(){
// Declaring a nullable variable by using ?
String? name;
// Assigning John to name
name = "John";
print("Name: $name");
// Assigning null to name
name = null;
print("Name: $name");
}
● Use if statement to check whether the variable is null or
not.
● Use ! operator, which returns null if the variable is null.
● Use ?? operator to assign a default value if the variable
is null.
void main(){
// Declaring a nullable variable by using ?
String? name;
// Assigning John to name
name = "John";
// Assigning null to name
name = null;
// Checking if name is null using if statement
if(name == null){
print("Name is null");
}
// Using ?? operator to assign a default value
String name1 = name ?? "Stranger";
print(name1);
// Using ! operator to return null if name is null
String name2 = name!;
print(name2);
}
Late Keyword
late keyword is used to declare a variable or field that will be initialized at a later time.
// late variable
late String name;
void main() {
// assigning value to late variable
name = "John";
print(name);
}
Asynchronous Programming
Synchronous operation means a task that needs to be solved before proceeding to the next one.
main() {
print("First Operation");
print("Second Big Operation");
print("Third Operation");
print("Last Operation");
}
In Asynchronous, program execution continues to the next line without waiting to complete other work.
Don’t wait.
main() {
print("First Operation");
Future.delayed(Duration(seconds:3),()=>print('Second Big Operation'));
print("Third Operation");
print("Last Operation");
}
Future In Dart
Future represents the result of an asynchronous operation and can have 2 states.
State Of Future
● Uncompleted
● Completed
Uncompleted => When you call an asynchronous function, it returns to an uncompleted future. It means the future is
waiting for the function asynchronous operation to finish or to throw an error.
Completed => It can be completed with value or completed with error. Future<int> produces an int value, and
Future<String> produces a String value.
main() {
print("Start");
getData();
print("End");
}
Future<String> middleFunction(){
return Future.delayed(Duration(seconds:5), ()=> "Hello");
}
Async And Await In Dart
the async keyword before a function body to make it asynchronous.
the await keyword to get the completed result of an asynchronous expression.
main() {
print("Start");
getData();
print("End");
}
Future<String> middleFunction(){
return Future.delayed(Duration(seconds:5), ()=> "Hello");
}
Dart Package
https://pub.dev/
01 add the package in pubspec.yaml
and run ‘pub get’
02
bottom_navy_bar: ^6.0.0
flutter_bloc: ^8.1.1
cached_network_image: ^3.2.3
fl_chart – A powerful Flutter chart library, currently supporting Line Chart, Bar Chart
and Pie Chart.
google_maps_flutter – A Flutter plugin for integrating Google Maps in iOS and Android
applications.
Form and Validation/ Gesture / MediaQuery
Gesture Detector
Gestures are generally defined as any physical action / movement of a user in the intention of activating a
specific control of the mobile device.
Tap − Touching the surface of the device with fingertip for a short period and then
releasing the fingertip.
Drag − Touching the surface of the device with fingertip and then moving the fingertip in
a steady manner and then finally releasing the fingertip.
● Tap
○ onTapDown
○ onTapUp
○ onTap
○ onTapCancel
● Double tap
○ onDoubleTap
● Long press
○ onLongPress
● Vertical drag
○ onVerticalDragStart
○ onVerticalDragUpdate
○ onVerticalDragEnd
● Horizontal drag
○ onHorizontalDragStart
○ onHorizontalDragUpdate
○ onHorizontalDragEnd
https://docs.flutter.dev/development/ui/advanced/gestures
Media Query
For example, to learn the size of the current media (e.g., the window
containing your app), you can read the MediaQueryData.size property from
the MediaQueryData returned by MediaQuery.of:
MediaQuery.of(context).size.
class Home extends StatelessWidget {
var size,height,width;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(“Media Query"),
backgroundColor: Colors.green,
),
body: Container(
color: Colors.yellow,
height: height/2,//half of the height size
width: width/2,//half of the width size
),
);
}
Form Validation
A Form widget with a GlobalKey.
void _submit() {
bool isValid = _formKey.currentState!.validate();
if (!isValid) {
return;
}
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) {
return HomeScreen();
},
),
);
}
RegExp class
a match-checking algorithm for text inputs
https://api.flutter.dev/flutter/dart-core/RegExp-class.html
Custom Widget
SafeArea in Flutter
SafeArea is basically a Padding widget
Animation in List Scrolling
DAY 7
Pull to Refresh Library
dependencies:
flutter:
sdk: flutter
pull_to_refresh: ^2.0.0
SmartRefresher
SmartRefresher(
{Key? key,
required this.controller,
this.child,
this.header,
this.footer,
this.enablePullDown: true,
this.enablePullUp: false,
this.onRefresh,
this.onLoading,
this.scrollController})
Web View
DAY 8
Web View
WebViews are hosted native views, and you as an app developer have a choice on how to host these
native views in your app.
● The WebView widget provides several page load progress events, which your
app can listen to.
● there are three different page load events that are fired: onPageStarted,
onProgress, and onPageFinished. In this step you will implement a page load
indicator.
State Management And Architecture
DAY 9
State Management
❖ State management is one of the most important processes in the life cycle of an
application.
❖ In Flutter is whatever data you need in order to rebuild your UI at any moment in time.
❖ When this data change, it will trigger a redraw of the user interface.
🌟 setState:
The low-level approach to use for widget-specific, ephemeral state. You can simply use
Statefulwidget and setState() method to get state.
the Bloc pattern allows one to separate all Flutter application logic into a single component
called the Business Logic Component.
Architecture Pattern
Mobile app architecture refers to a set of rules, techniques, processes, and patterns to develop a
mobile application.
Provider
https://pub.dev/packages/provider/install
● Provider makes easy to apply MVVM pattern and control the state of our applications.
● Provider is a Flutter package to handle state management of application.
● The flutter team recommend to use Provider for state management for beginners.
ChangeNotifier
DAY 10
Model–View–ViewModel (MVVM)
MVVM is useful to move business logic from view to ViewModel and Model. ViewModel is the
mediator between View and Model which carry all user events and return back the result.
Model
The model represents a single source of truth that carries the real-time fetch data or database-related
queries.
This layer can contain business logic, code validation, etc. This layer interacts with ViewModel for local
data or for real-time. Data are given in response to ViewModel.
ViewModel
ViewModel is the mediator between View and Model, which accept all the user events and request
that to Model for data. Once the Model has data then it returns to ViewModel and then ViewModel
notify that data to View.
View
The view is where the user is interacting with Widgets that are shown on the screen. These
user events request some actions which navigate to ViewModel, and the rest of ViewModel
does the job. Once ViewModel has the required data then it updates View.
Create View Model
wrapped the main root widget with the MultiProvider.
How to access the state and update the UI.
To access the state in the UserViewModel, use the below code in the build method.
DAY 11
What is BLOC?
Event
An Event is an action that is detected by the application, Typically, it’s a user action like clicking on a
button and some action is be performed.
Why Bloc?
BLoC provides an easy way to subscribe your Widgets to part of the state
and implement logic to modify the state. It records every single user
interaction in our application so that we can make data-driven decisions.
What is Data Provider?
A Data Provider can be considered as your back-end i.e your database where all
the users data is been started.
flutter_bloc also has its own widgets to build UI:
🛠 BlocBuilder
🛠 BlocProvider
🛠 MultiBlocProvider
🛠 BlocListener
🛠 MultiBlocListener
BlocBuilder
● BlocBuilder handles building a widget in response to new states.
● The builder function will be called many times and should be a pure
function that returns a widget in response to the state.
● the sample of BlocBuilder syntax structure👇
BlocProvider
● BlocProvider takes a Create function action that is responsible for
creating the Bloc and a child which will have access to the instance via
BlocProvider.of(context).
● BlocProvider creates the single instance of the bloc using a function which
takes the build context as an argument and return the only one instance of
the bloc(BlocA()).
MultiBlocProvider
● MultiBlocProvider is a Flutter widget that merges multiple BlocProvider
widgets into one.
● MultiBlocProvider improves the readability and eliminates the need to nest
multiple BlocProviders.
BlocListener
● BlocListener has the same structure as bloc builder .
● Blocbuilder function can be called multiple times inside the flutter
engine. Bloclistener is only called once for each state change (NOT
including initialState) unlike builder in BlocBuilder and is a void
function.
● It listens the state changes and process the UI changes according to
changed state.
How Flutter BLoC Works?
When a Application is built using Flutter BLoc pattern, whenever any data change is
happened,
➢ BLoC applies business logic to the current state and
➢ it re-create the new state to the UI
➢ When UI receive the new state it re-render itself to show latest version of UI with
new data that is been received from data provider.
How to use Bloc in flutter?
DAY 13
Rest API?
dependencies: Users
http:---
Posts
Step 2: Get the API URL and endpoints.
class ApiConstants {
static String baseUrl = 'https://jsonplaceholder.typicode.com';
static String usersEndpoint = '/users';
}
https://jsonplaceholder.typicode.com/
https://app.quicktype.io
Step 4 : create a file called api_service.dart
Status Code
FireBase
Authentication
Install =>https://pub.dev/packages/firebase_auth
CLI
Install => https://firebase.google.com/docs/cli#setup_update_cli
login_screen.dart
auth_service.dart
FireBase
What is firebase?
https://firebase.google.com/
Features
★ Hosting
★ Authentication
★ Storage/Database
★ Cloud Function
★ Testing
Firebase Projects
● Usage Plans
● Create Firebase project
● Set up Environment
Go to firebase console => Login with Gmail => “Add Project”
Firebase Authentication
Final Project Preparation
Example(bloc)
Example
Example - const
- Login /Logout
- Login Screen - views
- Register
- Register Screen - models
- Notification
- Notification List - blocs
- Display Users’
- Users’ item List - service
items
Mock API
https://mocki.io/
User
{//
"users" : [
{
"name":"John",
"age":30,
"cars":["Ford", "BMW", "Fiat"]
},
{
"name":"John",
"age":30,
"cars":["Ford", "BMW", "Fiat"]
}
]
}//
- MVVM / BLOC
- Mock API
- Firebase Authentication