Add to Cart using Provider in Flutter:Adding the product in cart using the provider State Management in Flutter.When developing the front-end app, it is necessary to handle the responses to each event triggered by UI activity. Technically, we must manage the state of UI components that change due to end-user interaction.
Provider:
The Provider is a state management solution that extends and simplifies Inherited Widgets. It is a versatile and powerful state manager that allows you to deliver data to any widget in your app. Also, it is fast and optimize to rebuild only the widgets that need to be update.
Three essential components of Flutter Provider state management:
Before using the provider state management in the Flutter app, we must first understand these basic concepts:
- ChangeNotifier
- ChangeNotifierProvider
- Consumer
ChangeNotifier
ChangeNotifier is a class that notifies its listeners when something changes. It is a more straightforward method for a limited number of listeners. It notifies its listeners about changes to the model using the notifyListeners() method.
ChangeNotifierProvider
ChangeNotifierProvider is a widget that delivers a ChangeNotifier instance. The code excerpt below will help you understand how it works.
Consumer
It is a widget with a builder function that is used to build the UI based on model updates. The builder function will pass the context, counter, and child parameters. Context is the same as every other widget creation function. The CounterModel member that was notice for change is the counter. For optimization, the third argument child is use.
Using Provider for state management in Flutter
To use Provider in your Flutter app, create a new project first, then add the following line to your pubspec.yaml file’s dependencies block:
dependencies:
provider: ^5.0.0
Adding Product to Cart Example
Main.dart
import 'package:flutter/material.dart';
import 'package:newproject/ProductScreen.dart';
import 'package:newproject/ProductVM.dart';
import 'package:provider/provider.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(
create: (context) => ProductsVM(),
),
],
child: MaterialApp(
title: 'State Management Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primaryColor: Colors.blue[200],
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: ProductScreen(),
),
);
}
}
Provider.dart
mport 'dart:math';
import 'package:flutter/material.dart';
import 'package:newproject/model.dart';
class ProductsVM with ChangeNotifier {
final List<Products> lst = [];
List<Products> get myList => lst;
add(String image, String name) {
lst.add(Products(image: image, name: name));
notifyListeners();
}
void removeFromList(String image, String name) {
lst.remove(Products(image: image, name: name));
notifyListeners();
}
del(int index) {
lst.removeAt(index);
notifyListeners();
}
}
model.dart
List of product details provides the details of product name, images,index
final prds = [
{
"name": "ABCD",
"image":
"https://media.ao.com/en-GB/Productimages/Images/rvMedium/iek6hwchzqbnz7uznug9um-iphone_14_productred_m_p.jpg"
},
{
"name": "QQWE",
"image":
"https://d1rlzxa98cyc61.cloudfront.net/catalog/product/cache/1801c418208f9607a371e61f8d9184d9/1/8/184913_2022.jpg"
},
{
"name": "WWSA",
"image":
"https://5.imimg.com/data5/ECOM/Default/2022/10/KQ/AW/MG/162219571/iphone-13-pro-mlvq3hn-a-apple-original-imag6vpc6mx3zwhz-500x500.jpg"
},
{
"name": "EXMP",
"image":
"https://5.imimg.com/data5/ANDROID/Default/2022/11/FK/NT/IA/83914669/product-jpeg-500x500.jpg"
},
{
"name": "SADS",
"image":
"https://5.imimg.com/data5/SELLER/Default/2023/8/337538182/SG/UY/DE/162018849/apple-iphone-13-pro-max-mobile-phone.png"
},
{
"name": "SADS",
"image":
"https://5.imimg.com/data5/ECOM/Default/2022/10/KQ/AW/MG/162219571/iphone-13-pro-mlvq3hn-a-apple-original-imag6vpc6mx3zwhz-500x500.jpg"
},
];
class Products {
Products({
required this.name,
required this.image,
});
String name;
String image;
Map<String, dynamic> toJson() => {
"name": name,
"image": image,
};
}
Product Screen.dart
import 'package:flutter/material.dart';
import 'package:newproject/CartScreen.dart';
import 'package:newproject/ProductItem.dart';
import 'package:newproject/ProductVM.dart';
import 'package:newproject/data.dart';
import 'package:provider/provider.dart';
class ProductScreen extends StatefulWidget {
@override
_ProductScreenState createState() => _ProductScreenState();
}
class _ProductScreenState extends State<ProductScreen> {
@override
Widget build(BuildContext context) {
final myList = context.watch<ProductsVM>().lst;
var screenSize = MediaQuery.of(context).size;
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
toolbarHeight: 50,
actions: [
InkWell(
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => CartScreen()));
},
child: Padding(
padding:
const EdgeInsets.only(left: 0, right: 10, top: 8, bottom: 8),
child: Stack(
alignment: AlignmentDirectional.center,
children: [
IconButton(
onPressed: () {},
icon: const Icon(
Icons.shopping_cart_rounded,
size: 30,
color: Colors.black,
),
),
Positioned(
top: 4,
right: 4,
child: Container(
height: 18,
width: 25,
decoration: const BoxDecoration(
shape: BoxShape.circle,
color: Colors.red,
),
child: Center(
child: Text(
"${myList.length}",
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.bold,
),
)),
),
),
],
),
),
)
],
leading: Padding(
padding: const EdgeInsets.all(8.0),
child: Icon(Icons.menu_rounded, color: Colors.blue, size: 25),
),
title: Center(
child: Text(
"My Cart",
style: TextStyle(color: Colors.blue),
),
),
),
body: Padding(
padding: const EdgeInsets.symmetric(vertical: 20),
child: SafeArea(
child: SingleChildScrollView(
child: Container(
height: screenSize.height * 0.24,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: prds.length,
itemBuilder: (context, index) => ProductItem(
screenSize: screenSize,
image: prds[index]["image"].toString(),
itemName: prds[index]["name"].toString(),
),
),
),
)),
),
);
}
}
CartList.dart
import 'package:flutter/material.dart';
import 'package:newproject/ProductVM.dart';
import 'package:provider/provider.dart';
class CartScreen extends StatefulWidget {
CartScreen({
Key? key,
}) : super(key: key);
@override
State<CartScreen> createState() => _CartScreenState();
}
class _CartScreenState extends State<CartScreen> {
@override
Widget build(BuildContext context) {
final myList = context.watch<ProductsVM>().lst;
return Scaffold(
appBar: AppBar(
title: Text("My List (${myList.length})"),
),
body: ListView.builder(
itemCount: myList.length,
itemBuilder: (_, index) {
return Card(
key: ValueKey(myList),
elevation: 4,
child: Column(
children: [
Image(
image: NetworkImage(
myList[index].image,
)),
Text(
myList[index].name,
),
TextButton(
child: const Text(
'Remove',
style: TextStyle(color: Colors.red),
),
onPressed: () {
context.read<ProductsVM>().del(index);
},
),
],
),
);
}),
);
}
}
Remove from the list:
To remove the product item from the list use the remove widget method which is giving below
del(int index) {
lst.removeAt(index);
notifyListeners();
}
For more: To know about Flutter Api Login page
Leave a Reply