Last active
September 30, 2019 03:28
-
-
Save jtlapp/c9f1afce36423152a5bbcba5adcf5319 to your computer and use it in GitHub Desktop.
Counter app with provider - complex version
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() => runApp(MyApp()); | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return ChangeNotifierProvider<Counter>( // <=== PROVIDER | |
builder: (context) => Counter(), | |
child: MaterialApp( | |
title: 'Counter App - Complex', | |
home: MyPage(), | |
), | |
); | |
} | |
} | |
class MyPage extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: Text("Page Title"), | |
), | |
body: Center( | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: [ | |
Consumer<Counter>( // <=== DEPENDENT | |
builder: (context, counter, child) => Text( | |
'${counter.count}', | |
style: Theme.of(context).textTheme.display1, | |
), | |
), | |
IncrementButton(), // <=== DEPENDENT | |
], | |
), | |
), | |
); | |
} | |
} | |
class IncrementButton extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
final counter = Provider.of<Counter>(context, listen: false); | |
return RaisedButton( | |
onPressed: () => counter.increment(), | |
child: Text("Increment"), | |
); | |
} | |
} | |
class Counter with ChangeNotifier { | |
int count = 0; | |
void increment() { | |
++count; | |
notifyListeners(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment