0% found this document useful (0 votes)
100 views

Flutter For Beginners

Flutter lab for beginners

Uploaded by

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

Flutter For Beginners

Flutter lab for beginners

Uploaded by

shek25945
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 39

UI DESIGN-FLUTTER Lab

List of Experiments: Students need to implement the following experiments:


1.a) Install Flutter and Dart SDK.

b) Write a simple Dart program to understand the language basics.

2.a) Explore various Flutter widgets (Text, Image, Container, etc.).

b) Implement different layout structures using Row, Column, and Stack widgets.

3.a) Design a responsive UI that adapts to different screen sizes.

b)Implement media queries and breakpoints for responsiveness.

4.a) Set up navigation between different screens using Navigator.

b)Implement navigation with named routes.


5.a) Learn about statefull and stateless widgets.
b) Implement state management using set State and Provider.

6.a)Create custom widgets for specific UI elements

b) Apply styling using themes and custom styles.

7. a) Design a form with various input fields.

b) Implement form validation and error handling.

8. a) Add animations to UI elements using Flutter's animation framework.

b) Experiment with different types of animations (fade, slide, etc.).

9. a) Fetch data from a REST API.

b) Display the fetched data in a meaningful way in the UI.

10. a) Write unit tests for UI components.

b) Use Flutter's debugging tools to identify and fix issues.

TEXT BOOK:
1. Marco L. Napoli, Beginning Flutter: A Hands-on Guide to App Development
1.a) Install Flutter and Dart SDK.
Ans) Dart SDK is a pre-compiled version so we have to download and extract it
only. For this follow the below-given instructions: Step 1: Download Dart SDK.
Download Dart SDK from the Dart SDK archive page. The URL
is: https://dart.dev/tools/sdk/archive

Click on DART SDK to download SDK for Windows 64-Bit Architecture. The
download will start and a zip file will be downloaded. Note: To download SDK for
any other OS select OS of your choice. Step 2: Extract the downloaded zip file.
Extract the contents of downloaded zip file and after extracting contents of zip file
will be as shown:
Step 3: Running Dart. Now open bin folder and type “cmd” as given below:

Command Prompt will open with our desired path of bin folder and now type dart”.

And now we are ready to use dart through bin folder but setting up the path in environment variables
will ease our task of Step3 and we can run dart from anywhere in the file system using command
prompt.
Step 4: Setting up path in environment variables. Open Environment Variables from
advanced system settings and add Path in System Variables as depicted in image:
Now we are done to use Dart from anywhere in the file system.

Step 5: Run Dart Using cmd


1.b) Write a simple Dart program to understand the language basics.
void main(){
var firstName = "John";
var lastName = "Doe";
print("Full name is $firstName $lastName");
}
Output: Full name is John Doe

void main() {
int num1 = 10; //declaring number1
int num2 = 3; //declaring number2

// Calculation
int sum = num1 + num2;
int diff = num1 - num2;
int mul = num1 * num2;
double div = num1 / num2; // It is double because it outputs number with
decimal.

// displaying the output print("The sum is $sum");


print("The diff is $diff");
print("The mul is $mul");
print("The div is $div");
}

Output:
The sum is 13
The diff is 7
The mul is 30
The div is 3.3333333333333335

2.a) Explore various Flutter widgets (Text, Image, Container, etc.).


Text Widget:
import 'package:flutter/material.dart';

void main() { runApp(MyApp()); }

class MyApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.green,
),
home: MyTextPage()
);
}
}
class MyTextPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title:Text("Text Widget Example")
),
body: Center(
child:Text(
"Hello World! This is a Text Widget.",
style: TextStyle(
fontSize: 35,
color: Colors.purple,
fontWeight: FontWeight.w700,
fontStyle: FontStyle.italic,
letterSpacing: 8,
wordSpacing: 20,
backgroundColor: Colors.yellow,
shadows: [
Shadow(color: Colors.blueAccent, offset: Offset(2,1), blurRadius:10)
]
),
)
),
);
}
}

Output: When we run this application in the emulator or device, we should get the UI similar to the
below screenshot:

Image Widget:
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Flutter Image Demo'),
),
body: Center(
child: Column(
children: <Widget>[
Image.asset('assets/tablet.png'),
Text(
'A tablet is a wireless touch screen computer that is smaller than a notebook but larger than a
smartphone.',
style: TextStyle(fontSize: 20.0),
)
],
),
),
),
);
}
}

Output:

Container Widget:
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

/// This Widget is the main application widget.


class MyApp extends StatelessWidget {

@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyContainerWidget(),
);
}
}

class MyContainerWidget extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Flutter Container Example"),
),
body: Container(
width: double.infinity,
height: 150.0,
color: Colors.green,
margin: EdgeInsets.all(25),
padding: EdgeInsets.all(35),
alignment: Alignment.center,
transform: Matrix4.rotationZ(0.1),
child: Text("Hello! I am in the container widget!!",
style: TextStyle(fontSize: 25)),
),
),
);
}
}

Output:

When we run this app, it will give the following screenshot:


2.b) Implement different layout structures using Row, Column, and Stack widgets

Row widgets:
import 'package:flutter/material.dart';

void main() { runApp(MyApp()); }


class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage()
);
}
}

class MyHomePage extends StatefulWidget {


@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {


@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Flutter Row Example"),
),
body: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children:<Widget>[
Container(
margin: EdgeInsets.all(12.0),
padding: EdgeInsets.all(8.0),
decoration:BoxDecoration(
borderRadius:BorderRadius.circular(8),
color:Colors.green
),
child: Text("React.js",style: TextStyle(color:Colors.yellowAccent,fontSize:25),),
),
Container(
margin: EdgeInsets.all(15.0),
padding: EdgeInsets.all(8.0),
decoration:BoxDecoration(
borderRadius:BorderRadius.circular(8),
color:Colors.green
),
child: Text("Flutter",style: TextStyle(color:Colors.yellowAccent,fontSize:25),),
),
Container(
margin: EdgeInsets.all(12.0),
padding: EdgeInsets.all(8.0),
decoration:BoxDecoration(
borderRadius:BorderRadius.circular(8),
color:Colors.green
),
child: Text("MySQL",style: TextStyle(color:Colors.yellowAccent,fontSize:25),),
)
]
),
);
}
}

Output:

When we run this app, we should get the UI as the below screenshot.
Column widgets:

import 'package:flutter/material.dart';
void main() { runApp(MyApp()); }
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage()
);
}
}

class MyHomePage extends StatefulWidget {


@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {


@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Flutter Column Example"),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children:<Widget>[
Container(
margin: EdgeInsets.all(20.0),
padding: EdgeInsets.all(12.0),
decoration:BoxDecoration(
borderRadius:BorderRadius.circular(8),
color:Colors.red
),
child: Text("React.js",style: TextStyle(color:Colors.yellowAccent,fontSize:20),),
),
Container(
margin: EdgeInsets.all(20.0),
padding: EdgeInsets.all(12.0),
decoration:BoxDecoration(
borderRadius:BorderRadius.circular(8),
color:Colors.red
),
child: Text("Flutter",style: TextStyle(color:Colors.yellowAccent,fontSize:20),),
),
Container(
margin: EdgeInsets.all(20.0),
padding: EdgeInsets.all(12.0),
decoration:BoxDecoration(
borderRadius:BorderRadius.circular(8),
color:Colors.red
),
child: Text("MySQL",style: TextStyle(color:Colors.yellowAccent,fontSize:20),),
)
]
),
);
}
}
Output:
When we run this app, we should get the UI as the below screenshot.

Stack Widget:
The below code explains how to use the stack widget in Flutter. In this code, we are going to try most
of the essential attributes of the stack widget.

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

/// This Widget is the main application widget.


class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(

home: MyStackWidget(),
);
}
}

class MyStackWidget extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Flutter Stack Widget Example"),
),
body: Center(
child: Stack(
fit: StackFit.passthrough,
overflow: Overflow.visible,
children: <Widget>[
// Max Size Widget
Container(
height: 300,
width: 400,
color: Colors.green,
child: Center(
child: Text(
'Top Widget: Green',
style: TextStyle(color: Colors.white, fontSize: 20),
),
),
),
Positioned(
top: 30,
right: 20,
child: Container(
height: 100,
width: 150,
color: Colors.blue,
child: Center(
child: Text(
'Middle Widget',
style: TextStyle(color: Colors.white, fontSize: 20),
),
),
),
),

Positioned(
top: 30,
left: 20,
child: Container(
height: 100,
width: 150,
color: Colors.orange,
child: Center(
child: Text(
'Bottom Widget',
style: TextStyle(color: Colors.white, fontSize: 20),

),
),
)
),
],
),
)
),
);
}
}

Output:

When we run the app, we should get the UI of the screen similar to the below screenshot:

3.a) Implement Design a responsive UI that adapts to different screen sizes Flutter.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Responsive UI Example',
home: ResponsiveHome(),
);
}
}

class ResponsiveHome extends StatelessWidget {


@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Responsive UI')),
body: LayoutBuilder(
builder: (context, constraints) {
// Determine screen size
bool isWideScreen = constraints.maxWidth > 600;
return Padding(
padding: EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
// Responsive Image
Container(
width: isWideScreen ? 300 : 150,
height: isWideScreen ? 300 : 150,
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage('https://via.placeholder.com/300'),
fit: BoxFit.cover,
),
borderRadius: BorderRadius.circular(15),
),
),
SizedBox(height: 20),
// Responsive Text
Text(
'Welcome to Responsive Flutter UI!',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: isWideScreen ? 24 : 18,
fontWeight: FontWeight.bold,
),
),
SizedBox(height: 20),
// Responsive Button
ElevatedButton(
onPressed: () {},
child: Text('Click Me'),
style: ElevatedButton.styleFrom(
padding: EdgeInsets.symmetric(
horizontal: isWideScreen ? 30 : 15,
vertical: isWideScreen ? 15 : 10,
),
),
),
],
),
);
},
),
);
}
}

Output:
Visual Layout

Narrow Screen (e.g., phone):

+---------------------+
| Responsive UI | <- App Bar
+---------------------+
| |
| [ Image ] | <- Smaller image
| |
| Welcome to | <- Smaller text
| Responsive Flutter |
| UI! |
| |
| [Click Me] | <- Smaller button
+---------------------+

Wide Screen (e.g., tablet):

+---------------------+
| Responsive UI | <- App Bar
+---------------------+
| |
| [ Image ] | <- Larger image
| |
| Welcome to | <- Larger text
| Responsive Flutter |
| UI! |
| |
| [ Click Me ] | <- Larger button
+---------------------+

3.b)Implement media queries and breakpoints for responsiveness Flutter


import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Responsive UI Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: ResponsiveHome(),
);
}
}

class ResponsiveHome extends StatelessWidget {


@override
Widget build(BuildContext context) {
// Get screen size using MediaQuery
final screenSize = MediaQuery.of(context).size;
final isMobile = screenSize.width < 600; // Mobile breakpoint
final isTablet = screenSize.width >= 600 && screenSize.width < 1200; // Tablet breakpoint
final isDesktop = screenSize.width >= 1200; // Desktop breakpoint

return Scaffold(
appBar: AppBar(title: Text('Responsive UI')),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
// Header
Container(
width: double.infinity,
padding: EdgeInsets.all(16),
color: Colors.blueAccent,
child: Text(
'Responsive Header',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: isDesktop ? 28 : isTablet ? 24 : 20,
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
),
SizedBox(height: 20),
// Content Area
Expanded(
child: Row(
children: [
// Left Column
Expanded(
child: Column(
children: [
Container(
margin: EdgeInsets.symmetric(vertical: 10),
height: isDesktop ? 200 : isTablet ? 160 : 120,
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage('https://via.placeholder.com/300'),
fit: BoxFit.cover,
),
borderRadius: BorderRadius.circular(10),
),
),
Text(
'Image 1',
style: TextStyle(fontSize: isDesktop ? 18 : isTablet ? 16 : 14),
),
SizedBox(height: 20),
Container(
margin: EdgeInsets.symmetric(vertical: 10),
height: isDesktop ? 200 : isTablet ? 160 : 120,
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage('https://via.placeholder.com/300'),
fit: BoxFit.cover,
),
borderRadius: BorderRadius.circular(10),
),
),
Text(
'Image 2',
style: TextStyle(fontSize: isDesktop ? 18 : isTablet ? 16 : 14),
),
],
),
),

// Right Column (only on tablet and desktop)


if (isTablet || isDesktop) SizedBox(width: 20),
if (isTablet || isDesktop)
Expanded(
child: Column(
children: [
Container(
margin: EdgeInsets.symmetric(vertical: 10),
height: isDesktop ? 200 : isTablet ? 160 : 120,
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage('https://via.placeholder.com/300'),
fit: BoxFit.cover,
),
borderRadius: BorderRadius.circular(10),
),
),
Text(
'Image 3',
style: TextStyle(fontSize: isDesktop ? 18 : isTablet ? 16 : 14),
),
SizedBox(height: 20),
Container(
margin: EdgeInsets.symmetric(vertical: 10),
height: isDesktop ? 200 : isTablet ? 160 : 120,
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage('https://via.placeholder.com/300'),
fit: BoxFit.cover,
),
borderRadius: BorderRadius.circular(10),
),
),
Text(
'Image 4',
style: TextStyle(fontSize: isDesktop ? 18 : isTablet ? 16 : 14),
),
],
),
),
],
),
),
// Footer Section
SizedBox(height: 20),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ElevatedButton(
onPressed: () {},
child: Text('Button 1'),
),
ElevatedButton(
onPressed: () {},
child: Text('Button 2'),
),
],
),
],
),
),
);
}
}
Output: Visual Representation

Narrow Screen (Mobile):

+---------------------------+

| Responsive UI | <- App Bar

+---------------------------+

| Responsive Header | <- Header

+---------------------------+

| [ Image 1 ] |

| Image 1 | <- Smaller image

| |

| [ Image 2 ] |

| Image 2 |
+---------------------------+

| [ Button 1 ]|

| [ Button 2 ]|

+---------------------------+

Wide Screen (Tablet/Desktop):


+---------------------------+
| Responsive UI | <- App Bar
+---------------------------+
| Responsive Header | <- Header
+---------------------------+
| [ Image 1 ] [ Image 3 ] |
| Image 1 Image 3 |
+---------------------------+
| [ Image 2 ] [ Image 4 ] |
| Image 2 Image 4 |
+---------------------------+
| [ Button 1 ]|
| [ Button 2 ]|
+---------------------------+

4.a) Set up navigation between different screens using Navigator.

import 'package:flutter/material.dart';

void main() {

runApp(MyApp());

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return MaterialApp(

title: 'Flutter Navigation Example',


theme: ThemeData(

primarySwatch: Colors.blue,

),

home: HomeScreen(),

);

// Home Screen

class HomeScreen extends StatelessWidget {

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(title: Text('Home Screen')),

body: Center(

child: ElevatedButton(

child: Text('Go to Second Screen'),

onPressed: () {

Navigator.push(

context,

MaterialPageRoute(builder: (context) => SecondScreen()),

);

},

),

),

);

}
}

// Second Screen

class SecondScreen extends StatelessWidget {

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(title: Text('Second Screen')),

body: Center(

child: Column(

mainAxisAlignment: MainAxisAlignment.center,

children: [

Text('This is the Second Screen!'),

SizedBox(height: 20),

ElevatedButton(

child: Text('Go to Third Screen'),

onPressed: () {

Navigator.push(

context,

MaterialPageRoute(builder: (context) => ThirdScreen()),

);

},

),

SizedBox(height: 20),

ElevatedButton(

child: Text('Go Back to Home Screen'),

onPressed: () {
Navigator.pop(context);

},

),

],

),

),

);

// Third Screen

class ThirdScreen extends StatelessWidget {

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(title: Text('Third Screen')),

body: Center(

child: Column(

mainAxisAlignment: MainAxisAlignment.center,

children: [

Text('This is the Third Screen!'),

SizedBox(height: 20),

ElevatedButton(

child: Text('Go Back to Second Screen'),

onPressed: () {

Navigator.pop(context);

},
),

SizedBox(height: 20),

ElevatedButton(

child: Text('Go Back to Home Screen'),

onPressed: () {

Navigator.popUntil(context, (route) => route.isFirst);

},

),

],

),

),

);

Output: Visual Representation

Home Screen:
+---------------------------+
| Home Screen | <- App Bar
+---------------------------+
| |
| [ Go to Second Screen ] | <- Center button
| |
+---------------------------+

Second Screen:

+---------------------------+
| Second Screen | <- App Bar
+---------------------------+
| |
| This is the Second Screen! |
| |
| [ Go to Third Screen ] | <- Button to Third Screen
| |
| [ Go Back to Home Screen ]| <- Button to Home Screen
| |
+---------------------------+

Third Screen:

+---------------------------+
| Third Screen | <- App Bar
+---------------------------+
| |
| This is the Third Screen! |
| |
| [ Go Back to Second Screen ]| <- Button to Second Screen
| |
| [ Go Back to Home Screen ]| <- Button to Home Screen
| |
+---------------------------+

4.b)Implement navigation with named routes.

import 'package:flutter/material.dart';
void main() {

runApp(MyApp());

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return MaterialApp(

title: 'Named Routes Example',

theme: ThemeData(

primarySwatch: Colors.blue,

),

initialRoute: '/',

routes: {

'/': (context) => HomeScreen(),

'/second': (context) => SecondScreen(),

'/third': (context) => ThirdScreen(),

},

);

// Home Screen

class HomeScreen extends StatelessWidget {

@override
Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(title: Text('Home Screen')),

body: Center(

child: ElevatedButton(

child: Text('Go to Second Screen'),

onPressed: () {

Navigator.pushNamed(context, '/second');

},

),

),

);

// Second Screen

class SecondScreen extends StatelessWidget {

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(title: Text('Second Screen')),

body: Center(

child: Column(

mainAxisAlignment: MainAxisAlignment.center,

children: [

Text('This is the Second Screen!'),

SizedBox(height: 20),
ElevatedButton(

child: Text('Go to Third Screen'),

onPressed: () {

Navigator.pushNamed(context, '/third');

},

),

SizedBox(height: 20),

ElevatedButton(

child: Text('Go Back to Home Screen'),

onPressed: () {

Navigator.pop(context);

},

),

],

),

),

);

// Third Screen

class ThirdScreen extends StatelessWidget {

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(title: Text('Third Screen')),

body: Center(
child: Column(

mainAxisAlignment: MainAxisAlignment.center,

children: [

Text('This is the Third Screen!'),

SizedBox(height: 20),

ElevatedButton(

child: Text('Go Back to Second Screen'),

onPressed: () {

Navigator.pop(context);

},

),

SizedBox(height: 20),

ElevatedButton(

child: Text('Go Back to Home Screen'),

onPressed: () {

Navigator.popUntil(context, (route) => route.isFirst);

},

),

],

),

),

);

Output: Visual Representation


Home Screen:
+---------------------------+
| Home Screen | <- App Bar
+---------------------------+
| |
| [ Go to Second Screen ] | <- Center button
| |
+---------------------------+
Second Screen:

+---------------------------+
| Second Screen | <- App Bar
+---------------------------+
| |
| This is the Second Screen! |
| |
| [ Go to Third Screen ] | <- Button to Third Screen
| |
| [ Go Back to Home Screen ]| <- Button to Home Screen
| |
+---------------------------+
Third Screen:

+---------------------------+
| Third Screen | <- App Bar
+---------------------------+
| |
| This is the Third Screen! |
| |
| [ Go Back to Second Screen ]| <- Button to Second Screen
| |
| [ Go Back to Home Screen ]| <- Button to Home Screen
| |
+---------------------------+

5.a) Learn about statefull and stateless widgets.


1.Stateful Widget Example:

import 'package:flutter/material.dart';
class MyStatefulWidget extends StatefulWidget {
@override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
int _counter = 0;

void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Stateful Widget Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('You have pushed the button this many times:'),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),

floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
Output for Stateful Widget:
+---------------------------+
| Stateful Widget Example | <- App Bar
+---------------------------+
| |
| You have pushed the button |
| this many times: |
| 0 | <- Counter
| |
+---------------------------+
| + | <- Floating Action Button
+---------------------------+

2.Stateful Widget Example:


import 'package:flutter/material.dart';
class MyStatelessWidget extends StatelessWidget {
final String title;
MyStatelessWidget({required this.title});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
child: Text('This is a Stateless Widget!'),
),
);
}
}
Output for Stateless Widget:
+---------------------------+
| My Stateless Widget | <- App Bar
+---------------------------+
| |
| This is a Stateless Widget! |
| |
+---------------------------+

5.b) Implement state management using set State and Provider.

1. State Management with SetState:

This method is suitable for small applications or simple use cases.

import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'SetState Example',
home: CounterScreen(),
);
}
}
class CounterScreen extends StatefulWidget {
@override
_CounterScreenState createState() => _CounterScreenState();
}

class _CounterScreenState extends State<CounterScreen> {


int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Counter using setState')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Counter Value: $_counter'),
SizedBox(height: 20),
ElevatedButton(
onPressed: _incrementCounter,
child: Text('Increment'),
),
],
),
),
);
}
}

Output:
After pressing the button once:
Counter Value: 1
After pressing it three times:
Counter Value: 3

2. State Management with Provider:


import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(
ChangeNotifierProvider(
create: (context) => Counter(),
child: MyApp(),
),
);
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Provider Example',
home: CounterScreen(),
);
}
}
class Counter with ChangeNotifier {
int _counter = 0;

int get counter => _counter;

void increment() {
_counter++;
notifyListeners(); // Notifies listeners to rebuild
}
}
class CounterScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Counter using Provider')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Counter Value: ${Provider.of<Counter>(context).counter}'),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {
Provider.of<Counter>(context, listen: false).increment();
},
child: Text('Increment'),
),
],
),
),
);
}
}

Output:
The Provider package is a powerful state management solution for larger applications.
First, you need to add the Provider package to your pubspec.yaml:
dependencies:
flutter:
sdk: flutter
provider: ^6.0.0 # Check for the latest version.

You might also like