Skip to content

Instantly share code, notes, and snippets.

@FlutterZeroGit
Created August 13, 2022 23:30
Show Gist options
  • Save FlutterZeroGit/7c1feba49633fd0e43f59ba7f445fbce to your computer and use it in GitHub Desktop.
Save FlutterZeroGit/7c1feba49633fd0e43f59ba7f445fbce to your computer and use it in GitHub Desktop.
StatelessWidget: Riverpod
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