Counter App with Provider State Management

 import "package:flutter/material.dart";

import "package:provider/provider.dart";
import "package:provider_wslc_statemanagement/providers/counterprovider.dart";

void main() {
runApp(const MyApp());
}

class MyApp extends StatelessWidget {
const MyApp({super.key});

@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) {
return CounterProvider();
},
child: MaterialApp(
title: "Counter App with Provider State Management",
debugShowCheckedModeBanner: false,
theme: ThemeData(
appBarTheme: const AppBarTheme(
backgroundColor: Colors.grey,
centerTitle: true,
),
),
home: const CounterAppTwo(),
),
);
}
}

class CounterAppTwo extends StatelessWidget {
const CounterAppTwo({super.key});

@override
Widget build(BuildContext context) {
final counter = Provider.of<CounterProvider>(context, listen: false);
print("Build Method Called...");

return Scaffold(
appBar: AppBar(
title: const Text(
"Counter App with Provider",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
body: Consumer<CounterProvider>(
builder: (context, value, child) {
print("Consumer, only text widget will rebuild...");
return Center(
child: Text(
value.count.toString(),
style:
const TextStyle(fontWeight: FontWeight.bold, fontSize: 60.0),
),
);
},
),
floatingActionButton: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
FloatingActionButton(
onPressed: () {
counter.increment();
},
backgroundColor: Colors.blue,
child: const Icon(Icons.add, color: Colors.white, size: 30.0),
),
const SizedBox(width: 20.0),
FloatingActionButton(
onPressed: () {
counter.decrement();
},
backgroundColor: Colors.blue,
child: const Icon(Icons.remove, color: Colors.white, size: 30.0),
),
const SizedBox(width: 20.0),
FloatingActionButton(
onPressed: () {
counter.setZero();
},
backgroundColor: Colors.brown,
child:
const Icon(Icons.lock_clock, color: Colors.white, size: 30.0),
),
],
),
);
}
}
import "package:flutter/material.dart";

class CounterProvider extends ChangeNotifier {
int count = 0;

increment() {
count++;
notifyListeners();
}

decrement() {
count--;
notifyListeners();
}

setZero() {
count = 0;
notifyListeners();
}
}




Comments

Popular posts from this blog

Second GET API Calling with Bloc simple Example in Flutter

Stack Container Scrollable Card widget UI with Custom Widget

Pagination with Bloc Pattern in Flutter