0% found this document useful (0 votes)
40 views71 pages

UI Design Flutter R22 Lab Manual 1

The document outlines a course on UI Design using Flutter, detailing course objectives, outcomes, and a list of experiments for students to implement. It covers the fundamentals of Flutter, including installation, widget types, and UI design principles, as well as practical exercises for creating responsive applications. Additionally, it provides guidance on setting up the development environment in Visual Studio Code and utilizing debugging and hot reload features.

Uploaded by

navyasrivaagdevi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views71 pages

UI Design Flutter R22 Lab Manual 1

The document outlines a course on UI Design using Flutter, detailing course objectives, outcomes, and a list of experiments for students to implement. It covers the fundamentals of Flutter, including installation, widget types, and UI design principles, as well as practical exercises for creating responsive applications. Additionally, it provides guidance on setting up the development environment in Visual Studio Code and utilizing debugging and hot reload features.

Uploaded by

navyasrivaagdevi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

U I DESIGN-FLUTTER

BTech. III Year I Sem. L T P C


0021
Course Objectives:
• Learns to Implement Flutter Widgets and Layout
• Understands Responsive UI Design and with Navigation in Flutter
• Knowledge on Widges and customize widgets for specific UI elements,
Themes
• Understand to include animation apart from fetching data Course Outcomes:
➢ Implements Flutter Widgets and Layouts
➢ Responsive UI Design and with Navigation in Flutter
➢ Create custom widgets for specific UI elements and also Apply styling using
themes and custom styles.
➢ Design a f orm with various input fields, along with validation and
error handling
➢ Fetches data and write code for unit Test for UI components and also
animation

List of Experiments: Students need to implement the following experiments

1. a) Introduction to FLUTTER.
b) Installation of Flutter for Windows.
2. a) Installation and setup in VS Code.
b) Explore various Flutter Text Widget.
3. a) Explore various Flutter widgets (Image, Container, etc.).
b) Implement different layout structures using Row, Column Widget.
4. a) Implement different layout structures using Stack Widget.
b) Set up navigation between different screens using Navigator.
5. a) Implement navigation with named routes.
b)Learn about stateful and stateless widgets.
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) Implement Animate properties of a Container Widget.
b) Use Flutter’s debugging tools to identify and fix issues.
10. a) Fetch data from a REST API
b) Display the fetched data in a meaningful way in the UI.
TEXT BOOK:
1. Marco L. Napoli, Beginning Flutter: A Hands-on Guide to App Development.

Downloaded by mote Vinay ([email protected])


3
Week-1

1a)Introductionto FLUTTER.
Flutter is an open-source framework developed by Google for building natively compiled
applications for mobile, web, and desktop from a single codebase. It aims to simplify and
acceleratethedevelopmentprocesswhileofferingarichsetoffeaturestoensurehighperformance
andagreatuserexperience.Flutterisanopen-sourceprojecthostedonGitHubwithcontributions from
Google and the community. Flutter uses Dart, a modern object-oriented language that compiles
to native ARM code and production ready JavaScript code.

KeyFeaturesofFlutter
1. Single Codebase for Multiple Platforms: With Flutter, you can write your application
once and deploy it on multiple platforms, including iOS, Android, web browsers,
Windows, macOS, and Linux. This reduces the need for platform-specific code and
accelerates development.
2. Dart Programming Language: Flutter uses Dart, a language also developed byGoogle.
Dart is designed to be easy to learn and use, with features that facilitate both high
performance and a smooth development experience. It supports both just-in-time (JIT)
compilationduringdevelopmentforquickiterationandahead-of-time(AOT)compilation for
optimized production builds.
3. RichSetofWidgets:Flutterprovidesacomprehensivecollectionofwidgetsthathelpyou build
complex UIs quickly. These widgets are designed to be customizable and can be
combinedtocreatehighlyinteractiveandvisuallyappealinginterfaces.Thewidgetsfollow the
Material Design guidelines for Android and the Cupertino design guidelines for iOS.
4. Fast Development with Hot Reload: One of Flutter’s standout features is Hot Reload,
which allows developers to see the results of changes almost instantly without restarting
the application. This significantly speeds up the development process and makes
experimenting with the UI easier.
5. High Performance: Flutter’s engine, written in C++, provides high performance by
renderingdirectlytotheplatform’sGPU.ThiseliminatestheneedforaJavaScript bridge,
asseeninsomeothercross-platformframeworks,ensuringthattheapprunssmoothlyand
efficiently.
6. Customizable and Extensible: Flutter's architecture allows for extensive customization
and the creation of complex UIs. Developers can build their own custom widgets and
extend existing ones to fit their needs. Additionally, the framework supports integration
withvariouspluginsandpackagestoaddfunctionalitysuchasaccessingdevicehardware,
networking, and more.
7. Strong Community and Ecosystem: Since its introduction, Flutter has gained a strong
community of developers and contributors. This has led to a growing ecosystem of
packagesandpluginsthatextendtheframework’scapabilities,makingiteasiertointegrate with
third-party services and tools.
8. Beautiful UIs: Flutter is known for its ability to create beautiful and smooth UIs. The
frameworkprovidesarangeofanimationsandvisualeffects,anditsdesignsystemallows for the
creation of highly responsive and adaptive interfaces.
HowFlutterWorks
● Rendering Engine: Flutter usesSkia, a 2D graphics library, as itsrendering engine. This
engine draws the application’s UI components directlyontothe screen, providing smooth
and high-performance rendering across different platforms.
● Widgets: Everything in Flutter is a widget, fromthe structuralelements like buttons and
menustothestylisticaspectslike fontsandcolors.WidgetsarecomposedtobuildtheUI, and
Flutter’s declarative approach makes it easy to manage state and build complex layouts.
● Platform Channels: To interact with native code or access platform-specific features,
Flutter uses platformchannels. These channels enable communicationbetweenDart code
and native code (Java/Kotlin for Android, Objective-C/Swift for iOS).
Widgets
InFlutter,awidgetisafundamentalbuildingblockusedtoconstructuserinterfaces. Widgetsare the
primary way developers define and compose the layout and behavior of their applications. Here’s
a comprehensive look at what widgets are and how they function within the Flutter framework:
Definition andPurpose
● Definition: Awidget inFlutter isa descriptionofpartofa user interface. It canrepresent
anything visible on the screen, from a simple button to a complex layout.
● Purpose: Widgetsareusedto constructtheUIofaFlutter applicationbydescribingwhat their
view should look like given their current configuration and state. They encapsulate both
the visual layout (how things look) and the behavior (how things work) of a component.
CharacteristicsofWidgets
● Immutable:WidgetsinFlutterareimmutable,meaningoncetheyarecreated,theycannot
bechanged.Ifawidgetneedstochangeitsappearanceorbehavior,anewwidgetinstance is
created with the updated configuration.
● Composable: Widgetscanbecombinedtogetherto buildcomplexUIs.Flutterprovidesa rich
set of pre-built widgets (like text, buttons, images, etc.) that can be nested and composed
to create custom widgets or entire screens.
Typesof Widgets
Fluttercategorizeswidgetsintotwomaintypesbased onhowtheymanagestate:
1. StatelessWidgets:
o Definition: Statelesswidgetsare widgetsthat do not have mutable state.Theyare
immutable and their appearance is solely a function of the configuration
information in their constructor.
o Characteristics:Statelesswidgetsaresimpleand lightweight becausetheydo not
need to manage state changes. Examples include Text, Icon, Image, etc.
ThefollowingsamplecodeshowsaStatelessWidgetbasestructure

classJournalListextendsStatelessWidget{ @override
Widgetbuild(BuildContextcontext){ return
Container();
}
}
2. StatefulWidgets:
o Definition: Stateful widgets are widgets that maintain state that might change
during the lifetime ofthe widget.Theyare responsible formanaging and updating
their own state.
o Characteristics:Statefulwidgetsaremorecomplexcomparedtostatelesswidgets
because they have mutable state. Examples include TextField, Checkbox, Slider,
etc.
ThefollowingexampleshowsaStatefulWidget basestructure

classJournalEditextendsStatefulWidget{ @override
_JournalEditStatecreateState()=>_ JournalEditState();
}
class_JournalEditStateextendsState<JournalEdit>{ @override
Widgetbuild(BuildContextcontext){ return
Container();
}
}
WidgetLifecycle
Widgets inFluttergo throughalifecyclefromcreationtodestruction:
● Creation:Widgetsareinstantiatedusingtheirconstructor,whichdefinestheir configuration.
● Build: The build() method is called to obtain the widget's UI representation based on its
current configuration.
● Update:Widgetscanberebuilt(i.e.,thebuild()methodiscalledagain)whentheir configuration
or the data they depend on changes.
● Destruction: Widgets maybe destroyed whentheyare no longer needed (e.g.,whenthey
are removed from the widget tree).

ExampleofaSimpleWidget

Here'sanexampleofastatelesswidget(Textwidget)inFlutter:
import'package:flutter/material.dart';

classMyAppextendsStatelessWidget{

@override

Widgetbuild(BuildContextcontext){

return MaterialApp(

home: Scaffold(

appBar: AppBar(title:

Text('My App'),

),

body: Center(

child: Text(

'Hello,Flutter!',

style:TextStyle(fontSize:24.0),

),

),

),

);

● In thisexample,theTextwidgetdisplaysthetext"Hello,Flutter!"in thecenter of the screen.


● TheTextwidgetisimmutableanditsappearanceisdeterminedsolelybyitsdataand
styleproperties.
● Whentheappruns,FlutterconstructsawidgettreestartingfromMyAppdowntoText,and
ultimately displays the UI on the device.
WidgetsarethefundamentalbuildingblocksofFlutterapplications,responsiblefordefiningboth the
visual layout and behavior ofthe user interface. Understanding how to create, compose, and
manage widgets effectively is crucial for developing robust and responsive Flutter applications.

1b)Installation of Flutter for Windows.

To install Flutter on Windows, follow these steps:

1. System Requirements

Ensure your system meets the minimum requirements for Flutter:

 Operating System: Windows 7 or later (64-bit)


 Disk Space: 1.64 GB (does not include IDE/tools)
 Tools: Git for Windows (for cloning and managing Flutter projects)

2. Download Flutter SDK

 Go to the Flutter installation page for Windows.


 Download the latest stable Flutter SDK ZIP from the "Windows" section.

3. Extract the ZIP File

 Extract the downloaded .zip file to an appropriate location on your file system (e.g.,
C:\src\flutter).
o Important: Do not install Flutter in a directory like C:\Program Files or any path with
spaces.

4. Update System Path

To run Flutter commands from any terminal window, you need to add Flutter to your system path.

 Steps to add Flutter to your system path:


1. Open File Explorer, right-click This PC, and select Properties.
2. Click Advanced system settings on the left.
3. Under System Properties, click the Environment Variables button.
4. Under System Variables, find and select the Path variable, then click Edit.
5. Click New, and add the full path to the flutter\bin directory. (e.g.,
C:\src\flutter\bin).
6. Click OK to save and exit the dialogs.

5. Run Flutter Doctor

 Open a new Command Prompt or PowerShell window (to apply the updated path).
 Run the following command:
bash
Copy code
flutter doctor

This will check your system for dependencies required by Flutter and show the status of your
installation. The command will also suggest any required steps, such as installing Android Studio or
Xcode for macOS, if they are missing.

6. Install Dependencies

 Git: If you don't have Git installed, Flutter requires Git for version control. You can install it from
Git for Windows.
 Android Studio: Flutter requires Android Studio for Android development. You can download it
from here.
o Flutter Plugin: Open Android Studio, go to Plugins in the settings, and install the Flutter
plugin (this also installs Dart).
o Android SDK: During the installation of Android Studio, ensure the Android SDK is also
installed. You may need to configure the SDK in Android Studio settings.

7. Set Up Android Device or Emulator

You will need either a physical device or an emulator to run and test your Flutter applications.

 For an Android Emulator:


1. Open Android Studio.
2. Go to Tools > AVD Manager to create and configure a new Android Virtual Device
(AVD).
3. Select the device type and system image, then click Finish.

8. Verify Installation

After running flutter doctor, make sure all required dependencies are installed. The output will
provide information on any missing components and how to install them.

 If everything is set up correctly, you should see:

scss
Copy code
[✓] Flutter (Channel stable, vX.X.X, on Microsoft Windows [Version
10.XX], locale en-US)
[✓] Android toolchain - develop for Android devices
[✓] Chrome - develop for the web
[✓] Visual Studio - develop for Windows
[✓] Connected device (2 available)

9. Create a New Flutter Project

 In your terminal, navigate to the directory where you want to create your project.
 Run the following command:

bash
Copy code
flutter create my_app
This creates a new Flutter project named my_app.

10. Run Your First Flutter App

 Navigate to the project directory:

bash
Copy code
cd my_app

 Connect your device or start the Android emulator.


 Run the app:

bash
Copy code
flutter run

Troubleshooting:

 If you encounter issues, flutter doctor will usually give helpful diagnostic information.
 Ensure your Android Studio, Xcode (for macOS), and any other dependencies are correctly
configured.
Week-2

2a) Installation and setup in VS

Code.Updating the extension

Updates to the extensions are shipped on a regular basis. By default, VS Code


automatically updates extensions when updates are available.

To install updates yourself:

1. Click Extensions in the Side Bar.


2. If the Flutter extension has an available update, click Update and then Reload.
3. Restart VS Code.

Creating projects
#
There are a couple ways to create a new project.

Creating a new project


#
To create a new Flutter project from the Flutter starter app template:

1. Go to View > Command Palette.…


2. You can also press Ctrl / Cmd + Shift + P.
3. Type flutter.
4. Select the Flutter: New Project.
5. Press Enter.
6. Select Application.
7. Press Enter.
8. Select a Project location.
9. Enter your desired Project name.

Opening a project from existing source code

To open an existing Flutter project:

1. Go to File > Open.


2. You can also press Ctrl / Cmd + O
3. Browse to the directory holding your existing Flutter source code files.
4. Click Open

Editing code and viewing issues

The Flutter extension performs code analysis. The code analysis can:

 Highlight language syntax


 Complete code based on rich type analysis
 Navigate to type declarations
 Go to Go > Go to Definition.
 You can also press F12.
 Find type usages.
 Press Shift + F12.
 View all current source code problems.

o Go to View > Problems.


o You can also press Ctrl / Cmd + Shift + M.
o The Problems pane displays any analysis issues:

Running and debugging

Start debugging by clicking Run > Start Debugging from the main IDE window, or
press F5.

 Selecting a target device

When a Flutter project is open in VS Code, you should see a set of Flutter specific
entries in the status bar, including a Flutter SDK version and a device name (or the
message No Devices):

How to perform a hot reload

To hot reload a Flutter app:

1. Run the app from a supported Flutter editor or a terminal window. Either a physical
or virtual device can be the target. Only Flutter apps in debug mode can be hot
reloaded or hot restarted.

2. Modify one of the Dart files in your project. Most types of code changes can be hot
reloaded; for a list of changes that require a hot restart, see Special cases.

3. If you're working in an IDE/editor that supports Flutter's IDE tools, select Save
All (cmd-s/ctrl-s), or click the hot reload button on the toolbar.
4. If you're running the app at the command line using flutter run, enter r in the
terminal window.

2b)Explore various Flutter Text Widget.

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

// function to trigger build process


void main() => runApp(const GeeksforGeeks());

class GeeksforGeeks extends StatelessWidget { const


GeeksforGeeks({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Colors.lightGreen,
appBar: AppBar(
backgroundColor: Colors.green, title:
const Text("welcome Screen"),
), // AppBar body:
Container(
child: const Center(
child: Text("Hello world!!"),
), // Center
), // Container
), // Scaffold
); // MaterialApp
}
}

Output:
Week-3

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


Image Widget:

import 'package:flutter/material.dart';

// function to start app building


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

class MyApp extends StatelessWidget {


const MyApp({Key? key}) : super(key: key);

// This widget is the root


// of your application

@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text(
'Insert Image Demo',
),
),
body: Center(
child: Column(
children: <Widget>[
Image.asset('assets/images/output.gif',
height: 200,
scale: 2.5
// color: Color.fromARGB(255, 15, 147, 59),
opacity:
const
AlwaysStoppedAnimation<double>(0.5)), //Image.asset
Image.asset(
'assets/images/geeksforgeeks.jpg',
height: 400,
width: 400,
), // Image.asset
], //<Widget>[]
), //Column
), //Center
),
);
}
}

Containter Widget:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {


const MyApp({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text("Container example"),
),
body: Container(
height: 200,
width: double.infinity,
//color: Colors.purple,
alignment: Alignment.center,
margin: const EdgeInsets.all(20),
padding: const EdgeInsets.all(30),
decoration: BoxDecoration(
border: Border.all(color: Colors.black, width: 3),
),
child: const Text("Hello! i am inside a container!",
style: TextStyle(fontSize: 20)),
),
),
);
}
}

Output:

3b) Implement different layout structures using Row, Column Widget.

Row Widget

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:

Column Widget:

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:
Week-4

4a)Implement different layout structures using Stack Widget.

Stack Widget:
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('GeeksforGeeks'),
backgroundColor: Colors.greenAccent[400],
), //AppBar
body: Center(
child: SizedBox(
width: 300,
height: 300,
child: Center(
child: Stack(
children: <Widget>[
Container(
width: 300,
height: 300,
color: Colors.red,
), //Container
Container(
width: 250,
height: 250,
color: Colors.black,
), //Container
Container(
height: 200,
width: 200,
color: Colors.purple,
), //Container
], //<Widget>[]
), //Stack
), //Center
), //SizedBox
) //Center
) //Scaffold
) //MaterialApp
);
}
Output:

4b)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 Demo',
theme: ThemeData(primarySwatch: Colors.blue),
home: HomeScreen(),
);
}
}
class HomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Home Screen')),
body: Center(
child: ElevatedButton(
child: const Text(
'Navigate to a new screen >>',
style: TextStyle(fontSize: 24.0),
),
onPressed: () {
_navigateToNextScreen(context);
},
),
),
);
}

void _navigateToNextScreen(BuildContext context) {


Navigator.of(context).push(MaterialPageRoute(builder: (context) =>
NewScreen()));
}
}
class NewScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('New Screen')),
body: const Center(
child: Text(
'This is a new screen',
style: TextStyle(fontSize: 24.0),
),
),
);
}
}

Output:
Week-5

5a) 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 Navigation Example',
initialRoute: '/',
routes: {
'/': (context) => HomeScreen(),
'/about': (context) => AboutScreen(),
},
);
}
}
class HomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Home Screen'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Welcome to the Home Screen.',
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {
Navigator.pushNamed(context, '/about');
},
child: Text('Go to About'),
),
],
),
),
);
}
}
class AboutScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('About Screen'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'This is the About Screen.',
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {
Navigator.pop(context);
},
child: Text('Go back to Home'),
),
],
),
),
);
}
}

Output:
5b)Learn about stateful and stateless widgets.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Stateful and Stateless Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int counter = 0;
void incrementCounter() {
setState(() {
counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Stateful and Stateless Example'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CounterDisplay(counter),
SizedBox(height: 20),
CounterButton(incrementCounter),
],
),
);
}
}
class CounterDisplay extends StatelessWidget {
final int count;
CounterDisplay(this.count);
@override
Widget build(BuildContext context) {
return Text(
'Counter Value: $count',
style: TextStyle(fontSize: 20),
);
}
}
class CounterButton extends StatelessWidget {
final VoidCallback onPressed;
CounterButton(this.onPressed);
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: onPressed,
child: Text('Increment Counter'),
);
}
}

Output:
Week-6:

6a)Create custom widgets for specific UI elements.


import 'package:flutter/material.dart';

class CustomButton extends StatelessWidget {

final String label;

final VoidCallback onPressed;

final Color color;

CustomButton({

required this.label,

required this.onPressed,

this.color = Colors.blue,

});

@override

Widget build(BuildContext context) {

return ElevatedButton(

style: ElevatedButton.styleFrom(primary: color),

onPressed: onPressed,

child: Text(label),

);

}
Output:

6b) Apply styling using themes and custom styles.


import 'package:flutter/material.dart';

// Include the Google Fonts package to provide more text format options

// https://pub.dev/packages/google_fonts

import 'package:google_fonts/google_fonts.dart';

void main() {

runApp(const MyApp());

class MyApp extends StatelessWidget {

const MyApp({super.key});

@override

Widget build(BuildContext context) {

const appName = 'Custom Themes';

return MaterialApp(

title: appName,

theme: ThemeData(

useMaterial3: true,

// Define the default brightness and colors.

colorScheme: ColorScheme.fromSeed(
seedColor: Colors.purple,

// TRY THIS: Change to "Brightness.light"

// and see that all colors change

// to better contrast a light background.

brightness: Brightness.dark,

),

// Define the default `TextTheme`. Use this to specify the default

// text styling for headlines, titles, bodies of text, and more.

textTheme: TextTheme(

displayLarge: const TextStyle(

fontSize: 72,

fontWeight: FontWeight.bold,

),

// TRY THIS: Change one of the GoogleFonts

// to "lato", "poppins", or "lora".

// The title uses "titleLarge"

// and the middle text uses "bodyMedium".

titleLarge: GoogleFonts.oswald(

fontSize: 30,

fontStyle: FontStyle.italic,

),

bodyMedium: GoogleFonts.merriweather(),

displaySmall: GoogleFonts.pacifico(),

),

),

home: const MyHomePage(

title: appName,

),

);
}

class MyHomePage extends StatelessWidget {

final String title;

const MyHomePage({super.key, required this.title});

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(

title: Text(title,

style: Theme.of(context).textTheme.titleLarge!.copyWith(

color: Theme.of(context).colorScheme.onSecondary,

)),

backgroundColor: Theme.of(context).colorScheme.secondary,

),

body: Center(

child: Container(

padding: const EdgeInsets.symmetric(

horizontal: 12,

vertical: 12,

),

color: Theme.of(context).colorScheme.primary,

child: Text(

'Text with a background color',

// TRY THIS: Change the Text value

// or change the Theme.of(context).textTheme

// to "displayLarge" or "displaySmall".

style: Theme.of(context).textTheme.bodyMedium!.copyWith(

color: Theme.of(context).colorScheme.onPrimary,
),

),

),

),

floatingActionButton: Theme(

data: Theme.of(context).copyWith(

// TRY THIS: Change the seedColor to "Colors.red" or

// "Colors.blue".

colorScheme: ColorScheme.fromSeed(

seedColor: Colors.pink,

brightness: Brightness.dark,

),

),

child: FloatingActionButton(

onPressed: () {},

child: const Icon(Icons.add),

),

),

);

}
Output:
Week-7:

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


import 'package:flutter/material.dart';

void main() {

runApp(MyApp());

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return MaterialApp(

title: 'Flutter Form Example',

theme: ThemeData(primarySwatch: Colors.blue),

home: FormPage(),

);

class FormPage extends StatefulWidget {

@override

_FormPageState createState() => _FormPageState();

class _FormPageState extends State<FormPage> {

final _formKey = GlobalKey<FormState>();

final TextEditingController _nameController = TextEditingController();

final TextEditingController _emailController = TextEditingController();

String? _selectedGender;

bool _acceptTerms = false;

List<String> genders = ['Male', 'Female', 'Other'];

void _submitForm() {

if (_formKey.currentState!.validate()) {
// Perform submission logic

print('Name: ${_nameController.text}');

print('Email: ${_emailController.text}');

print('Gender: $_selectedGender');

print('Accepted Terms: $_acceptTerms');

ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Form submitted!')));

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(title: Text('Flutter Form Example')),

body: Padding(

padding: const EdgeInsets.all(16.0),

child: Form(

key: _formKey,

child: Column(

children: [

TextFormField(

controller: _nameController,

decoration: InputDecoration(labelText: 'Name'),

validator: (value) {

if (value == null || value.isEmpty) {

return 'Please enter your name';

return null;

},

),

SizedBox(height: 16),
TextFormField(

controller: _emailController,

decoration: InputDecoration(labelText: 'Email'),

validator: (value) {

if (value == null || value.isEmpty) {

return 'Please enter your email';

} else if (!RegExp(r'^[^@]+@[^@]+\.[^@]+').hasMatch(value)) {

return 'Please enter a valid email';

return null;

},

),

SizedBox(height: 16),

DropdownButtonFormField<String>(

decoration: InputDecoration(labelText: 'Gender'),

value: _selectedGender,

items: genders.map((String gender) {

return DropdownMenuItem<String>(

value: gender,

child: Text(gender),

);

}).toList(),

onChanged: (String? newValue) {

setState(() {

_selectedGender = newValue;

});

},

validator: (value) {

if (value == null) {
return 'Please select your gender';

return null;

},

),

SizedBox(height: 16),

Row(

children: [

Checkbox(

value: _acceptTerms,

onChanged: (bool? value) {

setState(() {

_acceptTerms = value ?? false;

});

},

),

Flexible(

child: Text('I accept the terms and conditions'),

),

],

),

SizedBox(height: 16),

ElevatedButton(

onPressed: _submitForm,

child: Text('Submit'),

),

],

),

),
),

);

Output:

7 b) Implement form validation and error handling.


import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {

const MyApp({super.key});

@override

Widget build(BuildContext context) {

const appTitle = 'Form Validation Demo';

return MaterialApp(

title: appTitle,

home: Scaffold(

appBar: AppBar(
title: const Text(appTitle),

),

body: const MyCustomForm(),

),

);

// Create a Form widget.

class MyCustomForm extends StatefulWidget {

const MyCustomForm({super.key});

@override

MyCustomFormState createState() {

return MyCustomFormState();

// Create a corresponding State class.

// This class holds data related to the form.

class MyCustomFormState extends State<MyCustomForm> {

// Create a global key that uniquely identifies the Form widget

// and allows validation of the form.

//

// Note: This is a GlobalKey<FormState>,

// not a GlobalKey<MyCustomFormState>.

final _formKey = GlobalKey<FormState>();

@override

Widget build(BuildContext context) {

// Build a Form widget using the _formKey created above.

return Form(

key: _formKey,
child: Column(

crossAxisAlignment: CrossAxisAlignment.start,

children: [

TextFormField(

// The validator receives the text that the user has entered.

validator: (value) {

if (value == null || value.isEmpty) {

return 'Please enter some text';

return null;

},

),

Padding(

padding: const EdgeInsets.symmetric(vertical: 16),

child: ElevatedButton(

onPressed: () {

// Validate returns true if the form is valid, or false otherwise.

if (_formKey.currentState!.validate()) {

// If the form is valid, display a snackbar. In the real world,

// you'd often call a server or save the information in a database.

ScaffoldMessenger.of(context).showSnackBar(

const SnackBar(content: Text('Processing Data')),

);

},

child: const Text('Submit'),

),

),

],
),

);

Output:
Week-8:

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

import 'package:flutter/material.dart';

void main() {

runApp(MyApp());

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return MaterialApp(

title: 'Flutter Animation Example',

theme: ThemeData(primarySwatch: Colors.blue),

home: AnimationPage(),

);

class AnimationPage extends StatefulWidget {

@override

_AnimationPageState createState() => _AnimationPageState();

class _AnimationPageState extends State<AnimationPage>

with SingleTickerProviderStateMixin {

late AnimationController _controller;

late Animation<double> _fadeAnimation;

@override

void initState() {

super.initState();

_controller = AnimationController(

duration: const Duration(seconds: 2),


vsync: this,

);

_fadeAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(

CurvedAnimation(

parent: _controller,

curve: Curves.easeIn,

),

);

_controller.forward(); // Start the animation

@override

void dispose() {

_controller.dispose();

super.dispose();

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(title: Text('Flutter Animation Example')),

body: Center(

child: FadeTransition(

opacity: _fadeAnimation,

child: Container(

width: 200,

height: 200,

decoration: BoxDecoration(

color: Colors.blue,

borderRadius: BorderRadius.circular(15),
),

child: Center(

child: Text(

'Fade In!',

style: TextStyle(color: Colors.white, fontSize: 24),

),

),

),

),

),

);

Output:
8b) Experiment with different types of animations (fade, slide, etc.)
import 'package:flutter/material.dart';

void main() {

runApp(MyApp());

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return MaterialApp(

title: 'Flutter Animation Example',

theme: ThemeData(

primarySwatch: Colors.blue,

),

home: AnimationDemo(),

);

class AnimationDemo extends StatefulWidget {

@override

_AnimationDemoState createState() => _AnimationDemoState();

class _AnimationDemoState extends State<AnimationDemo>

with SingleTickerProviderStateMixin {

late AnimationController _controller;

late Animation<double> _fadeAnimation;

late Animation<Offset> _slideAnimation;

bool _isVisible = false;

@override

void initState() {
super.initState();

_controller = AnimationController(

duration: const Duration(milliseconds: 500),

vsync: this,

);

_fadeAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(_controller);

_slideAnimation = Tween<Offset>(begin: Offset(0.0, 1.0), end: Offset(0.0,


0.0)).animate(CurvedAnimation(

parent: _controller,

curve: Curves.easeInOut,

));

void _toggleFade() {

setState(() {

_isVisible = !_isVisible;

if (_isVisible) {

_controller.forward();

} else {

_controller.reverse();

});

void _toggleSlide() {

setState(() {

_isVisible = !_isVisible;

if (_isVisible) {

_controller.forward();

} else {

_controller.reverse();
}

});

@override

void dispose() {

_controller.dispose();

super.dispose();

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(

title: Text('Flutter Animation Example'),

),

body: Center(

child: Column(

mainAxisAlignment: MainAxisAlignment.center,

children: [

ElevatedButton(

onPressed: _toggleFade,

child: Text('Toggle Fade Animation'),

),

SizedBox(height: 20),

ElevatedButton(

onPressed: _toggleSlide,

child: Text('Toggle Slide Animation'),

),

SizedBox(height: 50),

// Fade Animation
FadeTransition(

opacity: _fadeAnimation,

child: Container(

width: 200,

height: 100,

color: Colors.blue,

alignment: Alignment.center,

child: Text(

'Fade Animation',

style: TextStyle(color: Colors.white, fontSize: 20),

),

),

),

// Slide Animation

SlideTransition(

position: _slideAnimation,

child: Container(

width: 200,

height: 100,

color: Colors.green,

alignment: Alignment.center,

child: Text(

'Slide Animation',

style: TextStyle(color: Colors.white, fontSize: 20),

),

),

),

],

),
),

);

Output:
Week-9

9a):Implement Animate properties of a Container Widget.


import 'dart:math';

import 'package:flutter/material.dart';

void main() => runApp(const AnimatedContainerApp());

class AnimatedContainerApp extends StatefulWidget {

const AnimatedContainerApp({super.key});

@override

State<AnimatedContainerApp> createState() => _AnimatedContainerAppState();

class _AnimatedContainerAppState extends State<AnimatedContainerApp> {

// Define the various properties with default values. Update these properties

// when the user taps a FloatingActionButton.

double _width = 50;

double _height = 50;

Color _color = Colors.green;

BorderRadiusGeometry _borderRadius = BorderRadius.circular(8);

@override

Widget build(BuildContext context) {

return MaterialApp(

home: Scaffold(

appBar: AppBar(

title: const Text('AnimatedContainer Demo'),

),

body: Center(
child: AnimatedContainer(

// Use the properties stored in the State class.

width: _width,

height: _height,

decoration: BoxDecoration(

color: _color,

borderRadius: _borderRadius,

),

// Define how long the animation should take.

duration: const Duration(seconds: 1),

// Provide an optional curve to make the animation feel smoother.

curve: Curves.fastOutSlowIn,

),

),

floatingActionButton: FloatingActionButton(

// When the user taps the button

onPressed: () {

// Use setState to rebuild the widget with new values.

setState(() {

// Create a random number generator.

final random = Random();

// Generate a random width and height.

_width = random.nextInt(300).toDouble();

_height = random.nextInt(300).toDouble();
// Generate a random color.

_color = Color.fromRGBO(

random.nextInt(256),

random.nextInt(256),

random.nextInt(256),1,);

// Generate a random border radius.

_borderRadius =

BorderRadius.circular(random.nextInt(100).toDouble());

});

},

child: const Icon(Icons.play_arrow),

),

),

);

Output:
9b): Use Flutter's debugging tools to identify and fix issues.
Ans) Flutter provides a set of debugging tools that can help you identify and fix issues in your
app. Here's a step-by-step guide on how to use these tools:

1. Flutter DevTools:

Run your app with the flutter run command.


Open DevTools by running the following command in your terminal:

bash

flutter pub global activate devtools


flutter pub global run devtools

Open your app in a Chrome browser and connect it to DevTools by clicking on the
"Open DevTools" button in the terminal or by navigating to http://127.0.0.1:9100/.
DevTools provides tabs like Inspector, Timeline, Memory, and more.

2. Flutter Inspector:

Use the Flutter Inspector in your integrated development environment (IDE) like
Android Studio or Visual Studio Code.

Toggle the Inspector in Android Studio with the shortcut Alt + Shift + D
(Windows/Linux) or Option + Shift + D (Mac).

Inspect the widget tree, modify widget properties, and observe widget relationships.

3. Hot Reload:

Leverage Hot Reload to see the immediate effect of code changes without restarting the entire
app.

Press R in the terminal or use the "Hot Reload" button in your IDE.

4. Debugging with Breakpoints:

Set breakpoints in your code to pause execution and inspect variables.

Use the debugger in your IDE to step through code and identify issues.

5. Logging:
Utilize the print function to log messages to the console.

print('Debugging message');

View logs in the terminal or the "Logs" tab in DevTools.

6. Debug Paint:

Enable debug paint to visualize the layout and rendering of widgets.

Use the debugPaintSizeEnabled and debugPaintBaselinesEnabled flags.

void main() {
debugPaintSizeEnabled = true; // Shows bounding boxes of widgets
runApp(MyApp());
}

7. Memory Profiling:

Use the "Memory" tab in DevTools to analyze memory usage and identify potential memory
leaks. Monitor object allocations and deallocations.

8. Performance Profiling (Timeline):

Analyze app performance using the "Timeline" tab in DevTools.


Identify UI jank, slow frames, and performance bottlenecks.

9. Flutter Driver Tests:

Write automated UI tests using Flutter Driver.


Simulate user interactions and validate the correctness of your UI.
Week-10 :

10a) Fetch data from a REST API

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

import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:cached_network_image/cached_network_image.dart';
class Product {
final int id;
final String title;
final double price;
final String description;
final String category;
final String image;
final double rating;
Product({
required this.id,
required this.title,
required this.price,
required this.description,
required this.category,
required this.image,
required this.rating,
});
factory Product.fromJson(Map<String, dynamic> json) {
return Product(
id: json['id'],
title: json['title'],
price: json['price'].toDouble(),
description: json['description'],
category: json['category'],
image: json['image'],
rating: json['rating']['rate'].toDouble(),
);
}
}
class ProductCard extends StatelessWidget {
final Product product;

const ProductCard({super.key,required this.product});


@override
Widget build(BuildContext context) {
return Card(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column( // this is the column
children: [
AspectRatio(
aspectRatio: 1, // this is the ratio
child: CachedNetworkImage( // this is to fetch the image
imageUrl: product.image,
fit: BoxFit.cover,
),
),

ListTile(
title: Text(product.title),
subtitle: Text('${product.price} \$'),// this is fetch the price from
the api
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.star, color: Colors.orange),// this will give
the rating
Text('${product.rating}'),
],
),
),
],
),
),
);
}
}

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


class MyApp extends StatelessWidget {
const MyApp({super.key});

// This widget is the root of your application.


@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// TRY THIS: Try running your application with "flutter run".
You'll see
// the application has a blue toolbar. Then, without quitting the app,
// try changing the seedColor in the colorScheme below to
Colors.green
// and then invoke "hot reload" (save your changes or press the "hot
// reload" button in a Flutter-supported IDE, or press "r" if you used
// the command line to start the app).
//
// Notice that the counter didn't reset back to zero; the application
// state is not lost during the reload. To reset the state, use hot
// restart instead.
//
// This works for code too, not just values: Most code changes can
be
// tested with just a hot reload.
colorScheme: ColorScheme.fromSeed(seedColor:
Colors.deepPurple),
useMaterial3: true,
),
//home: ProductsScreen(),
home: const ProductListScreen(),
);
}
}

class ProductListScreen extends StatefulWidget {


const ProductListScreen({super.key});

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

class ProductListScreenState extends State<ProductListScreen> {


List<Product> products = [];
@override
void initState() {
super.initState();
fetchProducts();
}

Future<void> fetchProducts() async {


final response = await
http.get(Uri.parse('https://fakestoreapi.com/products'));
if (response.statusCode == 200) {
List<dynamic> jsonData = json.decode(response.body);
setState(() {
products = jsonData.map((data) => Product.fromJson(data)).toList();
});
} else {
// Handle error if needed
print('Failed to load products');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Product List'),
),
body: ListView.builder(
// this give th length of item
itemCount: products.length,
itemBuilder: (context, index) {
// here we card the card widget
// which is in utils folder
return ProductCard(product: products[index]);
},
),
);
}
}
Run this command:
With Flutter Terminal:

$ flutter pub add cached_network_image

This will add a line like this to your package's pubspec.yaml (and run an
implicit flutter pub get):
In pubspec.yml file add
dependencies:
Line No 37: cupertino_icons: ^1.0.6
Line No 38: http: ^1.2.1
Line No 39: c ached_network_image: ^3.4.1

Output:

You might also like