Last active
July 26, 2022 01:06
-
-
Save terryl1900/73151e2b1b37c6677ee23c38f9218538 to your computer and use it in GitHub Desktop.
Counter app with provider
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'; | |
// 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