Created
September 18, 2019 13:53
-
-
Save jtlapp/1dd73beba80b33377fa6866c02d4e40d to your computer and use it in GitHub Desktop.
Counter app implemented with provider and StatefulWidget
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 MaterialApp( | |
title: 'Flutter Demo', | |
home: MyHomePage(), | |
); | |
} | |
} | |
// Counter app with InheritedWidget | |
class MyHomePage extends StatelessWidget { | |
Widget build(BuildContext context) { | |
return CounterWidget( | |
child: Scaffold( | |
appBar: AppBar( | |
title: Text("Page Title"), | |
), | |
body: Center( | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: [ | |
Consumer<int>(builder: (context, count, child) { | |
return Text( | |
'$count', | |
style: Theme.of(context).textTheme.display1, | |
); | |
}), | |
Consumer<CounterState>(builder: (context, counter, child) { | |
return RaisedButton( | |
onPressed: () => counter.incrementCount(), | |
child: Text("Increment"), | |
); | |
}), | |
], | |
), | |
), | |
), | |
); | |
} | |
} | |
class CounterWidget extends StatefulWidget { | |
CounterWidget({Key key, @required this.child}) : super(key: key); | |
final Widget child; | |
@override | |
CounterState createState() => CounterState(); | |
} | |
class CounterState extends State<CounterWidget> { | |
int count = 0; | |
void incrementCount() { | |
setState(() { | |
++count; | |
}); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Provider.value( | |
value: count, | |
child: Provider.value( | |
value: this, | |
child: widget.child, | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment