Skip to content

Instantly share code, notes, and snippets.

@champaksworldcreate
Last active April 8, 2022 05:21
Show Gist options
  • Save champaksworldcreate/52ba37bcb21a2b7fd6a6ed122c693b17 to your computer and use it in GitHub Desktop.
Save champaksworldcreate/52ba37bcb21a2b7fd6a6ed122c693b17 to your computer and use it in GitHub Desktop.
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(
MultiProvider(
providers: [
ChangeNotifierProvider(create: (context) => VsjBank()),
],
child: const VsjApp(),
),
);
}
class VsjBank with ChangeNotifier {
final Account _balance = Account();
Account get balance => _balance;
void deposit() {
_balance.balance += 10;
_balance.nooftransactions += 1;
notifyListeners();
}
void withdraw() {
_balance.balance -= 5;
_balance.nooftransactions += 1;
// notifyListeners();
}
void notify() {
notifyListeners();
}
}
class VsjApp extends StatelessWidget {
const VsjApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: const Text('Vsj Provider Demo'),
centerTitle: true,
backgroundColor: Colors.teal,
),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Card(
child: Text(
'Account Details',
style: TextStyle(fontWeight: FontWeight.bold),
)),
const AccountManager(),
Padding(
padding: const EdgeInsets.all(8.0),
child: ElevatedButton(
onPressed: () => context.read<VsjBank>().deposit(),
child: const Text('\nDeposit\nCalls notify\n'),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: ElevatedButton(
onPressed: () => context.read<VsjBank>().withdraw(),
child: const Text('\nWithdraw\nNo notify\n'),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: ElevatedButton(
onPressed: () => context.read<VsjBank>().notify(),
child: const Text('\nOnly Notify\n'),
),
),
const Card(
child: Text(
'Account Details Repeat',
style: TextStyle(fontWeight: FontWeight.bold),
)),
const AccountManager(),
],
),
),
),
);
}
}
class AccountManager extends StatelessWidget {
const AccountManager({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Column(
children: [
Text('Balance ${context.watch<VsjBank>().balance.balance}'),
Text(
'Transactions ${context.watch<VsjBank>().balance.nooftransactions}'),
],
);
}
}
class Account {
int nooftransactions = 0, balance = 0;
@override
String toString() {
return balance.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment