Last active
January 4, 2023 05:00
-
-
Save kwony/5b0db9f171c8fe01034c71e99a66051d to your computer and use it in GitHub Desktop.
flutter changenotifier sample
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'; | |
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