iTranslated by AI
Design Philosophy of Riverpod: A Personal Perspective
In this article, based on my personal perspective, I will examine the design philosophy that Riverpod introduces to applications. The design philosophy of a state management library strongly influences the applications that adopt it.
Design Philosophy
According to my observations, the main design rules introduced by Riverpod are as follows:
- PDS (Presentation Domain Separation)
- Reactive Programming
- Immutable objects
- Resource-heavy programming (for improved productivity)
- DI (utilizing Implicit interfaces)
I will summarize the key points based on my personal views. I have included links for each item wherever possible, so those who wish to verify more strict definitions or details can use those as a basis for their own consideration.
PDS (Presentation Domain Separation)
In my understanding, architectural patterns like MVC, MVP, and MVVM are used to realize PDS. While there are subtle differences depending on the architecture, those are simply debates on how to separate business logic from the UI.[1]
In Flutter, states can be described within the State of a StatefulWidget. This mechanism separates the View, which is rendered as a result of the Widget build(BuildContext context) method, from the Logic for that View. Because it is so commonplace, it is often overlooked, but this separation is confirmed to be extremely important when compared to pre-declarative UI days.
Aside from the logic corresponding to the View, the other logic that should be discussed is business logic.
In Flutter, views are the widget classes of your application. Views are the primary method of rendering UI, and shouldn't contain any business logic. They should be passed all data they need to render from the view model.
Although the official documentation's guide adopts the MVVM architecture, it also emphasizes the separation of business logic and UI.
Business logic can be described in the State class of a StatefulWidget. However, if you do this, the View-specific logic and the business logic will be mixed in one place. You might manage to get by if you mix them well, but in many cases, mechanisms are introduced to avoid such mixing. This is the reason why various state management libraries have emerged.
Using Flutter's built-in mechanisms, business logic can be separated from the UI by using InheritedWidget. The image is that InheritedWidget distributes objects that aggregate logic, and the UI references them via context. The downside of this design is that the learning cost is high and the amount of code to write is large. As a result, it can be said that it is a mechanism that is difficult to scale.
Currently, it is more common to use Provider, which is a high-quality wrapper around InheritedWidget. While there is no essential difference, the difference in code readability and the amount of code to write is significant.
The Flutter community continues to think about how to better separate business logic. For example, BLoC was introduced in the early days of Flutter, and there are several other patterns popular in the community, such as Redux and get_it.
In Riverpod, Provider or Notifier handles the business logic[2], and the UI references it via WidgetRef. Adopting Riverpod is synonymous with partitioning your code using Provider and Notifier. In summary, Riverpod is a tool for realizing PDS.
Reactive Programming
ReactiveX is a combination of the best ideas from the Observer pattern, the Iterator pattern, and functional programming
In my understanding, Reactive Programming is a technique that treats events as streams to be processed. More specifically, it refers to implementations realized by introducing tools like rxdart. While in some programming languages the aspect of the Iterator pattern becomes stronger, I believe that in Flutter and Dart, the aspect as the Observer pattern is stronger.
The basic usage of Riverpod is an example of the Observer pattern. The following (simplified) code is an example where a change in a User object is reflected in Text(username). Via ref.watch, each Observer reflects changes in the UI.
@riverpod
Stream<User?> user(Ref ref) {
final auth = ref.watch(authProvider);
return auth.authStateChanges();
}
@riverpod
String username(Ref ref) {
final user = ref.watch(userProvider).valueOrNull;
return user?.username ?? 'none';
}
~~~omitted~~~
Widget build(BuildContext context) {
final username = ref.watch(usernameProvider);
return Text(username);
}
ref.watch has a mechanism to "reflect updates of the Provider being referenced." The usernameProvider subscribes to the event published by userProvider. And the UI subscribes to the event published by usernameProvider. A pure Provider is like map in Rx.
Notifier can accept user operations. This enables a mechanism where user operations are reflected in the Notifier representing the business logic, and changes in the Notifier are reflected in the UI.
@riverpod
class Counter extends _$Counter {
@override
int build() => 0;
void increment() {
state++;
}
}
@riverpod
String countText(Ref ref) {
final counter = ref.watch(counterProvider);
return 'Count: ${counter}';
}
~~~omitted~~~
Widget build(BuildContext context) {
final countText = ref.watch(countTextProvider);
return Column(
children: [
Text(countText),
ElevatedButton,
onPressed: () => ref.read(counterProvider.notifier).increment(),
child: Text('Increment'),
),
],
);
}
Riverpod introduces the design philosophy of Reactive Programming. While it can be considered that the base is the relationship between ChangeNotifier and ListenableBuilder inherent to the Flutter framework, it is a more refined and generalized mechanism.
Immutable objects
Let's review object comparison in Dart. If you are already familiar with this, please feel free to skip this section. This part introduces the behavior of the following code and the reason behind it.
void main() {
final list1 = [1, 2, 3];
final list2 = list1;
list2.remove(0);
print(list1 == list2); // -> true
const list3 = [1, 2, 3];
final list4 = [...list3];
list4.remove(0);
print(list3 == list4); // -> false
}
Since list1 and list2 refer to the same object, changes to list2 are also reflected in list1. On the other hand, since list3 and list4 generate a new list, changes to list4 are not reflected in list3.
Next, let's try running the following code in DartPad.
void main() {
final list1 = ["Flutter"];
final list2 = ["Flutter"];
print(list1 == list2); // -> false
const list3 = ["Flutter"];
const list4 = ["Flutter"];
print(list3 == list4); // -> true
}
list1 and list2 are lists that hold the same "Flutter". In a simple comparison, they are treated as different objects. It is a bit confusing, but list3 and list4 return true because they were optimized using const.
You can compare list1 and list2 as intended by comparing them as follows:
import 'package:collection/collection.dart';
void main() {
final list1 = ["Flutter"];
final list2 = ["Flutter"];
print(ListEquality().equals(list1, list2));
const list3 = ["Flutter"];
const list4 = ["Flutter"];
print(list3 == list4);
}
The API being used is ListEquality from the collection package. Furthermore, by using DeepCollectionEquality, you can include whether the elements of the list are in the same order as a judgment condition. Whether ["Flutter", "Developer"] and ["Developer", "Flutter"] are judged as different lists or identical lists depends on the intent of the judgment. In most cases, using DeepCollectionEquality allows for comparisons that also take the order of the list elements into account.[3]
The issue of comparison is not just a problem for List or Map. It also occurs in the comparison of objects in Dart.
void main() {
final object1 = GoodClass("first");
final object2 = object1;
object2.goodString = "two";
print(object1 == object2); // -> true
print(object1.goodString); // -> two
print(object2.goodString); // -> two
}
class GoodClass {
GoodClass(
this.goodString,
);
String goodString;
}
In the example above, object1 and object2 refer to the same object. This example is an obvious one, but in complex or intricate code, you may accidentally update values.
The above problem can be said to occur because the object's values can be rewritten from the outside. Let's change it so it can be declared with const and provide the same String.
void main() {
final object1 = GoodClass("value");
final object2 = GoodClass("value");
print(object1 == object2); // -> false
print(object1.goodString); // -> value
print(object2.goodString); // -> value
}
class GoodClass {
const GoodClass(
this.goodString,
);
final String goodString;
}
By declaring the GoodClass instance as const, the value of goodString can no longer be changed. However, since the == of GoodClass has not been overridden, object1 and object2 are using the default comparison.
The default behavior for all Objects is to return true if and only if this object and other are the same object.
This problem can be fixed by overriding the == operator.
void main() {
final object1 = GoodClass("value");
final object2 = GoodClass("value");
print(object1 == object2); // -> true
print(object1.goodString); // -> value
print(object2.goodString); // -> value
}
class GoodClass {
const GoodClass(
this.goodString,
);
final String goodString;
@override
bool operator ==(Object other) {
return identical(this, other) ||
other is GoodClass && other.goodString == goodString;
}
}
Now we can determine whether GoodClass instances are identical.
In its documentation, Riverpod recommends using freezed, built_value, and equatable. These libraries make it easy to generate immutable objects and also write appropriate overrides for the == operator.
If immutable objects are not used, it becomes difficult for Riverpod to judge whether "the equals judgment of a given object is appropriate." It might be possible, or it might not. Riverpod does not offer any solution to this problem. Users must solve it at their own responsibility; in other words, they must use immutable objects.[4]
If business logic is being managed by Riverpod, for the reasons above, the main states will be implemented using immutable objects. As a result, Riverpod (partially) forces the application to use immutable objects.
Resource-heavy Programming (for improved productivity)
Flutter itself has aspects of this, but Riverpod is not concerned with object creation/destruction or suppressing the size of the objects themselves. Rather, it suggests creating many objects to keep the implementation simple and improve readability.
For example, Riverpod has an autoDispose feature. This is a mechanism for managing state tied to the Widget lifecycle. By using autoDispose, you can automatically create and destroy state. This makes it easy to manage state. For details, please refer to the following article.
One of the reasons why Flutter adopted Dart as its language is that Dart is a language that can handle short-lived objects efficiently.
Fast allocation
The Flutter framework uses a functional-style flow that depends heavily on the underlying memory allocator efficiently handling small, short-lived allocations. This style was developed in languages with this property and doesn't work efficiently in languages that lack this facility.
In that case, creating many short-lived objects when using Riverpod in Flutter is not a problem.[5] Because of these circumstances, when you use Riverpod, it becomes easier to concentrate on the written code itself. While this is generally called a style of resource-heavy programming, it can be said that its disadvantages are resolved by Dart's language characteristics.
At a fundamental level, declarative UI itself has aspects of resource-heavy programming. Riverpod is a mechanism that further improves productivity by combining logic description with resource-heavy programming.
DI (utilizing Implicit interfaces)
DI (Dependency Injection) is a technique for resolving dependencies between application components. By using DI, you can reduce coupling between components and write code that is easier to test. That is the general explanation, but for a fundamental explanation of DI, please refer to the video by kobakei.
As a representative example of DI, consider a UseCase that has multiple repositories.
@riverpod
LikeUseCase likeUseCase(Ref ref) {
return LikeUseCase(
repository: ref.watch(likeRepositoryProvider),
analyticsRepository: ref.watch(analyticsRepositoryProvider),
);
}
class LikeUseCase {
const LikeUseCase({
required this.articleRepository,
required this.analyticsRepository,
});
final ArticleRepository articleRepository;
final AnalyticsRepository analyticsRepository;
Future<void> like() async {
await articleRepository.like();
unawaited(analyticsRepository.sendEvent('like'));
}
Future<void> unlike() async {
await articleRepository.unlike();
unawaited(analyticsRepository.sendEvent('unlike'));
}
}
When writing tests for LikeUseCase or code that uses LikeUseCase, there is a need to inject mocks into the dependencies of LikeUseCase. What I would like to highlight here is that the mocks need to implement the interfaces of ArticleRepository or AnalyticsRepository.
Dart has a feature called Implicit interfaces. This is a mechanism where an interface for a class is prepared implicitly, even if you do not explicitly declare the interface that the class implements. Because of this mechanism, you do not need to separate the code for interfaces and implementations in Dart.
Usually, Mockito or Mocktail are used to create mocks. However, depending on how you do it, you can also create mocks by hand.
class MockArticleRepository implements ArticleRepository {
bool liked = false;
@override
Future<void> like() async {
liked = true;
}
@override
Future<void> unlike() async {
liked = false;
}
}
class MockAnalyticsRepository implements AnalyticsRepository {
final List<String> events = <String>[];
@override
Future<void> sendEvent(String event) async {
events.add(event);
}
}
After that, you just swap the Provider for the mock in your test code.
void main() {
test('LikeUseCase', () {
final mockArticleRepository = MockArticleRepository();
final mockAnalyticsRepository = MockAnalyticsRepository();
final container = createContainer(
overrides: [
likeRepositoryProvider.overrideWith(
(ref) => mockArticleRepository,
),
analyticsRepositoryProvider.overrideWith(
(ref) => mockAnalyticsRepository,
),
],
);
final likeUseCase = container.read(likeUseCaseProvider);
expect(likeUseCase.like(), completion(null));
expect(mockArticleRepository.liked, isTrue);
expect(mockAnalyticsRepository.events, contains('like'));
expect(likeUseCase.unlike(), completion(null));
expect(mockArticleRepository.liked, isFalse);
expect(mockAnalyticsRepository.events, contains('unlike'));
});
}
/// Cited from https://riverpod.dev/docs/essentials/testing
ProviderContainer createContainer({
ProviderContainer? parent,
List<Override> overrides = const [],
List<ProviderObserver>? observers,
}) {
final container = ProviderContainer(
parent: parent,
overrides: overrides,
observers: observers,
);
addTearDown(container.dispose);
return container;
}
As shown in the code, Riverpod provides DI functionality. By combining this with Dart's Implicit interfaces, you can describe test code relatively easily.
Summary
There may be some philosophies or paradigms that Riverpod introduces that you are not familiar with. However, Riverpod provides a mechanism that allows you to develop applications without needing that knowledge. Because various design philosophies are skillfully incorporated into Riverpod, users hardly need to pay any attention to them.
What is important here is that it is better to implement your application in the way Riverpod expects. By utilizing the features provided by Riverpod, you will be able to enjoy the benefits of these design philosophies.
I feel my lack of ability prevented me from summarizing this as well as I would like, but I hope this article is helpful.
-
Since they are heavily influenced by the era in which they were proposed, I wonder if they are strictly parallel entities. ↩︎
-
because they cannot reference
BuildContext↩︎ -
For the sake of explanation, I am using
ListEquality. ↩︎ -
I feel that this separation of responsibility is appropriate. ↩︎
-
There is such a thing as too much of anything, though. ↩︎
Discussion