Skip to content

Instantly share code, notes, and snippets.

@terryl1900
Last active July 26, 2022 01:06
Show Gist options
  • Save terryl1900/73151e2b1b37c6677ee23c38f9218538 to your computer and use it in GitHub Desktop.
Save terryl1900/73151e2b1b37c6677ee23c38f9218538 to your computer and use it in GitHub Desktop.
Counter app with provider
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
// counter.dart
class CountNotifier extends ChangeNotifier {
int count = 0;
void increment() {
count += 1;
notifyListeners();
}
}
// main.dart
void main() {
runApp(ChangeNotifierProvider(
create: (_) => CountNotifier(), child: const MyApp()));
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Counter example')),
body: Center(
child: Text('${Provider.of<CountNotifier>(context).count}'),
),
floatingActionButton: FloatingActionButton(
onPressed: () =>
Provider.of<CountNotifier>(context, listen: false).increment(),
child: const Icon(Icons.add),
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment