Skip to content

Instantly share code, notes, and snippets.

@aliyazdi75
Last active April 17, 2023 17:46
Show Gist options
  • Save aliyazdi75/7d42326bd50345c14077cfc8f52f8db4 to your computer and use it in GitHub Desktop.
Save aliyazdi75/7d42326bd50345c14077cfc8f52f8db4 to your computer and use it in GitHub Desktop.
Provider example
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class Item {
Item({required this.name});
String name;
}
class CartState extends ChangeNotifier {
final List<Item> _items = [];
List<Item> get items => _items;
int get totalPrice => _items.length * 42;
void add(Item item) {
_items.add(item);
notifyListeners();
}
void removeAll() {
_items.clear();
notifyListeners();
}
}
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatelessWidget {
final String title;
const MyHomePage({
Key? key,
required this.title,
}) : super(key: key);
void _addAProduct(BuildContext context, String name) {
Provider.of<CartState>(context, listen: false).add(Item(name: name));
}
void _deleteAllProducts(BuildContext context) {
Provider.of<CartState>(context, listen: false).removeAll();
}
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) => CartState(),
child: Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
Text(
'Your Last Product:',
),
ProductName(),
],
),
),
floatingActionButton: Builder(
builder: (context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
FloatingActionButton(
onPressed: () => _addAProduct(context, 'Phone'),
tooltip: 'Add a phone',
child: const Icon(Icons.phone),
),
FloatingActionButton(
onPressed: () => _addAProduct(context, 'Laptop'),
tooltip: 'Add a product',
child: const Icon(Icons.laptop),
),
FloatingActionButton(
onPressed: () => _deleteAllProducts(context),
tooltip: 'Delete all products',
child: const Icon(Icons.delete),
),
],
);
}
),
),
);
}
}
class ProductName extends StatelessWidget {
const ProductName({super.key});
@override
Widget build(BuildContext context) {
return Consumer<CartState>(
builder: (context, cart, child) {
return Text(
cart.items.isEmpty ? 'Nothing!' : cart.items.last.name,
style: Theme.of(context).textTheme.headlineMedium,
);
},
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment