EXERCISE NO: 1
Study and installation of Flutter/Kotlin multi-platform environment
AIM:
To Study and install Flutter/Kotlin multi-platform environment.
PROCEDURE:
1. Install Flutter from the link given below
https://docs.flutter.dev/get-started/install/windows/desktop
2. A zip file will be downloaded, now extract the files inside a folder named Flutter in C
drive.
3. To verify the proper installation of flutter, open the Command prompt and type the
following command.
>flutter doctor
4. You can also verify the installation by checking for the version of flutter using the
following command.
>flutter - -version
5. Now install Android studio from the link given below
https://developer.android.com/studio/?
gclid=CjwKCAiA27LvBRB0EiwAPc8XWRrnHP-
icvYCacEfP6rZLPYYovGo0v36tEgJHv0-1hqj25XllweRPhoC2VEQAvD_BwE
6. After installing both Flutter and Android Studio we have to install the Flutter Plugin in
Android Studio.
7. For installing flutter plugin go to Settings -> Plugins -> Search Flutter and install the
plugin and restart Android Studio
8. Create a new Flutter project in Android Studio by Clicking on File -> New Flutter
Project.
9. Now specify the name of the project all in lowercase separated by hyphens “-” and select
the languages to be Objective C and Java.
10. Now a new Flutter project would be created and the main.dart file will be present in the
lib folder.
11. Run the main.dart file by connecting it to a virtual emulator.
RESULT:
Thus Flutter/Kotlin multi-platform environment was studied and installed successfully.
EXERCISE NO: 2
Develop an application that uses Widgets, GUI components, Fonts, and Colors
AIM:
To develop an application that uses Widgets, GUI components, Fonts, and Colors.
PROCEDURE:
STEP 1: Create a new Flutter project in Android Studio by Clicking on File -> New Flutter
Project.
STEP 2: Now specify the name of the project all in lowercase separated by hyphens “-” and
select the languages to be Objective C and Java.
STEP 3: Now a new Flutter project will be created and the main.dart file will be present in the
lib folder.
STEP 4: Explore all the types of widgets, GUI components and options for font and color of
text.
STEP 5: Change the main.dart file by adding Widgets and GUI components.
STEP 6: Run the main.dart file by connecting it to a virtual emulator.
PROGRAM:
import "package:flutter/material.dart";
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 const MaterialApp(
home: MyHomePage()
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
padding: EdgeInsets.symmetric(vertical: 50),
child: Column(children: [
Text("Normal Text Widget", style: TextStyle(fontSize: 60, color: Colors.blue)),
Container(
padding: EdgeInsets.all(20),
child: Text("Text widget inside a container widget with padding")
),
SizedBox(height: 50,),
Row(children: [
Text("Text1"),
Text("Text2"),
Text("Text3"),
Text("Text4"),
Text("Text5"),
],),
SizedBox(height: 50,),
Stack(
children: [
Container(
color: Colors.yellow,
width: 400,
height: 400,
child: Text("bottom stack"),
),
Container(
color: Colors.red,
width: 200,
height: 200,
child: Text("middle stack"),
),
Container(
color: Colors.blue,
width: 100,
height: 100,
child: Text("first stack"), ),
],
)
],),
)
);
}
}
OUTPUT:
PROGRAM:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Change Text on Button Click',
home: ChangeTextScreen(),);
}
}
class ChangeTextScreen extends StatefulWidget {
@override
_ChangeTextScreen createState() => _ChangeTextScreen();
}
class _ChangeTextScreen extends State<ChangeTextScreen>{
String alarmText = "Alarm Off";
int count = 0;
void changeText(){
setState(() {
if(count % 2 ==0){
alarmText = "Alarm Off";
}
else{
alarmText = "Alarm On";
}
count++;
});
}
@override
Widget build(BuildContext context){
return Scaffold(
body: Container(
padding: EdgeInsets.symmetric( vertical: 250),
child: Center(
child: Column(
children: [
Text(alarmText),
SizedBox(height: 20,),
ElevatedButton(child: Text("Alarm Switch"), onPressed: changeText)
],),),));}}
OUTPUT:
RESULT:
Thus the development of an application that uses Widgets, GUI components, Fonts, and
Colors was done successfully.
EXERCISE NO: 3
Develop a native calculator application.
AIM:
To develop a native calculator application.
PROCEDURE:
STEP 1: Create a new Flutter project in Android Studio by Clicking on File -> New Flutter
Project.
STEP 2: Now specify the name of the project all in lowercase separated by hyphens “-” and
select the languages to be Objective C and Java.
STEP 3: Now a new Flutter project will be created and the main.dart file will be present in the
lib folder.
STEP 4: Change the main.dart file by adding Widgets and GUI components required to create a
calculator.
STEP 5: Add the functionality of the calculator.
STEP 6: Run the main.dart file by connecting it to a virtual emulator.
STEP 7: Check the working of the calculator.
PROGRAM:
import 'package:flutter/material.dart';
void main() {
runApp(CalculatorApp());
}
class CalculatorApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Native Calculator',
home: CalculatorScreen(),
);
}
}
class CalculatorScreen extends StatefulWidget {
@override
_CalculatorScreenState createState() => _CalculatorScreenState();
}
class _CalculatorScreenState extends State<CalculatorScreen> {
String _output = '';
double _num1 = 0;
double _num2 = 0;
String _operand = '';
void _buttonPressed(String buttonText) {
setState(() {
if (buttonText == 'C') {
_output = '';
_num1 = 0;
_num2 = 0;
_operand = '';
} else if (buttonText == '+' ||
buttonText == '-' ||
buttonText == '*' ||
buttonText == '/') {
_num1 = double.parse(_output);
_operand = buttonText;
_output = '';
} else if (buttonText == '=') {
_num2 = double.parse(_output);
if (_operand == '+') {
_output = (_num1 + _num2).toString();
}
if (_operand == '-') {
_output = (_num1 - _num2).toString();
}
if (_operand == '*') {
_output = (_num1 * _num2).toString();
}
if (_operand == '/') {
_output = (_num1 / _num2).toString();
}
_num1 = 0;
_num2 = 0;
_operand = '';
} else {
_output += buttonText;
}
});
}
Widget _buildButton(
String buttonText,
){
return Expanded(
child: Container(
margin: EdgeInsets.all(8.0),
child: ElevatedButton(
onPressed: () {
_buttonPressed(buttonText);
},
child: Text(
buttonText,
style: TextStyle(fontSize: 24.0),
),
),
),
);
}
Widget _buildButtonRow(List<String> buttons) {
return Row(
children: buttons
.map((button) => _buildButton(
button,
))
.toList(),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Native Calculator'),
),
body: Column(
children: [
Expanded(
child: Container(
alignment: Alignment.bottomRight,
padding: EdgeInsets.all(24.0),
child: Text(
_output,
style: TextStyle(fontSize: 48.0, fontWeight: FontWeight.bold),
),
),
),
Divider(height: 0.0),
Column(
children: [
_buildButtonRow(['1', '2', '3', '4']),
_buildButtonRow(['5', '6', '7', '8']),
_buildButtonRow(['9', '0', 'C', '=']),
_buildButtonRow(['+', '-', '*', '/']),
],
),
],
),
);
}
}
OUTPUT:
RESULT:
Thus developing a native calculator application was done successfully.
EXERCISE NO: 4
Develop a gaming application that uses 2-D animations and gestures.
AIM:
To develop a gaming application that uses 2-D animations and gestures.
PROCEDURE:
STEP 1: Create a new Flutter project in Android Studio by Clicking on File -> New Flutter
Project.
STEP 2: Now specify the name of the project all in lowercase separated by hyphens “-” and
select the languages to be Objective C and Java.
STEP 3: Now a new Flutter project will be created and the main.dart file will be present in the
lib folder.
STEP 4: Change the main.dart file by adding Widgets and GUI components required to create a
calculator.
STEP 5: Add the functionality of the game in a new page and name it game_page.dart
STEP 6: Run the main.dart file by connecting it to a virtual emulator.
STEP 7: Check the working of the game.
PROGRAM:
//main.dart
import 'package:flutter/material.dart';
import 'game_page.dart';
void main() {
runApp(const MainApp());
}
class MainApp extends StatelessWidget {
const MainApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData.dark(),
home: SnakeGamePage(),
);
}
}
//game_page.dart
import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
class SnakeGamePage extends StatefulWidget {
const SnakeGamePage({super.key});
@override
State<SnakeGamePage> createState() => _SnakeGamePageState(); }
enum Direction { up, down, left, right }
class _SnakeGamePageState extends State<SnakeGamePage> {
int row = 20, column = 20;
List<int> borderList = [];
List<int> snakePosition = [];
int snakeHead = 0;
int score = 11;
late Direction direction;
late int foodPoistion;
@override
void initState() {
startGame();
super.initState(); }
void startGame() {
makeBorder();
generateFood();
direction = Direction.right;
snakePosition = [45, 44, 43];
snakeHead = snakePosition.first;
Timer.periodic(const Duration(milliseconds: 300), (timer) {
updateSnake();
if (checkCollision()) {
timer.cancel();
showGameOverDialog(); } }); }
void showGameOverDialog() {
showDialog(
context: context,
barrierDismissible: false,
builder: (context) {
return AlertDialog(
title: const Text("Your are out Try Again!"),
content: const Text("Your snake got collided!"),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
startGame();
},
child: const Text("Try again")) ], ); }, ); }
bool checkCollision() {
if (borderList.contains(snakeHead)) return true;
if (snakePosition.sublist(1).contains(snakeHead)) return true;
return false; }
void generateFood() {
foodPoistion = Random().nextInt(row * column);
if (borderList.contains(foodPoistion)) {
generateFood(); } }
void updateSnake() {
setState(() {
switch (direction) {
case Direction.up:
snakePosition.insert(0, snakeHead - column);
break;
case Direction.down:
snakePosition.insert(0, snakeHead + column);
break;
case Direction.right:
snakePosition.insert(0, snakeHead + 1);
break;
case Direction.left:
snakePosition.insert(0, snakeHead - 1);
break;} });
if (snakeHead == foodPoistion) {
score++;
generateFood();
} else { snakePosition.removeLast(); }
snakeHead = snakePosition.first; }
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [Expanded(child: _buildGameView()), _buildGameControls()],),);}
Widget _buildGameView() {
return GridView.builder(
gridDelegate:
SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: column),
itemBuilder: (context, index) {
return Container(
margin: const EdgeInsets.all(1),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
color: fillBoxColor(index)), );},
itemCount: row * column, );}
Widget _buildGameControls() {
return Container(
padding: const EdgeInsets.all(20),
width: double.infinity,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Score : $score"),
IconButton(
onPressed: () {
if (direction != Direction.down) direction = Direction.up;},
icon: const Icon(Icons.arrow_circle_up),
iconSize: 100,),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
IconButton(
onPressed: () {
if (direction != Direction.right) direction = Direction.left;},
icon: const Icon(Icons.arrow_circle_left_outlined),
iconSize: 100,),
const SizedBox(width: 100),
IconButton(
onPressed: () {
if (direction != Direction.left) direction = Direction.right;},
icon: const Icon(Icons.arrow_circle_right_outlined),
iconSize: 100,),],),
IconButton(
onPressed: () {
if (direction != Direction.up) direction = Direction.down;},
icon: const Icon(Icons.arrow_circle_down_outlined),
iconSize: 100, ), ], ), ); }
Color fillBoxColor(int index) {
if (borderList.contains(index))
return Colors.yellow;
else {
if (snakePosition.contains(index)) {
if (snakeHead == index) {
return Colors.green;
} else {
return Colors.white.withOpacity(0.9); }
} else {
if (index == foodPoistion) {
return Colors.red; } } }
return Colors.grey.withOpacity(0.05); }
makeBorder() {
for (int i = 0; i < column; i++) {
if (!borderList.contains(i)) borderList.add(i); }
for (int i = 0; i < row * column; i = i + column) {
if (!borderList.contains(i)) borderList.add(i); }
for (int i = column - 1; i < row * column; i = i + column) {
if (!borderList.contains(i)) borderList.add(i); }
for (int i = (row * column) - column; i < row * column; i = i + 1) {
if (!borderList.contains(i)) borderList.add(i); } } }
OUTPUT:
RESULT:
Thus developing of gaming application that uses 2-D animations and gesture was done
successfully.
EXERCISE NO: 5
Develop a movie rating application (similar to IMDB)
AIM:
To develop a movie rating application that is similar to IMDB.
PROCEDURE:
STEP 1: Create a new Flutter project in Android Studio by Clicking on File -> New Flutter
Project.
STEP 2: Now specify the name of the project all in lowercase separated by hyphens “-” and
select the languages to be Objective C and Java.
STEP 3: Now a new Flutter project will be created and the main.dart file will be present in the
lib folder.
STEP 4: Change the main.dart file by adding Widgets and GUI components required to create a
movie rating application.
STEP 5: Run the main.dart file by connecting it to a virtual emulator.
PROGRAM:
//main.dart
import 'package:flutter/material.dart';
void main() {
runApp(MovieRatingApp());
}
class MovieRatingApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Movie Rating App',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MovieListScreen(),
);
}
}
class MovieListScreen extends StatelessWidget {
final List<Movie> movies = [
Movie(name: "Movie 1", image: "assets/img.png"),
Movie(name: "Movie 2", image: "assets/img_1.png"),
Movie(name: "Movie 3", image: "assets/img_2.png"),
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Movies'),
),
body: GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: _crossAxisCount(context),
crossAxisSpacing: 4.0,
mainAxisSpacing: 4.0,
),
itemCount: movies.length,
itemBuilder: (context, index) {
final movie = movies[index];
return MovieBox(movie: movie);
},
),
);
}
int _crossAxisCount(BuildContext context) {
final screenWidth = MediaQuery.of(context).size.width;
return (screenWidth ~/ 150).clamp(1, 5);
}
}
class MovieBox extends StatefulWidget {
final Movie movie;
MovieBox({required this.movie});
@override
_MovieBoxState createState() => _MovieBoxState();
}
class _MovieBoxState extends State<MovieBox> {
int _rating = 0;
void _setRating(int rating) {
setState(() {
_rating = rating;
});
}
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.grey),
borderRadius: BorderRadius.circular(8.0),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Expanded(
child: Image.asset(
widget.movie.image,
fit: BoxFit.cover,
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Text(
widget.movie.name,
textAlign: TextAlign.center,
style: TextStyle(fontSize: 12.0),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
GestureDetector(
onTap: () => _setRating(1),
child: Icon(
_rating >= 1 ? Icons.star : Icons.star_border,
color: Colors.yellow,),),
GestureDetector(
onTap: () => _setRating(2),
child: Icon(
_rating >= 2 ? Icons.star : Icons.star_border,
color: Colors.yellow,),),
GestureDetector(
onTap: () => _setRating(3),
child: Icon(
_rating >= 3 ? Icons.star : Icons.star_border,
color: Colors.yellow,),),
GestureDetector(
onTap: () => _setRating(4),
child: Icon(
_rating >= 4 ? Icons.star : Icons.star_border,
color: Colors.yellow, ), ),
GestureDetector(
onTap: () => _setRating(5),
child: Icon(
_rating >= 5 ? Icons.star : Icons.star_border,
color: Colors.yellow, ), ),
SizedBox(width: 5),
Text(
'Rating',
style: TextStyle(fontSize: 12.0),), ],),], ), ),], ), ); }}
class Movie {
final String name;
final String image;
Movie({required this.name, required this.image});
}
OUTPUT:
RESULT:
Thus the development of a movie rating application that is similar to IMDB was done
successfully.
EXERCISE NO: 6
Develop an application to connect to a web service and to retrieve data with HTTP.
AIM:
To develop an application to connect to a web service and to retrieve data with HTTP.
PROCEDURE:
STEP 1: Create a new Flutter project in Android Studio by Clicking on File -> New Flutter
Project.
STEP 2: Now specify the name of the project all in lowercase separated by hyphens “-” and
select the languages to be Objective C and Java.
STEP 3: Now a new Flutter project will be created and the main.dart file will be present in the
lib folder.
STEP 4: Change the main.dart file by adding Widgets and GUI components required to create
an application to connect to a web service and to retrieve data with HTTP.
STEP 5: Run the main.dart file by connecting it to a virtual emulator.
PROGRAM:
//main.dart
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_display/TO%20DO/todo_list.dart';
import 'package:flutter/material.dart';
Future<void> main() async {
// Connets your flutter project with firebase
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: TodoList(),
);
}
}
//home_page.dart
import 'package:firebase_display/splash_screen.dart';
import 'package:flutter/material.dart';
import 'google_login_auth.dart';
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
actions: [
ElevatedButton(
child: const Text(
"Logout",
style: TextStyle(color: Colors.black),
),
onPressed: () async {
await FirebaseServices().googleSignOut();
// ignore: use_build_context_synchronously
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const AuthSplashScreen()));
},
),
],
automaticallyImplyLeading: false,
title: const Text("Auto login"),
),
body: const Center(
child: Text(
"Welcome",
style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),
),
));
}
}
//google_login_auth.dart
import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
FirebaseAuth auth = FirebaseAuth.instance;
GoogleSignIn googleSignIn = GoogleSignIn();
class FirebaseServices {
final auth = FirebaseAuth.instance;
final googleSignIn = GoogleSignIn();
signInWithGoogle() async {
try {
final GoogleSignInAccount? googleSignInAccount =
await googleSignIn.signIn();
if (googleSignInAccount != null) {
final GoogleSignInAuthentication googleSignInAuthentication =
await googleSignInAccount.authentication;
final AuthCredential authCredential = GoogleAuthProvider.credential(
accessToken: googleSignInAuthentication.accessToken,
idToken: googleSignInAuthentication.idToken);
await auth.signInWithCredential(authCredential);
}
} on FirebaseAuthException catch (e) {
print(e.message);
throw e;
}
}
googleSignOut() async {
await auth.signOut();
await googleSignIn.signOut();
}
}
//firebase_image.dart
import 'package:flutter/material.dart';
import 'package:firebase_storage/firebase_storage.dart';
class FirestoreImageDisplay extends StatefulWidget {
const FirestoreImageDisplay({super.key});
@override
State<FirestoreImageDisplay> createState() => _MyWidgetState();
}
class _MyWidgetState extends State<FirestoreImageDisplay> {
late String imageUrl;
late String imageUrl1;
final storage = FirebaseStorage.instance;
@override
void initState() {
super.initState();
// Set the initial value of imageUrl to an empty string
imageUrl = '';
imageUrl1 = '';
//Retrieve the imge grom Firebase Storage
getImageUrl();
}
Future<void> getImageUrl() async {
// Get the reference to the image file in Firebase Storage
final ref = storage.ref().child('banner.jpg');
final ref1 = storage.ref().child('java.jpg');
// Get teh imageUrl to download URL
final url = await ref.getDownloadURL();
final url1 = await ref1.getDownloadURL();
setState(() {
imageUrl = url;
imageUrl1 = url1;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Display image from fiebase "),
),
body: Column(
children: [
SizedBox(
height: 300,
child: Image(
image: NetworkImage(imageUrl),
fit: BoxFit.cover,
)),
Card(
child: SizedBox(
height: 300,
child: Image(
image: NetworkImage(imageUrl1),
fit: BoxFit.cover,
)),
)
],
),
);
}
}
OUTPUT:
RESULT:
Thus the development of a movie rating application that is similar to IMDB was done
successfully.
EXERCISE NO: 7
Develop a simple shopping application.
AIM:
To develop a simple shopping application.
PROCEDURE:
STEP 1: Create a new Flutter project in Android Studio by Clicking on File -> New Flutter
Project.
STEP 2: Now specify the name of the project all in lowercase separated by hyphens “-” and
select the languages to be Objective C and Java.
STEP 3: Now a new Flutter project will be created and the main.dart file will be present in the
lib folder.
STEP 4: Change the main.dart file by adding Widgets and GUI components required to create a
simple shopping application.
STEP 5: Run the main.dart file by connecting it to a virtual emulator.
PROGRAM:
import 'package:flutter/material.dart';
void main() {
runApp(ECommerceApp());
}
class ECommerceApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'E-Commerce App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomePage(),
routes: {
'/cart': (context) => CartPage(),
},
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
List<String> cartItems = [];
void addToCart(String item) {
setState(() {
cartItems.add(item);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Shop'),
),
body: Stack(
children: [
ListView(
children: [
Padding(
padding: const EdgeInsets.only(bottom: 80.0),
child: Center(
child: Container(
width: 400.0, // Set container width to 400
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
ItemCard(
image: "assets/2.jpg",
name: 'Watch',
price: 50,
onAddToCart: () => addToCart('Watch'),
),
SizedBox(height: 20.0),
ItemCard(
image: "assets/1.jpg",
name: 'Phone',
price: 100,
onAddToCart: () => addToCart('Phone'),
),
SizedBox(height: 20.0),
ItemCard(
image: "assets/3.jpg",
name: 'Keyboard',
price: 80,
onAddToCart: () => addToCart('Keyboard'),
),
SizedBox(height: 20.0),
ItemCard(
image: "assets/4.jpg",
name: 'Mouse',
price: 40,
onAddToCart: () => addToCart('Mouse'),
),
],
),
),
),
),
],
),
Positioned(
left: 0,
right: 0,
bottom: 0,
child: Container(
color: Colors.blue,
height: 80,
width: MediaQuery.of(context).size.width,
child: Center(
child: ElevatedButton(
onPressed: () {
Navigator.pushNamed(
context,
'/cart',
arguments: cartItems,
);
},
child: Text('View Cart'),
),
),
),
),
],
),
);
}
}
class ItemCard extends StatelessWidget {
final String image;
final String name;
final int price;
final Function()? onAddToCart;
const ItemCard({
required this.image,
required this.name,
required this.price,
this.onAddToCart,
});
@override
Widget build(BuildContext context) {
return Card(
elevation: 4.0,
child: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Image.asset(
image,
height: 100,
fit: BoxFit.cover,
),
SizedBox(height: 10.0),
Text(
name,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18.0,
),
),
SizedBox(height: 10.0),
Text(
'\$$price',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16.0,
color: Colors.blue,
),
),
SizedBox(height: 10.0),
ElevatedButton(
onPressed: onAddToCart,
child: Text('Add to Cart'),
),
],
),
),
);
}
}
class CartPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final List<String> cartItems = ModalRoute.of(context)!.settings.arguments as List<String>;
final Map<String, int> itemCounts = {};
for (String item in cartItems) {
itemCounts[item] = (itemCounts[item] ?? 0) + 1;
}
// Prices of each item
final Map<String, int> itemPrices = {
'Watch': 50,
'Phone': 100,
'Keyboard': 80,
'Mouse':50
};
int totalAmount = 0;
for (var entry in itemCounts.entries) {
final itemName = entry.key;
final itemCount = entry.value;
final itemPrice = itemPrices[itemName] ?? 0;
totalAmount += (itemCount * itemPrice);
}
return Scaffold(
appBar: AppBar(
title: Text('Cart'),
),
body: Center(
child: Container(
width: 300,
padding: EdgeInsets.all(20),
decoration: BoxDecoration(
color: Colors.grey[200],
borderRadius: BorderRadius.circular(10),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Your Order',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
),
),
SizedBox(height: 20),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: itemCounts.entries.map((entry) {
final itemName = entry.key;
final itemCount = entry.value;
final itemPrice = itemPrices[itemName] ?? 0;
final totalItemPrice = itemCount * itemPrice;
return Text('$itemName x $itemCount = \$$totalItemPrice');
}).toList(),
),
Divider(
height: 30,
thickness: 2,
color: Colors.black,
),
Text(
'Total = \$$totalAmount',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18,
),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {
print('Payment logic goes here');
},
child: Text('Pay'),
),
],
),
),
),
);
}
}
OUTPUT:
RESULT:
Thus the development of a simple shopping application was done successfully.