Skip to content

Instantly share code, notes, and snippets.

@manofi21
Last active January 20, 2022 09:55
Show Gist options
  • Select an option

  • Save manofi21/aa540b8203aa323c7ac6a32823fcec97 to your computer and use it in GitHub Desktop.

Select an option

Save manofi21/aa540b8203aa323c7ac6a32823fcec97 to your computer and use it in GitHub Desktop.
Example #Riverpod
// Tambah variable state provider untuk nilai yang bisa di ubah2.
final pageIndexProvider = StateProvider<int>((ref) => 1);
// Tambah provider yang hanya bisa update jika nilai dari pageIndexProvider
// ! note: Nilai dalam provider tidak bisa di ubah dari luar, untuk menghindari rebuild yang tidak perlu.
final canGoToPreviousPageProvider = Provider<bool>((ref) {
return ref.watch(pageIndexProvider) == 0;
});
class PreviousButton extends ConsumerWidget {
const PreviousButton({Key? key}) : super(key: key);
@override
Widget build(BuildContext context, WidgetRef ref) {
// if not on first page, the previous button is active
final canGoToPreviousPage = ref.watch(canGoToPreviousPageProvider);
void goToPreviousPage() {
ref.read(pageIndexProvider.notifier).update((state) => state - 1);
}
return ElevatedButton(
onPressed: canGoToPreviousPage ? null : goToPreviousPage,
child: const Text('previous'),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment