Created
June 28, 2021 04:56
-
-
Save utgupta27/0d490b87ef21720b14f24f219da6a6c8 to your computer and use it in GitHub Desktop.
State Management in Flutter using Provider(5.0.0) Package
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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