Last active
May 18, 2019 11:02
-
-
Save apaatsio/52cccc8381450c3a55566ec1754d1006 to your computer and use it in GitHub Desktop.
Flutter: Simple counter using ChangeNotifierProvider
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'; | |
class Counter extends ChangeNotifier { | |
Counter(int initialValue) : _value = initialValue; | |
int _value; | |
set value(int newValue) { | |
_value = newValue; | |
notifyListeners(); | |
} | |
int get value => _value; | |
} | |
void main() { | |
runApp( | |
ChangeNotifierProvider<Counter>( | |
builder: (_) => Counter(0), | |
child: MyApp(), | |
), | |
); | |
} | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'ChangeNotifierProvider Demo', | |
home: MyHomePage(), | |
); | |
} | |
} | |
class MyHomePage extends StatelessWidget { | |
void _incrementCounter(BuildContext context) { | |
final counter = Provider.of<Counter>(context); | |
counter.value++; | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
body: Center( | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: <Widget>[ | |
Text('You have pushed the button this many times:'), | |
Consumer<Counter>( | |
builder: (context, counter, _) => Text( | |
'${counter.value}', | |
style: Theme.of(context).textTheme.display1, | |
), | |
), | |
], | |
), | |
), | |
floatingActionButton: FloatingActionButton( | |
onPressed: () => _incrementCounter(context), | |
tooltip: 'Increment', | |
child: Icon(Icons.add), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment