Skip to content

Instantly share code, notes, and snippets.

@kwony
Last active January 4, 2023 05:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kwony/5b0db9f171c8fe01034c71e99a66051d to your computer and use it in GitHub Desktop.
Save kwony/5b0db9f171c8fe01034c71e99a66051d to your computer and use it in GitHub Desktop.
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