Skip to content

Instantly share code, notes, and snippets.

@apaatsio
Last active May 18, 2019 11:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save apaatsio/52cccc8381450c3a55566ec1754d1006 to your computer and use it in GitHub Desktop.
Save apaatsio/52cccc8381450c3a55566ec1754d1006 to your computer and use it in GitHub Desktop.
Flutter: Simple counter using ChangeNotifierProvider
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