Last active
December 3, 2022 15:32
-
-
Save jtlapp/db7677d0123d45daebf65e6f49717bc4 to your computer and use it in GitHub Desktop.
Counter app implemented with ChangeNotifierProvider
This file contains hidden or 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() => runApp(MyApp()); | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'Flutter Demo', | |
home: MyHomePage(), | |
); | |
} | |
} | |
// Counter app with provider | |
class Counter with ChangeNotifier { | |
int count = 0; | |
void increment() { | |
++count; | |
notifyListeners(); | |
} | |
} | |
class MyHomePage extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return ChangeNotifierProvider<Counter>( | |
builder: (context) => Counter(), | |
child: Scaffold( | |
appBar: AppBar( | |
title: Text("Page Title"), | |
), | |
body: Center( | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: [ | |
Consumer<Counter>( | |
builder: (context, counter, child) => Text( | |
'${counter.count}', | |
style: Theme.of(context).textTheme.display1, | |
), | |
), | |
Builder(builder: (context) { | |
final counter = | |
Provider.of<Counter>(context, listen: false); | |
return RaisedButton( | |
onPressed: () => counter.increment(), | |
child: Text("Increment"), | |
); | |
}), | |
], | |
), | |
), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment