Skip to content

Instantly share code, notes, and snippets.

@MCarlomagno
Created January 12, 2022 20:07
Show Gist options
  • Save MCarlomagno/d45b5feae0c21b278d2be3c8297d48d2 to your computer and use it in GitHub Desktop.
Save MCarlomagno/d45b5feae0c21b278d2be3c8297d48d2 to your computer and use it in GitHub Desktop.
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(
MultiProvider(
providers: [
// Counter is the name of the provider model
// we will use to update the state of the Widgets
ChangeNotifierProvider(create: (_) => Counter()),
],
child: const MyApp(),
),
);
}
class Counter with ChangeNotifier, DiagnosticableTreeMixin {
int _count = 0;
int get count => _count;
void increment() {
_count++;
notifyListeners();
}
}
class MyWidget extends StatelessWidget {
const MyWidget({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Example'),
),
body: Center(
child: Column(
children: const <Widget>[
Text('You have pushed the button this many times:'),
Count(),
],
),
),
floatingActionButton: FloatingActionButton(
key: const Key('increment_floatingActionButton'),
// access to the Counter provider using the context
// and increments its value.
onPressed: () => context.read<Counter>().increment(),
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
class Count extends StatelessWidget {
const Count({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Text(
// rebuilds the UI wach time the count variable is
// updated inside the provider using watch method
'${context.watch<Counter>().count}',
key: const Key('counterState'),
style: Theme.of(context).textTheme.headline4);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment