UI Design FLutter Lab R23
UI Design FLutter Lab R23
DEPARTMENT OF
COMPUTER SCIENCE AND ENGINEERING
LABORATORY
MANUAL
NAME OF THE LAB : UI DESIGN- FLUTTER
CLASS : CSE
SEMESTER : 3-1(R23)
PREPARED BY :
[Link] SEKHAR
HOD-CSE
lOMoARcPSD|17292326
LISTOFEXPERIMENTS
WriteaProgramtoimplementthefollowingusingPython.
1. a)InstallFlutterAndDart SDK
b) WriteasimpleDartprogramtounderstandthelanguagebasics.
2. a)Explorevariousflutterwidgets(Text,Image,Container,etc..)
b) ImplementdifferentlayoutstructuresusingRow,Column,andStackwidgets
3. a)designaresponsiveUIthatadaptstodifferentscreensizes
b) Implementmediaqueriesandbreakpointsforresponsiveness
4. a)Setupnavigationbetweendifferentscreensusingnavigator
b) Implementnavigationwithnamed routes
6. a)CreatecustomwidgetsforspecificUI elements
b) Implementformvalidationanderrorhandling
b) Experimentwithdifferenttypesofanimationslikefade,slide,etc.
9. a)Fetchdatafrom RESTAPI
10. a)WriteunittestsforUIcomponents
b) UseFlutter’sdebuggingtoolstoidentifyandfix issues
lOMoARcPSD|17292326
1. Introduction
Objectivesofthelaboratorysessions
Prerequisitesfor students
Experiments:
b)WriteasimpleDartprogramtounderstandthelanguagebasics.
LabSession2:a)Explorevariousflutterwidgets(Text,Image,Container,etc..)
LabSession4:a)Setupnavigationbetweendifferentscreensusingnavigator
b)Implementnavigationwithnamedroutes Lab
b) Implement state management using set State and Provider Lab Session 6: a) Create custom widgets for
specific UI elements
b)Applystylingusingthemesandcustomstyles Lab
b)Implementformvalidationanderrorhandling
LabSession8: a)Add animationstoUI elementsusing flutter'sanimation framework
b)Experimentwithdifferenttypesofanimationslikefade,slide,etc.
b)DisplaythefetcheddatainameaningfulwayintheUI Lab
b)UseFlutter’sdebuggingtoolstoidentifyandfix issues
lOMoARcPSD|17292326
The lab manual of UI design with Flutter typically provides a structured guide for students to learn and
practice designing user interfaces using Flutter, a popular framework for building cross-platform mobile
applications. The manual usually covers various topics, including:
IntroductiontoFlutter:AnoverviewofFlutter,itsfeatures,andbenefitsformobileappdevelopment.
Setting Up Development Environment: Instructions for setting up Flutter and its dependencies on different
platforms like Windows, macOS, and Linux.
Flutter Basics: Fundamentals of Flutter, including widgets, layouts, navigation, state management, and
basic UI design principles.
Building UI Components: Step-by-step tutorials for creating common UI components such as buttons,
text fields, lists, and forms using Flutter widgets.
Styling and Theming: Guidelines for applying styles, themes, colors, fonts, and other visual elements to
enhance the appearance of the app.
Responsive Design: Techniques for designing responsive user interfaces that adapt to different screensizes
and orientations.
Navigation and Routing: How to implement navigation between screens and manage application routes
using Flutter's navigation system.
State Management: Introduction to state management techniques in Flutter, including setState, Provider,
Bloc, and other state management libraries.
API Integration: Integration of RESTful APIs to fetch and display data in the app, including handling
asynchronous operations and error handling.
Testing and Debugging: Strategies for testing UI components, debugging common issues, and using
Flutter's debugging tools effectively.
The lab manual typically includes hands-on exercises, code examples, and assignments to reinforce
learning and practical skills. It may also provide additional resources such as recommended readings,
online tutorials, and reference materials for further exploration of UI design concepts and Flutter
development. Overall, the lab manual serves as a comprehensive guide for students to gain proficiency in
designing user interfaces with Flutter.
Objectivesofthelaboratory sessions
Theobjectivesof laboratorysessionsinUI designwith Fluttertypically include:
UnderstandingFlutterFramework:GainfamiliaritywiththeFlutterframework,itsarchitecture,and key
concepts for building cross-platform mobile applications.
Practical Experience: Provide hands-on experience to students in designing user interfaces using Flutter
widgets, layouts, and components.
Applying UI Design Principles:Apply fundamental principles of UI design, such as consistency, clarity,
and usability, to create intuitive and visually appealing user interfaces.
ImplementingResponsiveDesign:Learntechniquesfordesigningresponsiveuserinterfacesthatadaptto
different screen sizes and orientations, ensuring a consistent user experience across devices.
Styling and Theming: Understand how to apply styles, themes, colors, and typography to enhance the
visual appearance of the app and maintain brand consistency.
Navigation and Routing: Learn how to implement navigation between screens and manage application
routes using Flutter's navigation system.
State Management: Explore various state management techniques in Flutter, such as setState, Provider,
Bloc, and others, to manage and update the state of UI components.
APIIntegration: IntegrateRESTfulAPIstofetchanddisplaydynamicdataintheapp,includinghandling
asynchronous operations and error handling.
Testing and Debugging: Practice testing UI components, debugging common issues, and using Flutter's
debugging tools effectively to identify and fix errors.
Deployment and Publishing: Understand the process of building and deploying Flutter apps to different
platforms likeAndroid and iOS, and publishing them to app stores.
Collaboration and Communication: Foster collaboration and communication skills by working in teams
on UI design projects, sharing ideas, and providing feedback to peers.
Enhance Critical Thinking and Problem-Solving Abilities: Engage in critical thinking and analytical
reasoning while designing and implementing solutions to complexAI problems, fostering problemsolving
skills essential for AI development.
Experiment with Different Approaches: Experiment with various AI approaches, including search
algorithms, heuristic methods, machine learning techniques, and optimization algorithms, to understand
their strengths, weaknesses, and applications.
Foster Collaboration and Communication: Collaborate with peers on problem-solving tasks, discuss
algorithm design choices, and communicate findings effectively, promoting teamwork and effective
communication skills.
Build a Strong Foundation inAI Theory and Practice: Develop a strong foundation in both theoretical
concepts and practical applications of artificial intelligence, preparing students for further study or
professional work in the field.
lOMoARcPSD|17292326
EncourageCreativityandInnovation:Encouragecreativityandinnovationinproblem-solving,allowing
students to explore alternative solutions, adapt existing algorithms, and develop novel approaches to AI
challenges.
Promote Lifelong Learning inAI: Cultivate a passion for lifelong learning and exploration in the field of
artificial intelligence, inspiring students to continue their education and pursue advancements in AI
technology throughout their careers.
Prerequisites forstudents
Before participating in laboratory sessions for UI design with Flutter, students should ideally have the
following prerequisites:
Basic Programming Skills: Students should have a basic understanding of programming concepts,
including variables, data types, control structures, and functions. Knowledge of object-oriented
programming (OOP) concepts like classes, objects, and inheritance would be beneficial.
Familiarity with Dart Programming Language: Flutter uses the Dart programming language, sostudents
should have a basic understanding of Dart syntax, features, and concepts. Topics such asvariables,
functions, classes, and asynchronous programming with Future and Stream would be important.
Understanding of UI Design Principles: Familiarity with fundamental principles of user interface (UI)
design, such as consistency, simplicity, visual hierarchy, and usability, would be helpful. Students should
have a basic understanding of how to design user-friendly and visually appealing interfaces.
Experience with Mobile Development: While not mandatory, prior experience with mobile app
development using frameworks like Flutter, React Native, or native development (Android/iOS) would be
advantageous. This includes understanding app lifecycle, navigation patterns, and platform-specific
considerations.
Development Environment Setup: Students should be able to set up and configure their development
environment for Flutter development. This includes installing Flutter SDK, Dart SDK, and necessary
development tools like IDE (e.g., Android Studio, IntelliJ IDEA, Visual Studio Code) and Flutter
plugins/extensions.
Problem-Solving Skills: Students should have strong problem-solving skills and the ability
[Link],researchingsolutionsonline,andseeking
help when needed.
Critical Thinking and Creativity: UI design involves creative thinking and problem-solving to create
intuitive and aesthetically pleasing user interfaces. Students should be able to think critically, analyze
design requirements, and propose innovative solutions.
Time Management: Managing time effectively is crucial for completing lab assignments, meeting
deadlines, and optimizing productivity during lab sessions. Students should be able to prioritize tasks,
allocate time wisely, and stay organized.
Effective Communication: Communication skills, both written and verbal, are essential for collaborating
with peers, discussing design ideas, and presenting project outcomes. Students should be able to articulate
their thoughts, provide constructive feedback, and work effectively in teams.
While these prerequisites provide a foundation for successful participation in UI design laboratorysessions,
students with varying levels of experience and backgrounds can benefit from engaging with the course
material and actively participating in hands-on activities and projects.
To effectively participate in UI design laboratory sessions with Flutter, students will need the following
software and hardware requirements:
SoftwareRequirements:
Flutter SDK: Install the Flutter SDK, which includes the Flutter framework and the Dart programming
language. Flutter provides installation instructions for various platforms such as Windows, macOS, and
Linux.
IntegratedDevelopmentEnvironment(IDE):
Recommended: Android Studio with Flutter plugin or Visual Studio Code with Flutter extension. Both
IDEs provide excellent support for Flutter development and include features
likecodecompletion,debugging,andprojectmanagement tools.
Alternatively,studentscanuseIntelliJIDEAwithFlutterpluginoranyothertexteditoroftheirchoice,but full-
featured IDEs are recommended for better productivity.
Dart SDK: The Dart SDK is included with the Flutter SDK, but students can also install it separately if
needed. It provides command-line tools for Dart development and is required for
runningDartprogramsoutsideofFlutterprojects.
MobileEmulators orDevices:
InstallAndroid Studio and set upAndroid Virtual Device (AVD) for runningAndroid emulators. For iOS
development,studentswillneedaMaccomputerwithXcodeinstalledtoruntheiOSsimulatorortestapps on
physical iOS devices.
Package Management: Flutter uses Dart's package manager, Pub, to manage dependencies. Students
should have access to the internet to download packages from Pub and add them to their Flutter projects.
HardwareRequirements:
Computer: Students will need a computer (desktop or laptop) running Windows, macOS, or Linux to
develop Flutter [Link] computer should meet the minimum system requirements for running the
chosen IDE and emulators/simulators.
Mobile Devices (Optional): While emulators/simulators are sufficient for testing and development,
students may also want to test their apps on physicalAndroid and iOS devices. Ensure compatibility with
Flutter by enabling developer mode and USB debugging on the devices.
Internet Connection: A stable internet connection is necessary for downloading Flutter SDK, IDEs,
packages from Pub, and accessing online resources and documentation.
Storage: Sufficient storage space on the computer to install Flutter SDK, IDEs, and other development
tools, as well as to store project files and dependencies.
By meeting these software and hardware requirements, students can effectively engage in UI design
laboratory sessions with Flutter, develop mobile applications, and gain practical experience in buildinguser
interfaces for various platforms.
MinimumSystemrequirements:
The minimum system requirements for developing Flutter applications are relatively modest, but they may
vary slightly depending on the operating system and the specific development tools being used.
Herearethegeneral minimumsystem requirements:
ForWindows:
lOMoARcPSD|17292326
OperatingSystem:Windows7SP1orlater(64-bit)
Processor:IntelCore i3orAMDequivalent(64-bit)Memory(RAM):4GBRAMor more
Storage:2GB offree disk space
GraphicsCard:Integrated graphicsor dedicatedGPUwith DirectX9 support
InternetConnection:Requiredfordownloadingdevelopmenttools,SDKs,and dependencies
FormacOS:
OperatingSystem:macOS 10.12 (Sierra) orlater
Processor: Intel Core i3 or higher
Memory(RAM):4GBRAMormore
Storage: 2GB of free disk space
GraphicsCard:IntegratedgraphicsordedicatedGPU
InternetConnection:Requiredfordownloadingdevelopmenttools,SDKs,and dependencies
ForLinux:
Operating System: Ubuntu 16.04 LTS (Xenial Xerus) or later, or another Linux distribution with similar
support
Processor:IntelCore i3orAMDequivalentMemory (RAM):4GB RAMor more
Storage:2GB offree disk space
GraphicsCard:IntegratedgraphicsordedicatedGPU
InternetConnection:Requiredfordownloadingdevelopmenttools,SDKs,and dependencies
These are general guidelines, and the actual system requirements may vary depending on factors such as
the size and complexity of the Flutter projects, the number of plugins and dependencies used, and the
performanceofthedevelopmenttools(IDEs)[Link],runningemulatorsorsimulatorsfor testing
on mobile devices may require more system resources.
LabSession1:
a) InstallflutterandDart sdk
ToinstallFlutterandtheDartSDK,youcanfollowthese steps:
a) Download Flutter:Visit the Flutterwebsite's Get Started page and download the Flutter SDKfor your
operating system (Windows, macOS, or Linux).
b) Extract the Flutter SDK:After downloading, extract the contents of the compressed file to a location
on your computer where you want to store the Flutter SDK. For example, you can extract it toC:\flutter
on Windows, /Users/<your-username>/flutter on macOS, or ~/flutter on Linux.
c) Add Flutterto yourPATH: Update your system's PATH variable to include the Flutter bin directory.
This step allows you to execute Flutter commands from any directory in your terminal or command
prompt. The precise steps for updating the PATH vary depending on your operating system.
Windows:
FromtheStartsearchbar,type'env'andselect'Editthesystemenvironmentvariables'. Click on
'Environment Variables'.
Under'SystemVariables',findthe'Path'variable,selectit,andclick'Edit'.
Click'New'andaddthepathtothebindirectoryinsidetheFlutterdirectory(e.g.,C:\flutter\bin).Click 'OK' on all open
dialogs to save your changes.
e) Install Flutter dependencies: Depending on your development environment, you may need to install
additional dependencies, such asAndroid Studio to fully set up your Flutter development environment.
f) Download Dart SDK (if not bundled with Flutter): Flutter comes with the Dart SDK bundled, so if
you've installed Flutter, you should have the Dart SDK as well. However, if you need to install Dart
separately, you can download it from the Dart "SDK archive".
print('Mydoubleis:$myDouble');print('Mystringis:$myString');print('Mybooleanis:$myBool');
//Basicarithmeticoperationsintresult=myNumber+5;print('Resultofaddition:$result');
lOMoARcPSD|17292326
//Conditionalstatementsif(myBool){print('myBoolistrue');}else{print('myBoolisfalse');}
//Loopsfor(inti=0;i<5;i++){ print('Iteration
$i');
}
// Lists
List<int>numbers=[1,2,3,4,5];print('Firstelementofthelist:${numbers[0]}');print('Lengthofthe list:
${[Link]}');
// Maps
Map<String,int>ages={
'Kiran': 30,
'Raj': 25,
'Alekya':35,};print('Kiran\'sage:${ages['Kiran']}');}
Output:
Lab Session 2:
a) Explorevariousflutterwidgets
Flutter provides a rich set of widgets to build user interfaces for mobile,web,and desktop
[Link] widgets help in creating visually appealing and interactive UIs. Here are some of the
commonlyused Flutter widgets categorized by their functionalities:
LayoutWidgets:
Container: A versatile widget that can contain other widgets and provides options for
alignment,padding,margin, and decoration.
RowandColumn:Widgetsthatarrangetheirchildreninahorizontalorverticallinerespectively.
Stack:Allowswidgetstobestackedontopofeachother,enablingcomplexlayouts.
ListView and GridView: Widgets for displaying a scrollable list or grid of children, with support for
various layouts and scrolling directions.
Scaffold: Implements the basic material design layout structure, providing app bars, drawers, and floating
action buttons.
TextandStylingWidgets:
Text:Displaysastringoftextwithoptionsforstylingsuchasfontsize,color,and alignment.
RichText: Allows for more complex text styling and formatting, including different styles within thesame
text span.
TextStyle:AclassfordefiningtextstylesthatcanbeappliedtoTextwidgets.
InputWidgets:
TextField:Awidgetforacceptinguserinputastext,withoptionsforcustomizationand validation.
Checkbox and Radio: Widgets for selecting from a list of options, either through checkboxes or radio
buttons.
DropdownButton:Providesadropdownmenuforselectingfromalistofoptions.
ButtonWidgets:
ElevatedButton and TextButton: Widgets for displaying buttons with different styles and customization
options.
GestureDetector: A versatile widget that detects gestures such as taps, swipes, and drags, allowing for
custom interactions.
NavigationWidgets:
Navigator:Managesastackofroute objectsandtransitionsbetweendifferent screensorpagesinthe app.
AnimationWidgets:
AnimatedContainer: An animated version of the Container widget, with support for transitioning
properties over a specified duration.
MaterialDesignWidgets:
AppBar:Amaterial designapp barthattypicallycontainsatitle,leadingandtrailingwidgets,andactions.
BottomNavigationBar: Provides a navigation bar at the bottom of the screen for switching betwee
different screens or tabs.
Card:Displayscontentorganizedinacard-likestructurewithoptionalelevationandpadding.
Cupertino(iOS-style)Widgets:
CupertinoNavigationBar:AnavigationbarintheiOSstyle.
CupertinoTextField:AtextfieldwidgetwiththeiOSstyle.
These are just a few examples of the many widgets available in Flutter. Each widget comes with its set of
properties and customization options, allowing developers to create highly customizable and responsive
user interfaces.
b) UserimplementdifferentlayoutstructuresusingRow,Column,andStackwidgets
1. RowLayout:void main() {runApp(MyApp());
}
classMyAppextendsStatelessWidget{
@override
Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar:AppBar(
title: Text('Row Layout'),
),
body: Row(
mainAxisAlignment: [Link],
children:<Widget>[ Container( color:[Link],
width: 100,
height: 100,
),
Container(color: [Link],
width: 100,
height: 100,
),
Output:
2. Column Layout:
import'package:flutter/[Link]';
void main() {runApp(MyApp());
}
classMyAppextendsStatelessWidget{
@override
height: 100,
),
Container(color: [Link], width:100,
height: 100,
),
],
),
),
);
}
}
lOMoARcPSD|17292326
Output:
3. Stack Layout:
import'package:flutter/[Link]';voidmain(){runApp(MyApp()); }
classMyAppextendsStatelessWidget{@override
Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar:AppBar(
title: Text('Stack Layout'),
),
body: Stack( alignment:[Link], children:<Widget>[
),
Lab Session 3:
a) DesignaresponsiveUIthatadaptstodifferentscreensizes
import'package:flutter/[Link]';
void main() {runApp(MyApp());
}
classMyAppextendsStatelessWidget{
@override
Widget build(BuildContext context) { return MaterialApp( title: 'Responsive UI Demo', theme:
ThemeData( primarySwatch: [Link],
),
home: ResponsiveHomePage(),
);
}
}
classResponsiveHomePageextendsStatelessWidget{
@override
Widgetbuild(BuildContextcontext){
return Scaffold(appBar: AppBar(
title:Text('ResponsiveUIDemo'),
),
body: LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) { if([Link]<600){
return _buildNarrowLayout();
} else{
return _buildWideLayout();
}
},
),
);
}
Widget _buildNarrowLayout() {
return Center( child:Column(
mainAxisAlignment:[Link],
children: <Widget>[FlutterLogo(size: 100),
SizedBox(height:20),
Text(
'NarrowLayout',
style:TextStyle(fontSize:24),
),
SizedBox(height: 20), ElevatedButton( onPressed:(){},
child: Text('Button'),
),
],
),
);
}
Output:
MobileView:
lOMoARcPSD|17292326
DesktopView:
b) Implementmediaqueriesandbreakpointsforresponsiveness
import'package:flutter/[Link]';
classMyAppextendsStatelessWidget{
@override
Widget build(BuildContext context) { returnMaterialApp(
title: 'Responsive UI with Media Queries',
theme:ThemeData(primarySwatch: [Link],
),
home: ResponsiveHomePage(),
);
}
}
classResponsiveHomePageextendsStatelessWidget{
@override
Widgetbuild(BuildContextcontext){
return Scaffold(appBar: AppBar(
title:Text('ResponsiveUIwithMediaQueries'),
),
body: LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) { if([Link]<600){
return _buildMobileLayout();
}elseif([Link]<1200){ return_buildTabletLayout();
} else{
return _buildDesktopLayout();
}
},
),
);
}
Widget_buildMobileLayout(){
return Center( child: Column(
mainAxisAlignment:[Link],
children:<Widget>[FlutterLogo(size:100),
SizedBox(height:20),
Text(
'Mobile Layout',
style:TextStyle(fontSize:24),
),
SizedBox(height: 20), ElevatedButton( onPressed:(){},
child: Text('Button'),
),
],
),
);
}
Widget_buildTabletLayout(){
return Center( child: Row(
mainAxisAlignment:[Link],
children: <Widget>[FlutterLogo(size: 100),
SizedBox(width: 20), Column(
mainAxisAlignment:[Link],
children:<Widget>[
Text( 'TabletLayout',
style:TextStyle(fontSize:24),
),
SizedBox(height: 20), ElevatedButton( onPressed:(){},
child: Text('Button'),
),
],
),
],
),
);
}
Widget_buildDesktopLayout(){
return Center( child: Row(
mainAxisAlignment:[Link],
children: <Widget>[FlutterLogo(size: 100),
SizedBox(width: 20), Column(
mainAxisAlignment:[Link],
children:<Widget>[
Text(
'Desktop Layout', style:TextStyle(fontSize:24),
),
SizedBox(height: 20), ElevatedButton( onPressed:() {}, child:Text('Button'),
),
],
lOMoARcPSD|17292326
Output:
),
],
),
);
}
}
Output:
}
Lab Session4:
a) Setupnavigationbetweendifferentscreensusingnavigator
voidmain(){runApp(MyApp());
}
classMyAppextendsStatelessWidget{
@override
Widget build(BuildContext context) { return MaterialApp( title: 'Navigation Example', theme:
ThemeData( primarySwatch: [Link],
),
home: FirstScreen(),
);
}
}
classFirstScreenextendsStatelessWidget{
@override
Widgetbuild(BuildContextcontext){
return Scaffold(
appBar:AppBar( title:Text('FirstScreen'),
),
body: Center( child:ElevatedButton( onPressed:() {
//Navigatetothesecondscreen
[Link]( context,
MaterialPageRoute(builder:(context) =>SecondScreen()),
);
},
child:Text('GotoSecondScreen'),
),
),
);
}
}
classSecondScreenextendsStatelessWidget{
@override
Widget build(BuildContext context) { returnScaffold(
appBar:AppBar(
title:Text('SecondScreen'),
),
body: Center( child:ElevatedButton( onPressed:() {
//Navigatebacktothefirstscreen [Link](context);
},
child:Text('GobacktoFirstScreen'),
),
),
);
}
lOMoARcPSD|17292326
Output:
}
b) Implementnavigationwithnamedroutes
import'package:flutter/[Link]';
voidmain(){runApp(MyApp());}
classMyAppextendsStatelessWidget{
@override
Widgetbuild(BuildContextcontext){returnMaterialApp(
title:'NamedRoutesDemo',initialRoute:'/',routes:{ '/':
(context) =>HomeScreen(),
'/second':(context)=>SecondScreen(),
'/third': (context) =>ThirdScreen(),
},
);
}
}
classHomeScreenextendsStatelessWidget{
@override
Widgetbuild(BuildContextcontext){
return Scaffold(appBar: AppBar(
title:Text('HomeScreen'),
),
body: Center( child: ElevatedButton( onPressed: () { [Link](context,
'/second');
},
child:Text('GotoSecondScreen'),
),
),
);
}
}
classSecondScreenextendsStatelessWidget{
@override
Widgetbuild(BuildContextcontext){
returnScaffold(appBar:AppBar( title:Text('SecondScreen'),
),
body: Center( child:ElevatedButton( onPressed:() {
[Link](context,'/third');
},
child:Text('GotoThirdScreen'),
),
),
);
}
}
classThirdScreenextendsStatelessWidget{
@override
Widgetbuild(BuildContextcontext){
return Scaffold(appBar: AppBar(
title:Text('ThirdScreen'),
),
body: Center( child: ElevatedButton( onPressed:(){
[Link](context, [Link]('/'));
},
child:Text('GoBacktoHome'),
),
),
);
}
}
lOMoARcPSD|17292326
LabSession5:
a) Learnaboutstatefulandstatelesswidgets
InFlutter,widgetscanbecategorizedintotwomaintypesbasedontheirbehaviorregardingstate management:
stateful widgets and stateless widgets.
StatelessWidgets:
}Definition: Stateless widgets are widgets that do not have any mutable state. Once created, their properties
(configuration) cannot change.
Characteristics:
Theyareimmutableand lightweight.
Theyonlydependontheirconfigurationandthebuildcontextprovidedduringconstruction. Their
appearance (UI) is purely a function of their configuration.
TheyareidealforUIelementsthatdonotchangeovertime,suchasstatictextlabels,icons,orsimple buttons. import
'package:flutter/[Link]';
voidmain(){runApp(MyApp());
}
classMyAppextendsStatelessWidget{
@override
Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar:AppBar(
title: Text('Cards Example'),
),
body: CardList(),
), );
}
}
classCardListextendsStatelessWidget{
@override
Widget build(BuildContext context) {
[Link](itemCount:10,
itemBuilder: (context, index) { return CardItem( title:'Card$index',
subtitle: 'Subtitle $index',
);
},
);
}
}
classCardItemextendsStatelessWidget{finalStringtitle;finalStringsubtitle;
constCardItem({
Keykey,
@required [Link],
@[Link],
}):super(key:key);
@override
Widgetbuild(BuildContextcontext){
return Card(
margin: [Link](horizontal: 16, vertical: 8), child: ListTile( title:Text(title),
subtitle: Text(subtitle), leading: CircleAvatar(
child:Text('${[Link](0,1)}'),
),
onTap:(){
lOMoARcPSD|17292326
//Handlecardtap
},
),
);
Output:
b) Implementstatemanagementusingsetstateandprovider
StatefulWidgets:
Definition: Stateful widgets are widgets that maintain state, allowing them to change and update over time
in response to user actions, network events, or other factors.
Characteristics:
Theyhave anassociated mutablestate thatcanchange duringthe widget's lifetime.
ThestateisstoredinaseparateclassthatextendsStateandisassociatedwiththestatefulwidget. Changes
to the state trigger a rebuild of the widget's UI, allowing dynamic updates.
TheyareidealforUIelementsthatneedtochangeorreacttouserinteractions,suchasinputforms, animations, or
scrollable lists. import 'package:flutter/[Link]';
voidmain(){runApp(MyApp());
}
classMyAppextendsStatelessWidget{
@override
Widget build(BuildContext context) { returnMaterialApp(
home: CounterApp(),
);
}
}
classCounterAppextendsStatefulWidget{
@override
_CounterAppStatecreateState()=> _CounterAppState();
}
class_CounterAppStateextendsState<CounterApp>{int_counter= 0;
@override
Widgetbuild(BuildContextcontext){
return Scaffold(appBar: AppBar(
title:Text('CounterApp'),
),
body: Center( child:Column(
mainAxisAlignment: [Link], children:<Widget>[
Text(
'Counter:',
style:TextStyle(fontSize:24),
),
Text(
'$_counter',
style:TextStyle(fontSize:36,fontWeight:[Link]),
),
],
lOMoARcPSD|17292326
),
),
floatingActionButton:FloatingActionButton(onPressed:_incrementCounter,
tooltip: 'Increment',
child: Icon([Link]),
),
);
}
}
Output:
Stateful widgets are composed of two classes: the stateful widget itself (which extends StatefulWidget) and
itscorresponding stateclass(whichextends State).The stateclass isresponsibleformaintainingthe widget's
mutable state and updating the UI accordingly via the setState() method.
stateless widgets are static and immutable, while stateful widgets are dynamic and can change over time by
managing their internal state. Understanding the difference between these two types of widgets is essential
for designing and building efficient and responsive Flutter UIs.
void main() {
runApp(MyApp());
}
classMyAppextendsStatelessWidget{
@override
Widget build(BuildContext context) {
return MaterialApp(
home: CounterPage(),
);
}
}
classCounterPageextendsStatefulWidget{
@override
_CounterPageStatecreateState()=> _CounterPageState();
}
@override
Widgetbuild(BuildContextcontext){
return Scaffold(appBar: AppBar(
title:Text('CounterExample(setState)'),
),
body: Center( child: Column(
mainAxisAlignment:[Link],
children:<Widget>[
Text(
'CounterValue:',
),
Text(
'$_counter',
style:[Link](context).textTheme.headline4,
),
],
lOMoARcPSD|17292326
),
),
floatingActionButton: FloatingActionButton(onPressed: _incrementCounter, tooltip:'Increment',
child: Icon([Link]),
),
);
}
}
Output:
StateManagementusingproviderpackage:
// [Link] import 'package:flutter/[Link]'; import 'package:provider/[Link]'; import
'provider/movie_provider.dart'; import 'screens/home_screen.dart';
void main() {
runApp(ChangeNotifierProvider<MovieProvider>(
child: constMyApp(),
create:(_)=>MovieProvider(),//CreateanewChangeNotifier object
));
}
classMyAppextendsStatelessWidget{constMyApp({Key?key}):super(key:key);
@override
Widgetbuild(BuildContextcontext){
home: constHomeScreen(),
);
}
}
create a model folder for models and create file [Link] class Movie
{finalStringtitle;finalString?runtime;//howlongthismovieis(inminute)
Movie({[Link],[Link]});}
Createaproviderfolderandcreatemovie_provider.dartinsidetheprovider folder
// provider/movie_provider.dart import 'package:flutter/[Link]'; import 'dart:math'; import
'../models/[Link]';
//Alist ofmovies
finalList<Movie>initialData=[Link]( 50,
(index)=>Movie( title:"Moview$index", runtime:"${Random().nextInt(100)+60}
minutes"));
classMovieProviderwithChangeNotifier {
//Allmovies (thatwillbe displayedonthe Homescreen)finalList<Movie> _movies= initialData;
//Retrieveallmovies
List<Movie>getmovies =>_movies;
//screens/home_screen.dartimport'package:flutter/[Link]';import'package:provider/[Link]';
classHomeScreenextendsStatefulWidget{constHomeScreen({Key?key}):super(key:key);
@override
State<HomeScreen>createState()=>_HomeScreenState();
}
class_HomeScreenStateextendsState<HomeScreen>{
@override
Widgetbuild(BuildContextcontext){
returnScaffold(appBar:AppBar(
title:constText('StateManagementusingprovider'),
),
body: Padding(
padding: [Link](15), child: Column(
lOMoARcPSD|17292326
size:30,
),onPressed: () {
if(){
context
.read<MovieProvider>()
.addToList(currentMovie);
} else { context
.read<MovieProvider>()
.removeFromList(currentMovie);
}
},
),
),
);
}),
),
],
),
),
);
}
}
createmy_list_screen.dartinsidethescreensfolder
classMyListScreenextendsStatefulWidget{constMyListScreen({Key?key}):super(key:key);
@override
State<MyListScreen>createState()=> _MyListScreenState();
}
class_MyListScreenStateextendsState<MyListScreen>{
@override
Widgetbuild(BuildContextcontext){
finalmyList=[Link]<MovieProvider>().myList; return Scaffold( appBar:AppBar(
title:Text("MyList(${[Link]})"),
),
body: [Link](itemCount: [Link], itemBuilder:(_,index){
final currentMovie = myList[index];
return Card(
key:ValueKey([Link]), elevation: 4,
child: ListTile(
title:Text([Link]), subtitle:Text([Link]??''),
trailing: TextButton( child: const Text( 'Remove',
style:TextStyle(color:[Link]),
),onPressed: () {
[Link]<MovieProvider>().removeFromList(currentMovie);
},
),
),
);
}),
);
}
}
lOMoARcPSD|17292326
Output:
we use the provider package to manage state. We define a Counter class that extends ChangeNotifier, and
[Link],wecallnotifyListeners()toinform the
listeners about the change.
LabSession6:
a) CreatecustomwidgetsforspecificUIelements
import 'package:flutter/[Link]';
void main() {
runApp(MyApp());
}
classMyAppextendsStatelessWidget{
@override
Widgetbuild(BuildContextcontext){
returnMaterialApp( home:
Scaffold(appBar:AppBar(
title:Text('CustomWidgetExample'),
),
body: Column(
mainAxisAlignment: [Link],
children: <Widget>[ Padding( padding: [Link](8.0), child:
CustomTextField( hintText: 'Enter your name', onChanged: (value) {
print('Namechanged: $value');
},
),
),
SizedBox(height: 20),
Padding( padding: [Link](8.0), child: CustomTextField( hintText:
'Enter Email', onChanged: (value) {
print('Namechanged: $value');
},
),
),
SizedBox(height: 20),
Padding( padding: [Link](8.0), child: CustomTextField( hintText:
'Enter Roll Number', onChanged: (value) {
print('Namechanged: $value');
},
),
),
SizedBox(height: 20), CustomButton( text:'PressMe', onPressed: () {
print('Buttonpressed!');
},
),
],
),
),
);
}
}
constCustomButton({ Key?key,
@required [Link],
@required [Link],
}):super(key:key);
@override
Widget build(BuildContext context) { return ElevatedButton( onPressed:onPressed,
child: Text(text!),
);
}
}
@override
Widgetbuild(BuildContextcontext){
return TextField(onChanged: onChanged, decoration: InputDecoration( hintText:hintText,
border: OutlineInputBorder(),
),
);
}
}
Output:
b) Applystylingusingthemesandcustomstyles
InFlutter,youcanapplystyling toyourwidgetsusingthemes
and custom styles to maintain consistencyand make your UI more visually
appealing.
import'package:flutter/[Link]';
voidmain(){runApp(MyApp());
}
ClassMyAppextendsStatelessWidget {
@override
Widget build(BuildContext context){ return
MaterialApp( theme: ThemeData(
//Definetheoverallthemeof the app primaryColor:
[Link], accentColor:[Link],
fontFamily:'Roboto', textTheme: TextTheme(
headline1:TextStyle(fontSize: 24, fontWeight:
[Link]), bodyText1: TextStyle(fontSize: 16),
),
elevatedButtonTheme: ElevatedButtonThemeData(
style: [Link]( primary:[Link],
textStyle: TextStyle(fontSize: 18),
padding: [Link](horizontal: 20, vertical: 15), shape:
RoundedRectangleBorder(
borderRadius: [Link](10),
),
),
),
),
home: HomePage(),
);
}
classHomePageextendsStatelessWidget{
@override
Widgetbuild(BuildContextcontext){
return Scaffold(appBar: AppBar( title:
Text('Styling Example'),
),
body: Center( child:Column(
mainAxisAlignment: [Link], children:<Widget>[
Text(
'WelcometoMyApp',
style:[Link](context).textTheme.headline1,
),
SizedBox(height: 20), ElevatedButton( onPressed:(){},
child: Text('Get Started'),
),
],
),
lOMoARcPSD|17292326
),
);
}
}
Output:
In this example:
WedefineacustomthemeusingThemeDataandapplyittotheentireappusingthethemepropertyof MaterialApp.
Thethemespecifiesprimaryandaccentcolors,acustomfontfamily,andtextstylesfordifferenttext elements
(headline6 and bodyText2).
In the HomePage widget, we [Link](context) to access the custom theme properties and apply them
to various widgets such as Text and ElevatedButton.
WealsodemonstratecustomstylingforaContainerwidgetwithacustombackgroundcolorandborder radius.
Using themes and custom styles like this helps maintain a consistent visual identity throughout your app
and makes it easier to manage and update styling across multiple widgets.
Lab Session7:
a) Designaformwithvariousinputfields
form with various input fields such as text fields, checkboxes, radio buttons, and a dropdown menu import
'package:flutter/[Link]';
voidmain(){runApp(MyApp());
}
classMyAppextendsStatelessWidget{
@override
Widget build(BuildContext context) { return MaterialApp( title:'FormExample',
theme: ThemeData(
primarySwatch: [Link],
),
home: FormPage(),
);
}
}
classFormPageextendsStatefulWidget{
@override
_FormPageStatecreateState()=> _FormPageState();
}
class_FormPageStateextendsState<FormPage>{final_formKey=GlobalKey<FormState>();
bool_subscribeToNewsletter=false;String_selectedCountry='USA';
@override
Widgetbuild(BuildContextcontext){
return Scaffold(appBar: AppBar(
title:Text('FormExample'),
),
decoration:InputDecoration(labelText:'Name'),
onSaved: (value) {
_name = value;
},
),
lOMoARcPSD|17292326
),
SizedBox(height: 20), ElevatedButton( onPressed:() {
_formKey.[Link](); //Submittheformdata print('Name:
$_name'); print('Email:$_email');
print('Subscribeto Newsletter: $_subscribeToNewsletter'); print('Country:$_selectedCountry');
},
child:Text('Submit'),
),
],
),
),
),
);
}
}
Output:
lOMoARcPSD|17292326
b) Implementformvalidationanderrorhandling
import'package:flutter/[Link]';
classMyAppextendsStatelessWidget{
@override
Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar:AppBar(
title: Text('Form Example'),
),
classFormWidgetextendsStatefulWidget{
@override
_FormWidgetStatecreateState()=>_FormWidgetState();
}class_FormWidgetStateextendsState<FormWidget>{final_formKey= GlobalKey<FormState>();
String _name;
String _email;
String _password;
String _phone;
String_address; @override
Widgetbuild(BuildContextcontext){
return Form( key: _formKey, child:Column(
crossAxisAlignment: [Link],
children:<Widget>[TextFormField(
decoration:InputDecoration(labelText:'Name'),
validator:(value){ if([Link]) {
return'Pleaseenter your name';
} return null;
},
onSaved:(value)=>_name = value,
),
SizedBox(height: 16), TextFormField( decoration: InputDecoration(labelText: 'Email'),
keyboardType:[Link], validator:(value){ if ([Link]) {
return'Pleaseenter youremail';
}
//Addmorecomplex emailvalidationlogicif needed return null;
},
onSaved:(value)=>_email = value,
),
SizedBox(height: 16), TextFormField(
decoration:InputDecoration(labelText:'Password'),
obscureText:true, validator:(value) { if([Link]){
return'Pleaseenter a password';
}
//Addmorecomplexpasswordvalidationlogicif needed return null;
},
onSaved:(value)=>_password = value,
),
SizedBox(height: 16), TextFormField(
decoration: InputDecoration(labelText: 'Phone'), keyboardType:[Link],
validator: (value) { if ([Link]) {
return'Pleaseenteryour phone number';
}
//Addmorecomplexphonenumbervalidationlogicifneeded returnnull;
},
onSaved:(value)=> _phone= value,
),
SizedBox(height: 16), TextFormField(
decoration: InputDecoration(labelText: 'Address'), maxLines: 3, validator:(value){
if ([Link]) {
return'Pleaseenter youraddress';
} return null;
},
onSaved:(value)=>_address= value,
),
SizedBox(height: 16), ElevatedButton( onPressed:_submitForm,
child: Text('Submit'),
),
],
),
);
}
//Performformsubmissionwiththesavedformdata
print('Form submitted:'); print('Name: $_name');
Output:
LabSession 8:
a) AddanimationstoUIelementsusingflutter'sanimationframework
import'package:flutter/[Link]';
classMyAppextendsStatelessWidget{
@override
Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar:AppBar(
title: Text('Animation Example'),
),
body:AnimationWidget(),
),
);
}
}
classAnimationWidgetextendsStatefulWidget{
@override
_AnimationWidgetStatecreateState()=>_AnimationWidgetState();
}
class_AnimationWidgetStateextendsState<AnimationWidget>
with SingleTickerProviderStateMixin {
AnimationController _controller;
Animation<double>_animation;
@overridevoidinitState() { [Link]();
_controller = AnimationController( duration:Duration(seconds:1),
vsync: this,
);
_animation=Tween<double>(begin:0,end:300).animate(_controller)
..addListener((){
setState((){});//Triggerrebuildwhenanimationvaluechanges
});}
@override
Widgetbuild(BuildContextcontext){
return Center( child: Column(
mainAxisAlignment: [Link], children:<Widget>[
Container( width: _animation.value, height: _animation.value, color:[Link],
child: FlutterLogo(size: 100),
),
SizedBox(height: 20), ElevatedButton( onPressed:(){
if (_controller.status == [Link]) {
_controller.reverse();
lOMoARcPSD|17292326
} else {
_controller.forward();
} },
child:Text(
_controller.status==[Link]
? 'ReverseAnimation'
: 'StartAnimation',
),
),
],
),
);
}
Output:
WedefineanAnimationobjectwithTweentodefinetherangeofvaluesfortheanimation. I
nsidetheinitState()method,[Link] addListener() to
trigger a rebuild when the animation value changes.
TheElevatedButtontogglestheanimationbetweenforwardandreversebasedonthestatusofthe animation
controller.
Youcancustomizetheanimationfurtherbyadjustingtheduration,addingcurves,orchainingmultiple animations
together.
b) Experimentwithdifferenttypesofanimationslikefade,slide,etc.
FadeAnimation:
import 'package:flutter/[Link]';
voidmain(){runApp(MyApp());
}
classMyAppextendsStatelessWidget{
@override
Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar:AppBar(
title: Text('Fade Animation Example'),
),
body: FadeAnimation(),
),
);
}
}
classFadeAnimationextendsStatefulWidget{
@override
_FadeAnimationStatecreateState()=> _FadeAnimationState();
}
class_FadeAnimationStateextendsState<FadeAnimation>
with SingleTickerProviderStateMixin {
AnimationController _controller;
Animation<double>_animation;
@overridevoidinitState() { [Link]();
_controller=AnimationController(vsync:this,
duration: Duration(seconds: 2),
);
_animation=Tween<double>(
begin: 0.0,
end: 1.0,
).animate(_controller);
_controller.forward();
}
@override
Widgetbuild(BuildContextcontext){
return Center( child: FadeTransition( opacity: _animation, child: Container( width:
200, height: 200,
color: [Link],
),
),
);
}
}
}
SlideAnimation:
import 'package:flutter/[Link]';
voidmain(){runApp(MyApp());
}
classMyAppextendsStatelessWidget{
@override
Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar:AppBar(
title: Text('Slide Animation Example'),
),
body: SlideAnimation(),
),
);
}
}
classSlideAnimationextendsStatefulWidget{
@override
_SlideAnimationStatecreateState()=>_SlideAnimationState();} class
_SlideAnimationState extends State<SlideAnimation>
withSingleTickerProviderStateMixin{AnimationController_controller;
Animation<Offset> _animation;
@overridevoidinitState() { [Link]();
_controller=AnimationController(vsync:this,
duration: Duration(seconds: 2),
);
_animation=Tween<Offset>( begin:Offset(-1.0,0.0), end:Offset(0.0,0.0),
).animate(_controller);
_controller.forward();
}
@override
Widgetbuild(BuildContextcontext){
return Center( child: SlideTransition( position: _animation, child: Container( width:
200, height: 200,
color: [Link],
),
),
);}
ScaleAnimation:import'package:flutter/[Link]';
voidmain(){runApp(MyApp());
}
classMyAppextendsStatelessWidget{
@override
Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar:AppBar(
title: Text('Scale Animation Example'),
),
body: ScaleAnimation(),
), );
}
}
classScaleAnimationextendsStatefulWidget{
@override
_ScaleAnimationStatecreateState()=>_ScaleAnimationState();
}
class_ScaleAnimationStateextendsState<ScaleAnimation>
with SingleTickerProviderStateMixin {
AnimationController _controller;
Animation<double>_animation;
@overridevoidinitState() { [Link]();
_controller=AnimationController(vsync:this,
duration: Duration(seconds: 2),
);
_animation=Tween<double>(
begin: 0.0, end: 1.0,
).animate(_controller);
_controller.forward();
}
@override
Widgetbuild(BuildContextcontext){
return Center( child: ScaleTransition( scale: _animation, child: Container( width:
200, height: 200,
color: [Link],
),
),
);}
Output:
LabSession9:
a) [Link]:dependencies:flutter: sdk:
flutter
http: ^0.13.3
import'dart:convert';import'package:flutter/[Link]';import'package:http/[Link]'ashttp; void
main() {runApp(MyApp());
}
classMyAppextendsStatelessWidget{
@override
Widget build(BuildContext context) { returnMaterialApp(
home: HomePage(),
);
}
}
classHomePageextendsStatefulWidget{
@override
_HomePageStatecreateState()=>_HomePageState();
}
class_HomePageStateextendsState<HomePage>{
List<dynamic> _data = [];
@override
voidinitState(){
[Link]();
_fetchDataFromApi();
}
if([Link]==200){
setState(() {
_data =[Link]([Link]);
});
} else {
throwException('Failedtoloaddata');
}
}
@override
Widgetbuild(BuildContextcontext){
return Scaffold(appBar: AppBar(
lOMoARcPSD|17292326
title:Text('APIDataExample'),
),
body: [Link](itemCount: _data.length, itemBuilder: (context, index) { return
ListTile( title: Text(_data[index]['title']),
subtitle:Text(_data[index]['body']),
);
},
),
);
}
Output:
b) DisplaythefetcheddatainameaningfulwayintheUI
displaythefetcheddatainameaningfulwayintheUI,wecanuseamorestructuredlayoutratherthanjust displaying
the data in a list. We'll create a custom widget to represent each post fetched from theAPI, and display
them in a scrollable list. import 'dart:convert'; import 'package:flutter/[Link]'; import
'package:http/[Link]' as http;
voidmain(){ runApp(MyApp());
}
classMyAppextendsStatelessWidget{
@override
Widgetbuild(BuildContextcontext){returnMaterialApp(home: HomePage(),
);
}}
classHomePageextendsStatefulWidget{
@override
_HomePageStatecreateState()=>_HomePageState();
}
class_HomePageStateextendsState<HomePage>{
List<dynamic>_data=[];bool_isLoading=false;
@overridevoid initState() {
[Link]();
_fetchDataFromApi();
}
finalresponse=[Link]([Link]('[Link] if
([Link] == 200) {
setState((){
_data =[Link]([Link]);
_isLoading = false;
});
} else {
throwException('Failedtoloaddata');
}
}
@override
Widgetbuild(BuildContextcontext){
return Scaffold(appBar: AppBar( title:
Text('API Data Example'),
),
body: _isLoading?Center(
child: CircularProgressIndicator(),
)
:[Link]( itemCount:_data.length, itemBuilder:(context,index){
return PostCard( title: _data[index]['title'],
body: _data[index]['body'],
);
},
),
);
}
}
classPostCardextendsStatelessWidget{finalStringtitle;finalStringbody;
@override
Widgetbuild(BuildContextcontext){
return Card(
lOMoARcPSD|17292326
child:Column(
crossAxisAlignment: [Link],
children: <Widget>[ Text( title,
style:TextStyle(fontSize:18,fontWeight:[Link]),
),
SizedBox(height: 8), Text( body,
style: TextStyle(fontSize: 16),
), ],
),
),
);
}
}
Output:
We'veaddedaloadingindicator(CircularProgressIndicator)toindicatewhendataisbeingfetched. The
fetched data is displayed as a list of PostCard widgets, each representing a post from theAPI.
ThePostCard widget displaysthe title and bodyof each postin a structured mannerusing a Cardlayout.
Lab Session10:
a) WriteunittestsforUIcomponents
Unit tests for UI components in Flutter typically involves using the flutter_test package along with the test
package for writing tests.
Here'show we can write unittestsfor the PostCard widget:
void main() {testWidgets('PostCard displays title and body', (WidgetTester tester) async { //Buildour
widget and trigger a frame. await [Link]( MaterialApp( home: PostCard(
title: 'Test Title',
body:'TestBody',
),
), );
// Verify that the title and body are displayed correctly. expect([Link]('Test Title'), findsOneWidget);
expect([Link]('Test Body'), findsOneWidget);
});
testWidgets('PostCard widget has correct styling', (WidgetTester tester) async { // Build our widget and
trigger a frame. await [Link]( MaterialApp( home: PostCard(
title: 'Test Title',
body:'TestBody',
),
), );
finalbodyText=[Link]<Text>([Link]('TestBody')); expect([Link],16);
});
}
Inthis test:
WeusethetestWidgetsfunctionfromtheflutter_testpackagetodefineourtest cases.
In the first test case, weensure thatthe PostCardwidget correctly displaysthe provided title and body text. In
the second test case, we verify that the text styles applied to the title and body texts are as [Link] use
expect statements to assert that the expected UI elements are found on the screen and that their properties
match the expected values.
Makesuretoreplace your_appwiththe appropriatepackagenamewhereyourPostCard widget resides.
Make sure to provide different test scenarios and edge cases to ensure comprehensive test coverage for
your UI components.
b) Useflutter'sdebuggingtoolstoidentifyandfixissues?
demonstrate the use of Flutter's debugging tools, let's consider a scenario where we have a simple counter
app, but there's a bug where the counter is not incrementing when the "+" button is pressed. We'll use
Flutter's debugging tools to identify and fix this issue. Here's the code for the counter app: import
'package:flutter/[Link]';
lOMoARcPSD|17292326
voidmain(){runApp(MyApp());
classMyAppextendsStatelessWidget{
@override
Widget build(BuildContext context) { returnMaterialApp(
home: CounterApp(),
);
}
}
classCounterAppextendsStatefulWidget{
@override
_CounterAppStatecreateState()=> _CounterAppState();
}
class_CounterAppStateextendsState<CounterApp>{int_counter=0; void
_incrementCounter() {
_counter++;}
@override
Widgetbuild(BuildContextcontext){
return Scaffold(appBar: AppBar(
title:Text('CounterApp'),
),
body: Center( child:Column( mainAxisAlignment:[Link],
children:<Widget>[
Text(
'Counter:',
style:TextStyle(fontSize:24),
),
Text(
'$_counter',
style:TextStyle(fontSize:36,fontWeight:[Link]),
),
],
),
),
floatingActionButton:FloatingActionButton(onPressed:_incrementCounter,
tooltip: 'Increment',
child: Icon([Link]),
),
);
}
}
Now,let'suseFlutter'sdebuggingtoolstoidentifyandfixthe issue:
WidgetInspector:First,let'sinspectthewidgettreetoseeifthe"+"buttoniscorrectlywiredtothe
_incrementCountermethod.Wecandothisbyrunningtheappindebugmodeandenablingthewidget
[Link] can dothis by clicking the "Open DevTools" buttonin your IDE (Android Studio/IntelliJ
IDEAor Visual Studio Code) or running the following command in your terminal: flutter run –debug
Once the app is running, click on the "Toggle Widget Inspector" button in the top-right corner of your
app. Then, select the FloatingActionButton widget representing the "+" button. Ensure that the
onPressed callback is correctly set to _incrementCounter.
DebuggingConsole:Ifeverythinglooksfineinthewidgetinspector,wecanaddsomedebugprint statementsto
the_incrementCounter method tosee ifit'sbeing called whenthe button [Link] the
_incrementCountermethodasfollows: void_incrementCounter(){print('Incrementing counter');
_counter++;
}
Now, run the app again in debug mode and observe the console output when you press the "+" button. If you
don't see the "Incrementing counter" message in the console, it means the _incrementCounter method is not
being called.
Breakpoints:As a final step, let's set a breakpoint in the _incrementCounter method and debug the app to see
if it's being hit. Add a breakpoint by clicking on the left margin of the _incrementCounter method in your
code editor. Then, run the app in debug mode and press the "+" button. The app should pause at the
breakpoint, allowing you to inspect the current state and variables. You can step through the code to see if
there are any issues with the execution flow.
By using Flutter's debugging tools, you should be able to identify the issue with the counter app and fix it
accordingly. In this case, if the debugging process reveals that the _incrementCounter method is not being
called, you can double-check the onPressed callback of the FloatingActionButton to ensure it's correctly
wired to the _incrementCounter method.