Skip to content

Instantly share code, notes, and snippets.

@utgupta27
Created June 28, 2021 04:56
Show Gist options
  • Save utgupta27/0d490b87ef21720b14f24f219da6a6c8 to your computer and use it in GitHub Desktop.
Save utgupta27/0d490b87ef21720b14f24f219da6a6c8 to your computer and use it in GitHub Desktop.
State Management in Flutter using Provider(5.0.0) Package
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() async{
WidgetsFlutterBinding.ensureInitialized();
runApp(
ChangeNotifierProvider(
create: (context) => Counter(),
child: MyApp(),),
);
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
Counter counter = Provider.of<Counter>(context,listen: false);
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'${Provider.of<Counter>(context).getCount}',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: counter.incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
class Counter extends ChangeNotifier{
int _counter = 0;
int get getCount => _counter;
void incrementCounter(){
_counter++;
notifyListeners();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment