SlideShare a Scribd company logo
Mobile Application Development
class 06
Dr. Mazin Alkathiri
IT Department
Seiyun University
2023-2024
Stateful and Stateless Widgets
• A widget is either stateful or stateless.
• If a widget can change—when a user interacts with it, for example—it's
stateful. A stateful widget is dynamic: for example, it can change its
appearance in response to events triggered by user interactions or
when it receives data.
• Checkbox , Radio , Slider , InkWell , Form , and TextField are examples of stateful
widgets.
• A stateless widget never changes. Icon , IconButton , and Text
are examples of stateless widgets.
• Stateless widgets are text, icons, icon buttons, and raised buttons.
Stateless Widget
• is something that does not have a state. To understand a
Stateless Widget you need to have a clear understanding of
widgets and states.
• A state can be defined as “an imperative changing of the user
interface”
• and, a widget is “an immutable description of the part of user
interface”.
What are Stateless Widgets?
• A Stateless Widget is one that does not have any mutable state that it needs to
track.
• The only area of focus of a stateless widget is the information displayed and the
user interface.
• They deal with situations that are independent of the user’s input.
• A Stateless Widget does not tell the framework when to remove it or rebuild it, it
gets a command from the framework itself.
• They create user interfaces that do not change dynamically upon updation in the
nearby values.
• We use a stateless widget when we create an application that does not require
redrawing a widget again and again.
• Given below is the basic structure of a stateless widget known as GreenFrog.
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container();
}
}
• The MyApp class is a Stateless Widget and Widget build is a
method with BuildContext as a parameter that returns
widgets. Every widget while entering the Widget build(Build
Context context) has to override it in order to enter the widget
tree. Some Examples of a stateless widget are Text, IconButton,
AppBar, etc. Build Method is called inside a stateless widget in
only three cases:
• Initially in the start when it is built for the very first time while
starting the application.
• If the parent widget is changed
• If the inherited widget is changed
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
void know() {
// ignore: avoid_print
print("Button Pressed");
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Statless Widget class'),
backgroundColor: Colors.green,
),
body: Center(
child: ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.green)),
onPressed: know,
child: const Text(
' Stateless Widget Tutorial ',
style: TextStyle(color: Colors.white),
),
),
),
),
• The control will enter the runApp()
through the main. From there it
will be redirected to the stateless
widget of the MyApp class.
• The build method will be called the
very first-time MyApp stateless
widget is built.
• Every time a widget wants to enter
the widget tree, it has to override
the Widget build (BuildContext
context)method.
• After that, the control goes to the
MaterialApp widget and the rest of
the code will be executed.
• Remember, every time a new
widget enters the widget tree, it
has to override the build method.
What are Stateful Widgets?
• A Stateful Widget has its own mutable state that it needs to track. It is modified
according to the user’s input.
• A Stateful Widget looks after two things primarily, the changed state based on its
previous state and an updated view of the user interface.
• A track of the previous state value has to be looked at because there is a need to
self-rebuild the widget to show the new changes made to your application.
• A Stateful Widget triggers a build method for creating its children widgets and
the subclass of the state holds the related data. It is often used in cases where
redrawing of a widget is needed.
• A Stateful Widget can change when:
– There is a User Input included
– There are some User Interaction
– There are some Dynamic Changes
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return Container();
}
}
The MyApp is a class that extends
Stateful Widget.
A generic method createState()
creates a mutable state for the
widget at a particular location
and returns another class that is
extended by the previous state.
The _MyAppState class extends
another state.
Special Methods Associated with Stateful Widget
• There are various methods provided by the Stateful class to
work with:
• 1. BuildContext: It provides information regarding which
widget is to be built/re-build and where it will be located after
re-building. Thus, BuildContext is the widget associated with
the state.
Widget build(BuildContext context) {
return Container();
}
• 2. SetState(): A State object is used to modify the user interface. It
executes the code for a particular callback and repaints the
widgets that rely on that state for configuration.
• 3. initState(): This method is the entry point of a widget. The
initState() method initializes all the methods that the build method
will depend upon. This is called only once in a widget’s lifetime and
mostly overridden the rest of the time.
setState(setState(() {
});
initState() {
//...
super.init();
}
• 4. didChangeDependencies(): It is used for loading the
dependencies required for execution of a state. The
didChangeDependencies() is called immediately after the
initState() is called for the first time and before the triggering
of the build method.
• 5. dispose(): This method is used for removing an object
permanently from the widget tree. It is used when we need to
clear up the memory by invoking super.dispose().
void didChangeDependencies() {
}
void dispose(){
//...
super.dispose();
}
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
MyApp({Key? key}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
backgroundColor: Colors.green,
title: const Text('statfull widget example - home window'),
),
body: const FirstScreen()));
}
}
class FirstScreen extends StatelessWidget {
const FirstScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
child: Center(
child: ElevatedButton(
onPressed: () => Navigator.of(context)
.push(MaterialPageRoute(builder: (context) => const NewScreen())),
child: const Text(
'Move to next screen',
style: TextStyle(color: Colors.white),
),
)),
);
}
}
• In the given example, the
user interface changes, and
the control shift to the next
screen as soon as the central
button is clicked i.e. State of
the object is changed. This is
exactly what a Stateful
Widget is used for.
class NewScreen extends StatefulWidget {
const NewScreen({Key? key}) : super(key: key);
@override
State<NewScreen> createState() => _NewScreenState();
}
class _NewScreenState extends State<NewScreen> {
TextEditingController textEditingController = TextEditingController();
@override
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Second window '),
backgroundColor: Colors.green,
),
body: Container(
child: Center(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: Container(
child: Text(
'User Interface Changed!!',
),
)),
Navigation and Routing
• In any application, navigating from one page / screen to
another defines the work flow of the application.
• The way that the navigation of an application is handled is
called Routing.
• Flutter provides a basic routing class – MaterialPageRoute and
two methods - Navigator.push and Navigator.pop, to define the
work flow of an application.
MaterialPageRoute
• MaterialPageRoute is a widget used to render its UI by
replacing the entire screen with a platform specific animation.
• Here, builder will accepts a function to build its content by
suppling the current context of the application.
MaterialPageRoute(builder: (context) => Widget())
• Navigation.push
Navigation.push is used to navigate to new screen using
MaterialPageRoute widget.
• Navigation.pop
Navigation.pop is used to navigate to previous screen.
Navigator.push( context, MaterialPageRoute(builder: (context) => Widget()), );
Navigator.push(context);
• Let us modify our products list application to better understand
the navigation concept.
• Let us create a Product class to organize the product information
class Product {
final String name;
final String description;
final int price;
final String image;
Product(this.name, this.description, this.price, this.image);
}
• Let us write a method getProducts in the Product class to generate our
dummy product records. Product(this.name, this.description, this.price, this.image);
static List<Product> getProducts() {
List<Product> items = <Product>[];
items.add(
Product(
"Pixel",
"Pixel is the most featureful phone ever",
800,
"pixel.png"
)
);
items.add(
Product(
"Laptop",
"Laptop is most productive development tool",
2000,
"laptop.png"
)
);
.
.
.
return items;
}
• Let us include our new widget, RatingBox.
class RatingBox extends StatefulWidget {
@override
_RatingBoxState createState() => _RatingBoxState();
}
class _RatingBoxState extends State<RatingBox> {
int _rating = 0;
void _setRatingAsOne() {
setState(() {
_rating = 1;
});
}
void _setRatingAsTwo() {
setState(() {
_rating = 2;
});
}
void _setRatingAsThree() {
setState(() {
_rating = 3;
});
}
Widget build(BuildContext context) {
double _size = 20;
print(_rating);
return Row(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
Container(
padding: EdgeInsets.all(0),
child: IconButton(
icon: (
_rating >= 1 ? Icon(
Icons.star,
size: _size,
)
: Icon(
Icons.star_border,
size: _size,
)
),
color: Colors.red[500],
onPressed: _setRatingAsOne,
iconSize: _size,
),
),
Container(
padding: EdgeInsets.all(0),
child: IconButton(
icon: (
_rating >= 2 ?
Icon(
Icons.star,
size: _size,
)
: Icon(
Icons.star_border,
size: _size,
)
),
color: Colors.red[500],
onPressed: _setRatingAsTwo,
iconSize: _size,
),
),
Container(
padding: EdgeInsets.all(0),
child: IconButton(
icon: (
_rating >= 3 ?
Icon(
Icons.star,
size: _size,
)
: Icon(
Icons.star_border,
size: _size,
)
),
color: Colors.red[500],
onPressed: _setRatingAsThree,
iconSize: _size,
),
),
],
);
}
}
• Let us modify our ProductBox widget to work with our new Product class.
class ProductBox extends StatelessWidget {
ProductBox({Key? key, required this.item}) : super(key: key);
final Product item;
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(2),
height: 140,
child: Card(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Image.asset("assets/appimages/" + this.item.image),
Expanded(
child: Container(
padding: EdgeInsets.all(5),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Text(this.item.name, style: TextStyle(fontWeight: FontWeight.bold)), Text(this.item.description),
Text("Price: " + this.item.price.toString()),
RatingBox(),
],
)
• Let us rewrite our MyHomePage widget to work with Product
model and to list all products using ListView.
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Product Navigation")),
body: ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return GestureDetector(
child: ProductBox(item: items[index]),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ProductPage(item: items[index]),
),
);
},
);
},
)
);
}
• Now, let us add ProductPage to show the product details.
class ProductPage extends StatelessWidget {
ProductPage({Key? key, required this.item}) : super(key: key);
final Product item;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(this.item.name),
),
body: Center(
child: Container(
padding: EdgeInsets.all(0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Image.asset("assets/appimages/" + this.item.image),
Expanded(
child: Container(
padding: EdgeInsets.all(5),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Text(this.item.name, style: TextStyle(fontWeight: FontWeight.bold)),
Mobile Application Development class 006

More Related Content

PPTX
Mobile Application Development class 003
PPTX
FlutterArchitecture FlutterArchitecture.ppt
PPTX
FlutterArchitecture FlutterDevelopement (1).pptx
PPTX
Mobile Applications Development class 03-starting with flutter
PPTX
App_development22222222222222222222.pptx
PDF
The battle between the states (all about flutter stateless & stateful widgets...
PDF
MVP Community Camp 2014 - How to use enhanced features of Windows 8.1 Store ...
PDF
Rp 6 session 2 naresh bhatia
Mobile Application Development class 003
FlutterArchitecture FlutterArchitecture.ppt
FlutterArchitecture FlutterDevelopement (1).pptx
Mobile Applications Development class 03-starting with flutter
App_development22222222222222222222.pptx
The battle between the states (all about flutter stateless & stateful widgets...
MVP Community Camp 2014 - How to use enhanced features of Windows 8.1 Store ...
Rp 6 session 2 naresh bhatia

Similar to Mobile Application Development class 006 (20)

PPTX
Force Flutter to Rebuild or Redraw All Widgets.pptx
PPT
Hello Android
PPTX
Application Developmet lecture for backend
PDF
Introduction of Xcode
PPTX
PDF
Refactor Large applications with Backbone
PDF
Refactor Large apps with Backbone
PDF
Refactoring Large Web Applications with Backbone.js
PDF
[Flutter] Flutter Provider 看似簡單卻又不簡單的狀態管理工具 @ Devfest Kaohsiung 2023
PDF
22Flutter.pdf
PPTX
Mod_5 of Java 5th module notes for ktu students
PPTX
iOS app dev Training - Session1
PDF
iOS (7) Workshop
PDF
Fundamental concepts of react js
PPTX
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
PPTX
Creating GUI.pptx Gui graphical user interface
PPTX
Unit-1.2 Android-Activities, Fragments, and Intents (1).pptx
PDF
Developer Student Clubs NUK - Flutter for Beginners
PPTX
Modern android development
PPTX
iOS Development (Part 3) - Additional GUI Components
Force Flutter to Rebuild or Redraw All Widgets.pptx
Hello Android
Application Developmet lecture for backend
Introduction of Xcode
Refactor Large applications with Backbone
Refactor Large apps with Backbone
Refactoring Large Web Applications with Backbone.js
[Flutter] Flutter Provider 看似簡單卻又不簡單的狀態管理工具 @ Devfest Kaohsiung 2023
22Flutter.pdf
Mod_5 of Java 5th module notes for ktu students
iOS app dev Training - Session1
iOS (7) Workshop
Fundamental concepts of react js
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
Creating GUI.pptx Gui graphical user interface
Unit-1.2 Android-Activities, Fragments, and Intents (1).pptx
Developer Student Clubs NUK - Flutter for Beginners
Modern android development
iOS Development (Part 3) - Additional GUI Components
Ad

More from Dr. Mazin Mohamed alkathiri (20)

PPTX
Computer Introduction (Operating Systems)-Lecture06
PPTX
Mobile Application Development (local database) class-07
PPTX
Mobile Application Development (Shared Preferences) class-06
PPTX
Mobile Application Development((Handling User Input and Navigation) class-05
PPTX
Computer Introduction (Data Encryption)-Lecture05
PPTX
Computer Introduction (Computer Viruses )-Lecture04
PPTX
Mobile Applications Development class 04-Layout-04
DOCX
Appendix to Lecture 3 Building a flutter app
PPTX
Mobile Applications Development class 02 ntroduction to Drat
PPTX
Computer Introduction (Software)-Lecture03
PPTX
Computer Introduction (Hardware)-Lecture02
PPTX
Computer Introduction (introduction)-Lecture01
PPTX
Introduction to Academic Writing class 0-1
PPTX
Mobile Applications Development class 01 - Introduction
PPT
OS-operating systems- ch05 (CPU Scheduling) ...
PPTX
ESSENTIAL of (CS/IT/IS) class 07 (Networks)
PPTX
Advance Mobile Application Development class 07
PPTX
ESSENTIAL of (CS/IT/IS) class 06 (database)
PPT
OS-operating systems- ch04 (Threads) ...
PPTX
Advance Mobile Application Development class 05
Computer Introduction (Operating Systems)-Lecture06
Mobile Application Development (local database) class-07
Mobile Application Development (Shared Preferences) class-06
Mobile Application Development((Handling User Input and Navigation) class-05
Computer Introduction (Data Encryption)-Lecture05
Computer Introduction (Computer Viruses )-Lecture04
Mobile Applications Development class 04-Layout-04
Appendix to Lecture 3 Building a flutter app
Mobile Applications Development class 02 ntroduction to Drat
Computer Introduction (Software)-Lecture03
Computer Introduction (Hardware)-Lecture02
Computer Introduction (introduction)-Lecture01
Introduction to Academic Writing class 0-1
Mobile Applications Development class 01 - Introduction
OS-operating systems- ch05 (CPU Scheduling) ...
ESSENTIAL of (CS/IT/IS) class 07 (Networks)
Advance Mobile Application Development class 07
ESSENTIAL of (CS/IT/IS) class 06 (database)
OS-operating systems- ch04 (Threads) ...
Advance Mobile Application Development class 05
Ad

Recently uploaded (20)

PPTX
UNIT III MENTAL HEALTH NURSING ASSESSMENT
PDF
What if we spent less time fighting change, and more time building what’s rig...
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
History, Philosophy and sociology of education (1).pptx
PDF
Classroom Observation Tools for Teachers
PPTX
Orientation - ARALprogram of Deped to the Parents.pptx
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
Paper A Mock Exam 9_ Attempt review.pdf.
PDF
Complications of Minimal Access Surgery at WLH
PDF
Updated Idioms and Phrasal Verbs in English subject
PDF
Trump Administration's workforce development strategy
PDF
Anesthesia in Laparoscopic Surgery in India
PPTX
Cell Structure & Organelles in detailed.
PDF
A systematic review of self-coping strategies used by university students to ...
PDF
01-Introduction-to-Information-Management.pdf
PPTX
UV-Visible spectroscopy..pptx UV-Visible Spectroscopy – Electronic Transition...
UNIT III MENTAL HEALTH NURSING ASSESSMENT
What if we spent less time fighting change, and more time building what’s rig...
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
History, Philosophy and sociology of education (1).pptx
Classroom Observation Tools for Teachers
Orientation - ARALprogram of Deped to the Parents.pptx
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Supply Chain Operations Speaking Notes -ICLT Program
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Module 4: Burden of Disease Tutorial Slides S2 2025
Paper A Mock Exam 9_ Attempt review.pdf.
Complications of Minimal Access Surgery at WLH
Updated Idioms and Phrasal Verbs in English subject
Trump Administration's workforce development strategy
Anesthesia in Laparoscopic Surgery in India
Cell Structure & Organelles in detailed.
A systematic review of self-coping strategies used by university students to ...
01-Introduction-to-Information-Management.pdf
UV-Visible spectroscopy..pptx UV-Visible Spectroscopy – Electronic Transition...

Mobile Application Development class 006

  • 1. Mobile Application Development class 06 Dr. Mazin Alkathiri IT Department Seiyun University 2023-2024
  • 2. Stateful and Stateless Widgets • A widget is either stateful or stateless. • If a widget can change—when a user interacts with it, for example—it's stateful. A stateful widget is dynamic: for example, it can change its appearance in response to events triggered by user interactions or when it receives data. • Checkbox , Radio , Slider , InkWell , Form , and TextField are examples of stateful widgets. • A stateless widget never changes. Icon , IconButton , and Text are examples of stateless widgets. • Stateless widgets are text, icons, icon buttons, and raised buttons.
  • 3. Stateless Widget • is something that does not have a state. To understand a Stateless Widget you need to have a clear understanding of widgets and states. • A state can be defined as “an imperative changing of the user interface” • and, a widget is “an immutable description of the part of user interface”.
  • 4. What are Stateless Widgets? • A Stateless Widget is one that does not have any mutable state that it needs to track. • The only area of focus of a stateless widget is the information displayed and the user interface. • They deal with situations that are independent of the user’s input. • A Stateless Widget does not tell the framework when to remove it or rebuild it, it gets a command from the framework itself. • They create user interfaces that do not change dynamically upon updation in the nearby values. • We use a stateless widget when we create an application that does not require redrawing a widget again and again. • Given below is the basic structure of a stateless widget known as GreenFrog.
  • 5. class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Container(); } } • The MyApp class is a Stateless Widget and Widget build is a method with BuildContext as a parameter that returns widgets. Every widget while entering the Widget build(Build Context context) has to override it in order to enter the widget tree. Some Examples of a stateless widget are Text, IconButton, AppBar, etc. Build Method is called inside a stateless widget in only three cases: • Initially in the start when it is built for the very first time while starting the application. • If the parent widget is changed • If the inherited widget is changed
  • 6. import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); void know() { // ignore: avoid_print print("Button Pressed"); } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('Statless Widget class'), backgroundColor: Colors.green, ), body: Center( child: ElevatedButton( style: ButtonStyle( backgroundColor: MaterialStateProperty.all(Colors.green)), onPressed: know, child: const Text( ' Stateless Widget Tutorial ', style: TextStyle(color: Colors.white), ), ), ), ), • The control will enter the runApp() through the main. From there it will be redirected to the stateless widget of the MyApp class. • The build method will be called the very first-time MyApp stateless widget is built. • Every time a widget wants to enter the widget tree, it has to override the Widget build (BuildContext context)method. • After that, the control goes to the MaterialApp widget and the rest of the code will be executed. • Remember, every time a new widget enters the widget tree, it has to override the build method.
  • 7. What are Stateful Widgets? • A Stateful Widget has its own mutable state that it needs to track. It is modified according to the user’s input. • A Stateful Widget looks after two things primarily, the changed state based on its previous state and an updated view of the user interface. • A track of the previous state value has to be looked at because there is a need to self-rebuild the widget to show the new changes made to your application. • A Stateful Widget triggers a build method for creating its children widgets and the subclass of the state holds the related data. It is often used in cases where redrawing of a widget is needed. • A Stateful Widget can change when: – There is a User Input included – There are some User Interaction – There are some Dynamic Changes
  • 8. class MyApp extends StatefulWidget { const MyApp({Key? key}) : super(key: key); @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { @override Widget build(BuildContext context) { return Container(); } } The MyApp is a class that extends Stateful Widget. A generic method createState() creates a mutable state for the widget at a particular location and returns another class that is extended by the previous state. The _MyAppState class extends another state.
  • 9. Special Methods Associated with Stateful Widget • There are various methods provided by the Stateful class to work with: • 1. BuildContext: It provides information regarding which widget is to be built/re-build and where it will be located after re-building. Thus, BuildContext is the widget associated with the state. Widget build(BuildContext context) { return Container(); }
  • 10. • 2. SetState(): A State object is used to modify the user interface. It executes the code for a particular callback and repaints the widgets that rely on that state for configuration. • 3. initState(): This method is the entry point of a widget. The initState() method initializes all the methods that the build method will depend upon. This is called only once in a widget’s lifetime and mostly overridden the rest of the time. setState(setState(() { }); initState() { //... super.init(); }
  • 11. • 4. didChangeDependencies(): It is used for loading the dependencies required for execution of a state. The didChangeDependencies() is called immediately after the initState() is called for the first time and before the triggering of the build method. • 5. dispose(): This method is used for removing an object permanently from the widget tree. It is used when we need to clear up the memory by invoking super.dispose(). void didChangeDependencies() { } void dispose(){ //... super.dispose(); }
  • 12. import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatefulWidget { MyApp({Key? key}) : super(key: key); @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, home: Scaffold( appBar: AppBar( backgroundColor: Colors.green, title: const Text('statfull widget example - home window'), ), body: const FirstScreen())); } }
  • 13. class FirstScreen extends StatelessWidget { const FirstScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Container( child: Center( child: ElevatedButton( onPressed: () => Navigator.of(context) .push(MaterialPageRoute(builder: (context) => const NewScreen())), child: const Text( 'Move to next screen', style: TextStyle(color: Colors.white), ), )), ); } }
  • 14. • In the given example, the user interface changes, and the control shift to the next screen as soon as the central button is clicked i.e. State of the object is changed. This is exactly what a Stateful Widget is used for. class NewScreen extends StatefulWidget { const NewScreen({Key? key}) : super(key: key); @override State<NewScreen> createState() => _NewScreenState(); } class _NewScreenState extends State<NewScreen> { TextEditingController textEditingController = TextEditingController(); @override @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Second window '), backgroundColor: Colors.green, ), body: Container( child: Center( child: Padding( padding: const EdgeInsets.symmetric(horizontal: 20.0), child: Container( child: Text( 'User Interface Changed!!', ), )),
  • 15. Navigation and Routing • In any application, navigating from one page / screen to another defines the work flow of the application. • The way that the navigation of an application is handled is called Routing. • Flutter provides a basic routing class – MaterialPageRoute and two methods - Navigator.push and Navigator.pop, to define the work flow of an application.
  • 16. MaterialPageRoute • MaterialPageRoute is a widget used to render its UI by replacing the entire screen with a platform specific animation. • Here, builder will accepts a function to build its content by suppling the current context of the application. MaterialPageRoute(builder: (context) => Widget())
  • 17. • Navigation.push Navigation.push is used to navigate to new screen using MaterialPageRoute widget. • Navigation.pop Navigation.pop is used to navigate to previous screen. Navigator.push( context, MaterialPageRoute(builder: (context) => Widget()), ); Navigator.push(context);
  • 18. • Let us modify our products list application to better understand the navigation concept. • Let us create a Product class to organize the product information class Product { final String name; final String description; final int price; final String image; Product(this.name, this.description, this.price, this.image); }
  • 19. • Let us write a method getProducts in the Product class to generate our dummy product records. Product(this.name, this.description, this.price, this.image); static List<Product> getProducts() { List<Product> items = <Product>[]; items.add( Product( "Pixel", "Pixel is the most featureful phone ever", 800, "pixel.png" ) ); items.add( Product( "Laptop", "Laptop is most productive development tool", 2000, "laptop.png" ) ); . . . return items; }
  • 20. • Let us include our new widget, RatingBox. class RatingBox extends StatefulWidget { @override _RatingBoxState createState() => _RatingBoxState(); } class _RatingBoxState extends State<RatingBox> { int _rating = 0; void _setRatingAsOne() { setState(() { _rating = 1; }); } void _setRatingAsTwo() { setState(() { _rating = 2; }); } void _setRatingAsThree() { setState(() { _rating = 3; }); }
  • 21. Widget build(BuildContext context) { double _size = 20; print(_rating); return Row( mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.end, mainAxisSize: MainAxisSize.max, children: <Widget>[ Container( padding: EdgeInsets.all(0), child: IconButton( icon: ( _rating >= 1 ? Icon( Icons.star, size: _size, ) : Icon( Icons.star_border, size: _size, ) ), color: Colors.red[500], onPressed: _setRatingAsOne, iconSize: _size, ), ), Container( padding: EdgeInsets.all(0), child: IconButton( icon: ( _rating >= 2 ? Icon( Icons.star, size: _size, ) : Icon( Icons.star_border, size: _size, ) ), color: Colors.red[500], onPressed: _setRatingAsTwo, iconSize: _size, ), ), Container( padding: EdgeInsets.all(0), child: IconButton( icon: ( _rating >= 3 ? Icon( Icons.star, size: _size, ) : Icon( Icons.star_border, size: _size, ) ), color: Colors.red[500], onPressed: _setRatingAsThree, iconSize: _size, ), ), ], ); } }
  • 22. • Let us modify our ProductBox widget to work with our new Product class. class ProductBox extends StatelessWidget { ProductBox({Key? key, required this.item}) : super(key: key); final Product item; Widget build(BuildContext context) { return Container( padding: EdgeInsets.all(2), height: 140, child: Card( child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Image.asset("assets/appimages/" + this.item.image), Expanded( child: Container( padding: EdgeInsets.all(5), child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Text(this.item.name, style: TextStyle(fontWeight: FontWeight.bold)), Text(this.item.description), Text("Price: " + this.item.price.toString()), RatingBox(), ], )
  • 23. • Let us rewrite our MyHomePage widget to work with Product model and to list all products using ListView. @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text("Product Navigation")), body: ListView.builder( itemCount: items.length, itemBuilder: (context, index) { return GestureDetector( child: ProductBox(item: items[index]), onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => ProductPage(item: items[index]), ), ); }, ); }, ) ); }
  • 24. • Now, let us add ProductPage to show the product details. class ProductPage extends StatelessWidget { ProductPage({Key? key, required this.item}) : super(key: key); final Product item; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(this.item.name), ), body: Center( child: Container( padding: EdgeInsets.all(0), child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Image.asset("assets/appimages/" + this.item.image), Expanded( child: Container( padding: EdgeInsets.all(5), child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Text(this.item.name, style: TextStyle(fontWeight: FontWeight.bold)),