Skip to content

Instantly share code, notes, and snippets.

@jtlapp
Last active October 19, 2021 17:39
Show Gist options
  • Save jtlapp/60e3628f271a069ab7e14a4b89d2707d to your computer and use it in GitHub Desktop.
Save jtlapp/60e3628f271a069ab7e14a4b89d2707d to your computer and use it in GitHub Desktop.
Counter app with provider - compact version
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 - Compact',
home: 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,
),
),
Builder(builder: (context) { // <=== DEPENDENT
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