Created
August 13, 2022 23:30
-
-
Save FlutterZeroGit/7c1feba49633fd0e43f59ba7f445fbce to your computer and use it in GitHub Desktop.
StatelessWidget: Riverpod
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:flutter_riverpod/flutter_riverpod.dart'; | |
class CounterNotifier extends ChangeNotifier { | |
int _count = 0; | |
void add() { | |
_count++; | |
notifyListeners(); | |
} | |
void subtract() { | |
_count--; | |
notifyListeners(); | |
} | |
} | |
final counterProvider = ChangeNotifierProvider( | |
(ref) => CounterNotifier(), | |
); | |
void main() => runApp(ProviderScope(child: MyApp())); | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
home: Scaffold( | |
appBar: AppBar(title: const Text('FlutterZero')), | |
body: Center( | |
child: Consumer( | |
builder: (context, ref, child) { | |
final count = ref.watch(counterProvider); | |
return Row( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: [ | |
IconButton( | |
icon: Icon(Icons.remove), | |
onPressed: () => count.subtract(), | |
), | |
Text( | |
count._count.toString(), | |
style: TextStyle(fontSize: 30), | |
), | |
IconButton( | |
icon: Icon(Icons.add), | |
onPressed: () => count.add(), | |
), | |
], | |
); | |
}, | |
), | |
), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment