Skip to content

Instantly share code, notes, and snippets.

@biniama
Last active December 8, 2022 12:50
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 biniama/9b959e92a336da2340dd6918fca97d62 to your computer and use it in GitHub Desktop.
Save biniama/9b959e92a336da2340dd6918fca97d62 to your computer and use it in GitHub Desktop.
StateNotifier and StateNotifierProvider Example for Flutter
//Add the following in `pubspec.yaml`
dependencies:
flutter_riverpod: ^2.1.1
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
void main() => runApp(ProviderScope(child: MyApp()));
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'RiverPod!',
theme: ThemeData(primarySwatch: Colors.blue),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('State Management with RiverPod!'),
),
body: Column(
children: [
FavScreen(),
],
),
);
}
}
final favProvider = StateNotifierProvider<FavNotifier, List<String>>((ref) {
return FavNotifier();
});
class FavNotifier extends StateNotifier<List<String>> {
FavNotifier() : super([]);
void add(String fav) {
state = [...state, fav];
}
void remove(String taskId) {
state = [
for (final todo in state)
if (todo != taskId) todo,
];
}
void toggle(String taskId) {
print('state $state');
print('taskId $taskId');
(state.contains(taskId)) ? remove(taskId) : add(taskId);
print('state $state');
}
}
class FavScreen extends ConsumerWidget {
List<Map<String, String>> data = [{"id": '1', 'title': '1'},{"id": '2', 'title': '2'},{'id': '3', 'title': '3'},{'id': '4', 'title': '4'}];
@override
Widget build(BuildContext context, WidgetRef ref) {
return Column(
children: data.map((element) => FavItem(fav: element)).toList(),
);
}
}
class FavItem extends ConsumerWidget {
final Map<String, String> fav;
FavItem({Key? key, required this.fav}) : super(key: key);
@override
Widget build(BuildContext context, WidgetRef ref) {
List<String> favIds = ref.watch(favProvider);
return Row(
children: [
Checkbox(
onChanged: (newValue) => ref.read(favProvider.notifier).toggle(fav['id']!),
value: favIds.contains(fav['id']),
),
Text(fav['title']!),
],
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment