Skip to content

Instantly share code, notes, and snippets.

@kwony
Last active January 4, 2023 05:00
Embed
What would you like to do?
flutter changenotifier sample
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(ChangeNotifierProvider(
create: (_) => ExampleModel(),
child: Example(),
));
}
class Example extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Consumer<ExampleModel>(
child: GestureDetector(
child: const Text(
"increase tap",
style: TextStyle(fontSize: 30),
),
onTap: () {
context.read<ExampleModel>().increaseCount();
},
),
builder: (context, model, child) {
return Column(
children: [
const SizedBox(
height: 30,
),
Text("count: ${model.counter}"),
const SizedBox(
height: 30,
),
if (child != null) child
],
);
},
));
}
}
class ExampleModel with ChangeNotifier {
int counter = 0;
increaseCount() {
counter++;
notifyListeners();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment