onestudio-co / flutter-bond

Your next Flutter project template!
178 stars 49 forks source link

Use riverpod in collectios page #57

Closed MahmoudHafezDarwish closed 1 year ago

MahmoudHafezDarwish commented 1 year ago

ChangeNotifierProvider will give you the ability to notify listeners which in turn will rebuild with the new state. [image 1] image

When creating the presenter you should think about how the view and presenter should interact, keeping this in mind:

UI --- (triggers events) ---> Presenter

UI <---(reacts to) --- Presenter states

Hooks are a package that implements a new kind of object that manages a Widget life-cycles. They exist for one reason: increase the code-sharing between widgets by removing duplicates.

You can read more about hooks: https://pub.dev/packages/flutter_hooks

We use it with riverpod (hooks_riverpod package). This way we don't need Consumer widgets and our widget tree looks nicer: [image 2] image

RequestProvider: is an addition that helps us execute any long-running async operation, with states:

initial, loading, success and error.

Most often that will be API requests. We make each use case of data fetch into single provider that extends RequestProvider. And we can listen for changes and show appropriate UI:

success show data loading show loading indicator error show error message This does not mean that one request = one provider, because use case can be doing several connected requests (parallel or sequential) that will at the end produce one data class which UI needs. These all requests would be part of one provider.

If you don't need to watch for error or loading states for some reason, then you can do request without RequestNotifier (but I think this will be very rare). Usage Extend the request provider like in the CollectionsRequestProvider [image 1]

freezed is a library that generates code for creating immutable value objects with ease. It generates code that includes copyWith methods, == and hashCode implementations, and can also be used for union types. Essentially, freezed allows you to define a data class that is guaranteed to be immutable, and that has all the necessary methods for working with the object. that brings some Kotlin/Swift-like goodies that Dart is missing.