UI Design Flutter R22 Lab Manual 1
UI Design Flutter R22 Lab Manual 1
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.
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),
),
),
),
);
1. System Requirements
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.
To run Flutter commands from any terminal window, you need to add Flutter to your system path.
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.
You will need either a physical device or an emulator to run and test your Flutter applications.
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.
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)
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.
bash
Copy code
cd my_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
Creating projects
#
There are a couple ways to create a new project.
The Flutter extension performs code analysis. The code analysis can:
Start debugging by clicking Run > Start Debugging from the main IDE window, or
press F5.
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):
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.
Text Widget:
import 'package:flutter/material.dart';
@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
import 'package:flutter/material.dart';
@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';
@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:
Row Widget
import 'package:flutter/material.dart';
@override
return MaterialApp(
home: MyHomePage()
);
@override
_MyHomePageState createState() => _MyHomePageState();
}
@override
return Scaffold(
appBar: AppBar(
),
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';
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:
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);
},
),
),
);
}
Output:
Week-5
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:
CustomButton({
required this.label,
required this.onPressed,
this.color = Colors.blue,
});
@override
return ElevatedButton(
onPressed: onPressed,
child: Text(label),
);
}
Output:
// 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());
const MyApp({super.key});
@override
return MaterialApp(
title: appName,
theme: ThemeData(
useMaterial3: true,
colorScheme: ColorScheme.fromSeed(
seedColor: Colors.purple,
brightness: Brightness.dark,
),
textTheme: TextTheme(
fontSize: 72,
fontWeight: FontWeight.bold,
),
titleLarge: GoogleFonts.oswald(
fontSize: 30,
fontStyle: FontStyle.italic,
),
bodyMedium: GoogleFonts.merriweather(),
displaySmall: GoogleFonts.pacifico(),
),
),
title: appName,
),
);
}
@override
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(
horizontal: 12,
vertical: 12,
),
color: Theme.of(context).colorScheme.primary,
child: Text(
// to "displayLarge" or "displaySmall".
style: Theme.of(context).textTheme.bodyMedium!.copyWith(
color: Theme.of(context).colorScheme.onPrimary,
),
),
),
),
floatingActionButton: Theme(
data: Theme.of(context).copyWith(
// "Colors.blue".
colorScheme: ColorScheme.fromSeed(
seedColor: Colors.pink,
brightness: Brightness.dark,
),
),
child: FloatingActionButton(
onPressed: () {},
),
),
);
}
Output:
Week-7:
void main() {
runApp(MyApp());
@override
return MaterialApp(
home: FormPage(),
);
@override
String? _selectedGender;
void _submitForm() {
if (_formKey.currentState!.validate()) {
// Perform submission logic
print('Name: ${_nameController.text}');
print('Email: ${_emailController.text}');
print('Gender: $_selectedGender');
@override
return Scaffold(
body: Padding(
child: Form(
key: _formKey,
child: Column(
children: [
TextFormField(
controller: _nameController,
validator: (value) {
return null;
},
),
SizedBox(height: 16),
TextFormField(
controller: _emailController,
validator: (value) {
} else if (!RegExp(r'^[^@]+@[^@]+\.[^@]+').hasMatch(value)) {
return null;
},
),
SizedBox(height: 16),
DropdownButtonFormField<String>(
value: _selectedGender,
return DropdownMenuItem<String>(
value: gender,
child: Text(gender),
);
}).toList(),
setState(() {
_selectedGender = newValue;
});
},
validator: (value) {
if (value == null) {
return 'Please select your gender';
return null;
},
),
SizedBox(height: 16),
Row(
children: [
Checkbox(
value: _acceptTerms,
setState(() {
});
},
),
Flexible(
),
],
),
SizedBox(height: 16),
ElevatedButton(
onPressed: _submitForm,
child: Text('Submit'),
),
],
),
),
),
);
Output:
const MyApp({super.key});
@override
return MaterialApp(
title: appTitle,
home: Scaffold(
appBar: AppBar(
title: const Text(appTitle),
),
),
);
const MyCustomForm({super.key});
@override
MyCustomFormState createState() {
return MyCustomFormState();
//
// not a GlobalKey<MyCustomFormState>.
@override
return Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextFormField(
// The validator receives the text that the user has entered.
validator: (value) {
return null;
},
),
Padding(
child: ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
ScaffoldMessenger.of(context).showSnackBar(
);
},
),
),
],
),
);
Output:
Week-8:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
@override
return MaterialApp(
home: AnimationPage(),
);
@override
with SingleTickerProviderStateMixin {
@override
void initState() {
super.initState();
_controller = AnimationController(
);
CurvedAnimation(
parent: _controller,
curve: Curves.easeIn,
),
);
@override
void dispose() {
_controller.dispose();
super.dispose();
@override
return Scaffold(
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!',
),
),
),
),
),
);
Output:
8b) Experiment with different types of animations (fade, slide, etc.)
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
@override
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: AnimationDemo(),
);
@override
with SingleTickerProviderStateMixin {
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
);
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
return Scaffold(
appBar: AppBar(
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: _toggleFade,
),
SizedBox(height: 20),
ElevatedButton(
onPressed: _toggleSlide,
),
SizedBox(height: 50),
// Fade Animation
FadeTransition(
opacity: _fadeAnimation,
child: Container(
width: 200,
height: 100,
color: Colors.blue,
alignment: Alignment.center,
child: Text(
'Fade Animation',
),
),
),
// Slide Animation
SlideTransition(
position: _slideAnimation,
child: Container(
width: 200,
height: 100,
color: Colors.green,
alignment: Alignment.center,
child: Text(
'Slide Animation',
),
),
),
],
),
),
);
Output:
Week-9
import 'package:flutter/material.dart';
const AnimatedContainerApp({super.key});
@override
// Define the various properties with default values. Update these properties
@override
return MaterialApp(
home: Scaffold(
appBar: AppBar(
),
body: Center(
child: AnimatedContainer(
width: _width,
height: _height,
decoration: BoxDecoration(
color: _color,
borderRadius: _borderRadius,
),
curve: Curves.fastOutSlowIn,
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
_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,);
_borderRadius =
BorderRadius.circular(random.nextInt(100).toDouble());
});
},
),
),
);
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:
bash
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.
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');
6. Debug Paint:
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.
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;
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}'),
],
),
),
],
),
),
);
}
}
@override
ProductListScreenState createState() => ProductListScreenState();
}
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: