<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kyaw Thet Wam on Medium]]></title>
        <description><![CDATA[Stories by Kyaw Thet Wam on Medium]]></description>
        <link>https://medium.com/@kyawthetwam?source=rss-59f0ebe208c1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vUx5Ptzcut4xUbqWX3QtDQ.jpeg</url>
            <title>Stories by Kyaw Thet Wam on Medium</title>
            <link>https://medium.com/@kyawthetwam?source=rss-59f0ebe208c1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 05:57:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kyawthetwam/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Flutter App Architecture : Inspiring Domain Driven Design]]></title>
            <link>https://blog.stackademic.com/flutter-app-architecture-inspiring-domain-driven-design-d681e5e7c0c6?source=rss-59f0ebe208c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/d681e5e7c0c6</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[app-architecture]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[riverpod]]></category>
            <dc:creator><![CDATA[Kyaw Thet Wam]]></dc:creator>
            <pubDate>Sun, 14 Jul 2024 14:11:31 GMT</pubDate>
            <atom:updated>2024-07-16T00:08:49.028Z</atom:updated>
            <content:encoded><![CDATA[<h3>Flutter App Architecture: Inspiring Domain-Driven Design</h3><p>The importance of a well-structured design in Flutter applications</p><p>∘ <a href="#657b">Introduction</a><br> ∘ <a href="#00fb">Presentation Layer</a><br> ∘ <a href="#60c5">Domain Layer</a><br> ∘ <a href="#ff00">Infrastructure Layer</a><br> ∘ <a href="#4b76">Testability</a><br> ∘ <a href="#3433">Conclusion</a></p><h4>Introduction</h4><p>Writing robust and maintainable Flutter applications demands more than just writing code — it requires a well-thought-out architecture. Without a clear architectural pattern, your codebase can quickly become confusing, presenting challenges for maintenance and testing. Among the various architectural paradigms like MVC, MVVM, and others, Domain-Driven Design (DDD) stands out as a powerful approach for structuring applications.</p><p>DDD focuses on organizing software around business domains instead of technical details, creating a clear and realistic architecture. This not only improves code maintainability but also aligns closely with business needs, promoting a collaborative development process. However, fully adopting DDD can be challenging due to its complexity and steep learning curve.</p><p>In this article, we explore how Flutter developers can leverage DDD-inspired approaches to achieve cleaner, more maintainable codebases. We’ll discuss the benefits of DDD, highlight its core principles, and demonstrate practical strategies for integrating DDD-inspired architecture into your Flutter projects. Let’s dive in!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8xrG0Vz61Rx3Uj1HifXR7A.png" /><figcaption>Credit to original owner.</figcaption></figure><p>In this article, we will demonstrate this architecture by implementing an authentication feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*7SoT8ICh1JNxmBq9L2ojuA.png" /></figure><h4>Presentation Layer</h4><p>The presentation layer is responsible for displaying data to the user and handling user interactions. It consists of two main components: Widgets and Providers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kOko60IS_A-C73hDLgFmIQ.png" /></figure><p><strong>Widgets:</strong></p><p>Widgets are the building blocks of the Flutter UI. They are responsible for rendering the visual elements of the application and responding to user input. Widgets in the presentation layer perform the following functions:</p><ul><li><strong>Displaying Data:</strong> Widgets display data provided by the Providers.</li><li><strong>State Changes:</strong> They listen for state changes from Providers and update the UI accordingly.</li><li><strong>User Interaction:</strong> Widgets handle user interactions, such as taps, swipes, and other gestures.</li></ul><p><strong>Providers:</strong></p><p>Providers serve as a bridge between the Widgets and the business logic of the application. They manage the state and notify the Widgets when the state changes. Providers in the presentation layer perform the following functions:</p><ul><li><strong>Observable State:</strong> Providers maintain an observable state that can be used by the Widgets.</li><li><strong>Notify Listeners:</strong> They notify the Widgets when the state changes, ensuring that the UI is always in sync with the data such as fetching data from the repositories, and exposing this data to the Widgets.</li></ul><p>In the following code, when the user clicks the login button, the signIn method of the AuthNotifier class is called. The SignInScreen listens for state changes from the authNotifierProvider. If you’re not familiar with Riverpod, please check out this <a href="https://medium.com/@kyawthetwam/riverpod-essentials-mastering-state-management-in-flutter-apps-879cfe68a4d7">article</a>.</p><pre><br>class SignInScreen extends ConsumerWidget {<br>  const SignInScreen({super.key});<br><br>  @override<br>  Widget build(BuildContext context, WidgetRef ref) {<br><br>  // Listening to state changes and taking actions based on the state.<br>    ref.listen(authNotifierProvider, (_, state) {<br>      state.maybeWhen(<br>        loading: () =&gt; LoadingOverlay.show(),<br>        data: (auth) {<br>          LoadingOverlay.hide();<br>        },<br>        error: (err, stack) {<br>          LoadingOverlay.hide();<br>          // show your error dialog.<br>        },<br>        orElse: () {},<br>      );<br>    });<br>    <br>   return Scaffold(<br>      body: Column(<br>         children: [<br>          // other widgets<br>          <br>          // call mutate method.<br>          EmailIconButton(<br>            text: &#39;LogIn&#39;,<br>            onPressed: () {<br>              if (_formKey.currentState!.validate()) {<br>               ref.read(authNotifierProvider.notifier).signIn(<br>               emailController.text,<br>               passwordController.text);<br>              }<br>            },<br>          ),<br>        ],<br>       ),                     <br>    );<br>  }<br>}</pre><p>GuardX is an extension method of guard (async value method) that automatically converts exceptions or errors into asyncError. The AuthNotifier class notifies state changes to its listeners within widgets.</p><pre>@Riverpod(keepAlive: true)<br>class AuthNotifier extends _$AuthNotifier {<br>  @override<br>  FutureOr&lt;Auth&gt; build() async {<br>    await Future.delayed(const Duration(seconds: 1));<br>    final user = await ref.watch(authRepositoryProvider).isSignIn();<br><br>    if (user == null) return const Auth.unauthenticated();<br><br>    return Authenticated(user: user);<br>  }<br><br>  Future&lt;void&gt; signIn(String email, String password) async {<br>    state = const AsyncValue.loading();<br><br>    state = await state.guardX(() async {<br>      final user =<br>          await ref.watch(authRepositoryProvider).signIn(email, password);<br>      if (user == null) return const Auth.unauthenticated();<br>      return Auth.authenticated(user: user);<br>    });<br>  }<br><br>  Future&lt;void&gt; signOut() async {<br>    state = const AsyncValue.loading();<br><br>    state = await state.guardX(() async {<br>      await ref.watch(authRepositoryProvider).signOut();<br>      return const Auth.unauthenticated();<br>    });<br>  }<br>}</pre><p>In summary, the presentation layer is crucial for ensuring a responsive and interactive user interface. Widgets render the UI and handle user interactions, while Providers manage the state and notify Widgets of any changes. This separation of concerns allows for a clean and maintainable codebase, making it easier to manage the UI and the underlying business logic.</p><h4>Domain Layer</h4><p>The domain layer is the core of the application, encapsulating the business logic and domain entities. It serves as the intermediary between the presentation layer and the data sources, ensuring that the business rules and logic are consistently applied.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LfdLURq2a8B_qaYC2AZ9Iw.png" /></figure><pre>part &#39;user.freezed.dart&#39;;<br><br>@freezed<br>abstract class User implements _$User {<br>  const factory User({<br>    @Default(&quot;&quot;) String id,<br>    @Default(&quot;&quot;) String name,<br>    @Default([]) List&lt;String&gt; permission,<br>  }) = _User;<br>}</pre><p>The domain layer consists of entities which represent the core business objects in the application. They encapsulate the key attributes and behaviors of the business domain. In the domain layer,</p><ul><li><strong>Encapsulate Business Logic:</strong> Entities contain business logic and rules that are critical to the application.</li><li><strong>Domain-Driven Design:</strong> Entities are designed based on the real-world business requirements, reflecting the structure and behavior of the domain.</li></ul><h4>Infrastructure Layer</h4><p>The infrastructure layer supports the application by providing the necessary data sources and external services. It interacts with external systems, such as APIs and local databases, and handles the raw data, transforming it into entities usable by the presentation layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bN9Vo4HZVK1k5VH8wT45dg.png" /></figure><p>The infrastructure layer consists of Repositories, Data Transfer Objects (DTOs), Remote Data Sources, and Local Data Sources.</p><p><strong>Data Transfer Objects (DTOs):</strong></p><p>DTOs are simple objects that carry data between processes. They are used to transfer data from the remote and local data sources to Entities in the domain layer. In the infrastructure layer, DTOs:</p><ul><li><strong>Data Transformation:</strong> Transform raw data from external sources into a format suitable for entities of the domain layer.</li><li><strong>Decoupling:</strong> Decouple the domain entities from the data source structures, ensuring that changes in the data sources do not directly affect the domain layer.</li><li><strong>Serialization/Deserialization:</strong> Handle the serialization and deserialization of data when communicating with external APIs and databases.</li></ul><pre><br>part &#39;user_dto.freezed.dart&#39;;<br>part &#39;user_dto.g.dart&#39;;<br><br>@freezed<br>abstract class UserDTO implements _$UserDTO {<br>  const UserDTO._();<br>  const factory UserDTO({<br>    @Default(&quot;&quot;) String id,<br>    @Default(&quot;&quot;) String name,<br>    @Default(PermissionDTO()) PermissionDTO permission,<br>  }) = _UserDTO;<br><br>  //from json and to json which is json serialization<br>  factory UserDTO.fromJson(Map&lt;String, dynamic&gt; json) =&gt;<br>      _$UserDTOFromJson(json);<br><br>// converting UserDTO object to User entity<br>  User toDomain() {<br>    return User(<br>      name: name,<br>      id: id,<br>      permission: permission.permissionList(),<br>    );<br>  }<br><br>//converting User entity to UserDTO object<br>  factory UserDTO.fromDomain(User _) {<br>    return UserDTO(<br>      name: _.name,<br>      id: _.id,<br>      permission: PermissionDTO.fromDomain(_.permission),<br>    );<br>  }<br>}</pre><p><strong>Remote Data Sources:</strong></p><p>Remote Data Sources are responsible for interacting with external services, such as APIs, to fetch and send data. They handle the communication with the outside world and ensure that the application can access remote data. In the infrastructure layer, remote data sources:</p><ul><li><strong>API Communication:</strong> Manage the communication with external APIs, including sending requests and handling responses.</li><li><strong>Data Fetching:</strong> Fetch raw data from remote services and pass it to the DTOs for transformation.</li></ul><pre><br>@Riverpod(keepAlive: true)<br>AuthRemoteDataSource authRemoteDataSource(AuthRemoteDataSourceRef ref) {<br>  return AuthRemoteDataSource(<br>    firebaseAuth: ref.watch(firebaseAuthProvider),<br>    firebaseFirestore: ref.watch(firebaseFirestoreProvider),<br>  );<br>}<br><br>class AuthRemoteDataSource {<br>  AuthRemoteDataSource({<br>    required this.firebaseAuth,<br>    required this.firebaseFirestore,<br>  });<br><br>  final FirebaseAuth firebaseAuth;<br>  final FirebaseFirestore firebaseFirestore;<br><br>  Future&lt;UserDTO?&gt; signIn(String email, String password) async {<br>    final userCredential = await firebaseAuth.signInWithEmailAndPassword(<br>        email: email, password: password);<br><br>    final userDto = await getUserData(userCredential.user!.uid);<br><br>    if (userDto == null) {<br>      await userCredential.user!.delete();<br>    }<br><br>    return userDto;<br>  }<br><br>  Future&lt;void&gt; signOut() async =&gt; await firebaseAuth.signOut();<br><br>  Future&lt;UserDTO?&gt; getUserData(String id) async {<br>    final userDoc = await firebaseFirestore.collection(&quot;users&quot;).doc(id).get();<br><br>    if (!userDoc.exists) return null;<br><br>    return UserDTO.fromJson(userDoc.data()!);<br>  }<br>}</pre><p><strong>Local Data Sources:</strong></p><p>Local Data Sources are responsible for accessing data stored locally on the device, such as in a local database. They provide a way to store and retrieve data without relying on network connectivity. In the infrastructure layer, local data sources:</p><ul><li><strong>Database Operations:</strong> Perform CRUD (Create, Read, Update, Delete) operations on the local database ensuring that the application can function offline by storing necessary data locally.</li><li><strong>Data Persistence:</strong> Maintain data persistence across application sessions, allowing the application to remember and reuse data.</li></ul><pre>@Riverpod(keepAlive: true)<br>AuthLocalDataSource authLocalDataSource(AuthLocalDataSourceRef ref) {<br>  return AuthLocalDataSource(<br>      flutterSecureStorage: ref.watch(secureStorageProvider));<br>}<br><br>class AuthLocalDataSource {<br>  AuthLocalDataSource({required this.flutterSecureStorage});<br><br>  final FlutterSecureStorage flutterSecureStorage;<br><br>  Future&lt;void&gt; signOut() async =&gt;<br>      await flutterSecureStorage.delete(key: &quot;user&quot;);<br><br>  Future&lt;void&gt; saveUserData(String userData) async =&gt;<br>      await flutterSecureStorage.write(key: &#39;user&#39;, value: userData);<br><br>  Future&lt;UserDTO?&gt; getUserData() async {<br>    final userString = await flutterSecureStorage.read(key: &#39;user&#39;);<br><br>    if (userString == null) return Future(() =&gt; null);<br><br>    return UserDTO.fromJson(jsonDecode(userString));<br>  }<br>}</pre><p><strong>Repositories:</strong></p><p>Repositories abstract the complexities of data retrieval and manipulation, providing a clean and consistent API for the presentation layer to interact with. The repositories handle data from both remote and local data sources, ensuring that the domain entities have access to the necessary data without being tightly coupled to the underlying data storage mechanisms.</p><ul><li><strong>Abstraction:</strong> They abstract the details of data sources, providing a clean API for the presentation layer to interact with.</li></ul><pre><br>@Riverpod(keepAlive: true)<br>AuthRepository authRepository(AuthRepositoryRef ref) {<br><br>// As shown in the diagram, the remote data source and local data source <br>// are injected into the repository<br><br>  return AuthRepository(<br>    authRemoteDataSource: ref.watch(authRemoteDataSourceProvider),<br>    authLocalDataSource: ref.watch(authLocalDataSourceProvider),<br>  );<br>}<br><br>class AuthRepository {<br>  AuthRepository({<br>    required this.authRemoteDataSource,<br>    required this.authLocalDataSource,<br>  });<br><br>  final AuthRemoteDataSource authRemoteDataSource;<br>  final AuthLocalDataSource authLocalDataSource;<br><br>  Future&lt;User?&gt; isSignIn() async {<br>    final userDto = await authLocalDataSource.getUserData();<br><br>    if (userDto == null) return null;<br><br>    return userDto.toDomain();<br>  }<br><br>  Future&lt;User?&gt; signIn(String email, String password) async {<br>    final userDto = await authRemoteDataSource.signIn(email, password);<br>    if (userDto == null) return null;<br><br>    final user = userDto.toDomain();<br><br>    await authLocalDataSource.saveUserData(jsonEncode(userDto.toJson()));<br><br>    return user;<br>  }<br><br>  Future&lt;void&gt; signOut() async {<br>    await Future.wait([<br>      authRemoteDataSource.signOut(),<br>      authLocalDataSource.signOut(),<br>    ]);<br>  }<br>}</pre><p>In summary, the infrastructure layer provides the essential support for data management and external communication in the application. DTOs facilitate data transfer between the presentation layer (encapsulating entities) and data sources, remote data sources handle interactions with external APIs, and local data sources manage data stored on the device.</p><h4>Testability</h4><p>It is designed to enhance testability, ensuring that different parts of the application can be tested independently and thoroughly. This modular design promotes clean separation of concerns, making it easier to write unit tests, integration tests, and end-to-end tests. We will focus solely on unit tests in this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*PpR3itqDMk4x_urWY5DQXg.png" /></figure><p><strong>Presentation Layer Testability:</strong></p><p><strong>Widgets:</strong></p><pre>void main() {<br>  group(&#39;SignInScreen&#39;, () {<br>    late AuthNotifier mockAuthNotifier;<br><br>    setUp(() {<br>      mockAuthNotifier = MockAuthNotifier();<br>    });<br><br>    testWidgets(&#39;renders SignInScreen&#39;, (tester) async {<br>      await tester.pumpWidget(<br>        ProviderScope(<br>          overrides: [<br>            authNotifierProvider.overrideWith(() =&gt; mockAuthNotifier),<br>          ],<br>          child: const MaterialApp(<br>            home: SignInScreen(),<br>          ),<br>        ),<br>      );<br>      // Verify that the UI elements are rendered correctly<br>      expect(find.text(&#39;some title&#39;), findsOneWidget);<br>      expect(find.byType(SignInForm), findsOneWidget);<br>      expect(find.byType(LogoImage), findsOneWidget);<br>    });<br>  });<br>}</pre><p><strong>Providers:</strong></p><ul><li><strong>Mocking Dependencies:</strong> Dependencies such as data sources or repositories can be mocked, allowing providers to be tested in isolation.</li></ul><pre><br>class MockAuthRepository extends Mock implements AuthRepository {}<br><br>void main() {<br>  const tUser = User(id: &#39;1&#39;, name: &#39;John Doe&#39;);<br>  const tUserDto = UserDTO(id: &#39;1&#39;, name: &#39;John Doe&#39;);<br>  final tException = Exception(&#39;test_exception&#39;);<br><br>  const loadingState = AsyncLoading&lt;Auth&gt;();<br>  const unauthenticated = AsyncData&lt;Auth&gt;(Auth.unauthenticated());<br>  const authenticated = AsyncData&lt;Auth&gt;(Auth.authenticated(user: tUser));<br>  late MockAuthRepository mockAuthRepository;<br>  late MockAuthLocalDataSource mockAuthLocalDataSource;<br><br>  T errorState&lt;T&gt;() =&gt; any(that: isA&lt;AsyncError&lt;Auth&gt;&gt;());<br><br>  setUp(() {<br>    registerFallbackValue(const AsyncLoading&lt;Auth&gt;());<br>    mockAuthRepository = MockAuthRepository();<br>    mockAuthLocalDataSource = MockAuthLocalDataSource();<br>  });<br><br>  group(&#39;sign in&#39;, () {<br>    test(&#39;success&#39;, () async {<br>      when(() =&gt; mockAuthRepository.isSignIn()).thenAnswer((_) async =&gt; null);<br><br>      when(() =&gt; mockAuthRepository.signIn(&quot;email&quot;, &quot;password&quot;))<br>          .thenAnswer((_) async =&gt; tUser);<br><br>      when(() =&gt; mockAuthLocalDataSource<br>              .saveUserData(jsonEncode(tUserDto.toJson())))<br>          .thenAnswer((_) async =&gt; Future.value());<br><br>      final container = createContainer(overrides: [<br>        authRepositoryProvider.overrideWithValue(mockAuthRepository),<br>        authLocalDataSourceProvider.overrideWithValue(mockAuthLocalDataSource),<br>      ]);<br><br>      final listener = setUpListener(container, authNotifierProvider);<br><br>      verifyOnly(listener, () =&gt; listener(null, loadingState));<br><br>      final authNotifier = container.read(authNotifierProvider.notifier);<br><br>      final call = authNotifier.signIn(&quot;email&quot;, &quot;password&quot;);<br><br>      await expectLater(call, completes);<br><br>      verifyInOrder([<br>        () =&gt; listener(loadingState, unauthenticated),<br>        () =&gt; listener(unauthenticated, authenticated),<br>      ]);<br><br>      verifyNoMoreInteractions(listener);<br>    });<br><br>    test(&#39;failure&#39;, () async {<br>      when(() =&gt; mockAuthRepository.isSignIn()).thenAnswer((_) async =&gt; null);<br><br>      when(() =&gt; mockAuthRepository.signIn(&quot;email&quot;, &quot;password&quot;))<br>          .thenThrow(tException);<br><br>      when(() =&gt; mockAuthLocalDataSource<br>              .saveUserData(jsonEncode(tUserDto.toJson())))<br>          .thenAnswer((_) async =&gt; Future.value());<br><br>      final container = createContainer(overrides: [<br>        authRepositoryProvider.overrideWithValue(mockAuthRepository),<br>        authLocalDataSourceProvider.overrideWithValue(mockAuthLocalDataSource),<br>      ]);<br><br>      final listener = setUpListener(container, authNotifierProvider);<br><br>      verifyOnly(listener, () =&gt; listener(null, loadingState));<br><br>      final authNotifier = container.read(authNotifierProvider.notifier);<br><br>      final call = authNotifier.signIn(&quot;email&quot;, &quot;password&quot;);<br><br>      await expectLater(call, completes);<br><br>      verifyInOrder([<br>        () =&gt; listener(loadingState, unauthenticated),<br>        () =&gt; listener(unauthenticated, errorState()),<br>      ]);<br><br>      verifyNoMoreInteractions(listener);<br>    });<br>  });<br><br>}</pre><p><strong>Domain Layer Testability:</strong></p><p>Entities encapsulate business logic and rules. They can be unit tested by creating different instances and verifying their behavior according to the business rules.</p><pre>const constUser = User(<br>  id: &quot;1&quot;,<br>  name: &quot;John&quot;,<br>  permission: [&quot;read&quot;, &quot;write&quot;],<br>);<br><br>void main() {<br>  group(&#39;User&#39;, () {<br>    test(&#39;should create a User instance with default values&#39;, () {<br>      const user = User();<br><br>      expect(user.id, &quot;&quot;);<br>      expect(user.name, &quot;&quot;);<br>      expect(user.permission, moduleList);<br>    });<br><br>    test(&#39;should create a User instance with specified values&#39;, () {<br>      expect(constUser.id, &quot;1&quot;);<br>      expect(constUser.name, &quot;John&quot;);<br>      expect(constUser.permission, [&quot;read&quot;, &quot;write&quot;]);<br>    });<br><br>    test(&#39;should override specific values in a copy of User instance&#39;, () {<br>      const originalUser = constUser;<br><br>      final updatedUser = originalUser.copyWith(<br>        name: &quot;Jane&quot;,<br>      );<br><br>      expect(updatedUser.id, &quot;1&quot;); // id should remain unchanged<br>      expect(updatedUser.name, &quot;Jane&quot;); // name should be updated<br>      expect(updatedUser.permission,<br>          [&quot;read&quot;, &quot;write&quot;]); // permission should remain unchanged<br>    });<br><br>    test(&#39;Equality Test&#39;, () {<br>      const user1 = constUser;<br>      const user2 = constUser;<br><br>      const user3 = User(<br>          id: &#39;2&#39;, name: &#39;Jane&#39;, permission: [&#39;read&#39;]);<br><br>      expect(user1, equals(user2)); // user1 should be equal to user2<br>      expect(user1 == user3, isFalse); // user1 should not be equal to user3<br>    });<br>  });<br>}</pre><p><strong>Infrastructure Layer Testability:</strong></p><p><strong>DTOs:</strong></p><ul><li><strong>Serialization/Deserialization:</strong> DTOs can be tested to ensure that they correctly serialize and deserialize data between the domain layer and data sources.</li></ul><pre><br>void main() {<br>  late UserDTO userDto;<br><br>  setUp(() {<br>    userDto = const UserDTO(<br>      id: &quot;user123&quot;,<br>      name: &quot;John Doe&quot;,<br>    );<br>  });<br><br>  group(&#39;UserDTO&#39;, () {<br><br>    test(&#39;should convert UserDTO to JSON and vice versa&#39;, () {<br>      // Convert UserDTO to JSON<br>      final jsonMap = userDto.toJson();<br><br>      // Verify the generated JSON<br>      expect(jsonMap[&#39;id&#39;], &quot;user123&quot;);<br>      expect(jsonMap[&#39;name&#39;], &quot;John Doe&quot;);<br><br><br>      // Convert JSON back to UserDTO<br>      final fromJsonUserDto = UserDTO.fromJson(jsonMap);<br><br>      // Verify the conversion<br>      expect(fromJsonUserDto.id, &quot;user123&quot;);<br>      expect(fromJsonUserDto.name, &quot;John Doe&quot;);<br><br>    });<br>  });<br>}</pre><p><strong>Remote Data Sources:</strong></p><ul><li><strong>API Mocking:</strong> Remote data sources can be tested by mocking API responses. This allows testing the communication logic with external services without making actual network calls.</li></ul><pre><br>void main() {<br>  group(&#39;FirestoreService&#39;, () {<br>    late FakeFirebaseFirestore fakeFirebaseFirestore;<br>    late MockFirebaseAuth mockFirebaseAuth;<br>    const String collectionPath = &#39;collectionPath&#39;;<br><br>    setUp(() {<br>      fakeFirebaseFirestore = FakeFirebaseFirestore();<br>      mockFirebaseAuth = MockFirebaseAuth();<br>    });<br>    ProviderContainer setUpContainer() {<br>      return createContainer(overrides: [<br>        firebaseFirestoreProvider.overrideWithValue(fakeFirebaseFirestore),<br>        firebaseAuthProvider.overrideWithValue(mockFirebaseAuth)<br>      ]);<br>    }<br><br>    group(&#39;Sign In&#39;, () {<br>      test(&#39;signInWithEmailAndPassword returns user on success&#39;, () async {<br>        // Arrange<br>        const email = &#39;test@example.com&#39;;<br>        const password = &#39;password123&#39;;<br>        final mockedUserCredential = MockUserCredential();<br>        final mockedUser = MockUser();<br>        when(() =&gt; mockFirebaseAuth.signInWithEmailAndPassword(<br>            email: email,<br>            password: password)).thenAnswer((_) async =&gt; mockedUserCredential);<br>        when(() =&gt; mockedUserCredential.user).thenReturn(mockedUser);<br><br>        // Act<br><br>        final container = setUpContainer();<br><br>        final authService = container.read(firebaseAuthProvider);<br><br>        final result = await authService.signInWithEmailAndPassword(<br>            email: email, password: password);<br><br>        // Assert<br>        expect(result, equals(mockedUserCredential));<br><br>        verifyOnly(<br>            mockFirebaseAuth,<br>            () =&gt; mockFirebaseAuth.signInWithEmailAndPassword(<br>                email: email, password: password));<br>      });<br>    });<br>}</pre><p><strong>Local Data Sources:</strong></p><ul><li><strong>Database Mocking:</strong> Local data sources can be tested using in-memory databases or database mocking libraries.</li></ul><pre>class MockSecureStorage extends Mock implements FlutterSecureStorage {}<br><br>void main() {<br>  late MockSecureStorage mockSecureStorage;<br>  const userData = &#39;{&quot;id&quot;: &quot;1&quot;, &quot;name&quot;: &quot;John Doe&quot;}&#39;;<br><br>  setUp(() {<br>    mockSecureStorage = MockSecureStorage();<br>  });<br><br>  ProviderContainer setUpContainer() {<br>    return createContainer(overrides: [<br>      secureStorageProvider.overrideWithValue(mockSecureStorage)<br>    ]);<br>  }<br><br>  group(&#39;saveUserData&#39;, () {<br>    test(&#39;should write user data to secure storage&#39;, () async {<br>      when(() =&gt; mockSecureStorage.write(key: &#39;user&#39;, value: userData))<br>          .thenAnswer((_) async {});<br><br>      final container = setUpContainer();<br><br>      final authLocalDataSource = container.read(authLocalDataSourceProvider);<br><br>      final result = authLocalDataSource.saveUserData(userData);<br><br>      expectLater(result, completes);<br><br>      verifyOnly(mockSecureStorage,<br>          () =&gt; mockSecureStorage.write(key: &#39;user&#39;, value: userData));<br><br>      verifyNoMoreInteractions(mockSecureStorage);<br>    });<br>  });<br><br>  group(&#39;getUserData&#39;, () {<br>    test(&#39;should return UserDTO when user data exists in secure storage&#39;,<br>        () async {<br>      when(() =&gt; mockSecureStorage.read(key: &#39;user&#39;))<br>          .thenAnswer((_) async =&gt; userData);<br><br>      final container = setUpContainer();<br><br>      final authLocalDataSource = container.read(authLocalDataSourceProvider);<br><br>      final result = await authLocalDataSource.getUserData();<br><br>      expect(result, isNotNull);<br>      expect(result!.id, &#39;1&#39;);<br>      expect(result.name, &#39;John Doe&#39;);<br><br>      verifyOnly(mockSecureStorage, () =&gt; mockSecureStorage.read(key: &#39;user&#39;));<br>      verifyNoMoreInteractions(mockSecureStorage);<br>    });<br><br>    test(&#39;should return null when user data does not exist in secure storage&#39;,<br>        () async {<br>      when(() =&gt; mockSecureStorage.read(key: &#39;user&#39;))<br>          .thenAnswer((_) async =&gt; null);<br><br>      final container = setUpContainer();<br><br>      final authLocalDataSource = container.read(authLocalDataSourceProvider);<br><br>      final result = await authLocalDataSource.getUserData();<br><br>      expect(result, isNull);<br><br>      verifyOnly(mockSecureStorage, () =&gt; mockSecureStorage.read(key: &#39;user&#39;));<br>      verifyNoMoreInteractions(mockSecureStorage);<br>    });<br>  });<br>}</pre><p><strong>Repositories:</strong></p><ul><li><strong>Mock Data Sources:</strong> Repositories can be tested by mocking the remote and local data sources. This ensures that the data access logic works correctly without needing actual data sources.</li></ul><pre>class MockAuthRemoteDataSource extends Mock implements AuthRemoteDataSource {}<br><br>class MockAuthLocalDataSource extends Mock implements AuthLocalDataSource {}<br><br>void main() {<br>  late MockAuthRemoteDataSource mockAuthRemoteDataSource;<br>  late MockAuthLocalDataSource mockAuthLocalDataSource;<br><br>  setUp(() {<br>    mockAuthRemoteDataSource = MockAuthRemoteDataSource();<br>    mockAuthLocalDataSource = MockAuthLocalDataSource();<br>  });<br><br>  ProviderContainer setUpContainer() {<br>    return createContainer(<br>      overrides: [<br>        authRemoteDataSourceProvider<br>            .overrideWithValue(mockAuthRemoteDataSource),<br>        authLocalDataSourceProvider.overrideWithValue(mockAuthLocalDataSource),<br>      ],<br>    );<br>  }<br><br>  const tUserDto = UserDTO(id: &#39;1&#39;, name: &#39;John Doe&#39;);<br><br>  final tUser = tUserDto.toDomain();<br><br>  final tException = Exception(&#39;test_exception&#39;);<br><br>  group(&#39;isSignIn&#39;, () {<br>    test(&#39;isSignIn - returns null when local data source is null&#39;, () async {<br>      when(() =&gt; mockAuthLocalDataSource.getUserData())<br>          .thenAnswer((_) async =&gt; null);<br><br>      final container = setUpContainer();<br><br>      final authRepo = container.read(authRepositoryProvider);<br><br>      final result = await authRepo.isSignIn();<br><br>      expect(result, isNull);<br><br>      verifyOnly(<br>          mockAuthLocalDataSource, () =&gt; mockAuthLocalDataSource.getUserData());<br>    });<br><br>    test(&#39;isSignIn - returns User when local data source is not null&#39;,<br>        () async {<br>      when(() =&gt; mockAuthLocalDataSource.getUserData())<br>          .thenAnswer((_) async =&gt; tUserDto);<br><br>      final container = setUpContainer();<br><br>      final authRepo = container.read(authRepositoryProvider);<br><br>      final result = await authRepo.isSignIn();<br><br>      expect(result, tUser);<br><br>      verifyOnly(<br>          mockAuthLocalDataSource, () =&gt; mockAuthLocalDataSource.getUserData());<br>    });<br><br>    test(&#39;signIn - returns null when remote data source returns null&#39;,<br>        () async {<br>      when(() =&gt; mockAuthRemoteDataSource.signIn(&#39;email&#39;, &#39;password&#39;))<br>          .thenAnswer((_) async =&gt; null);<br><br>      final container = setUpContainer();<br><br>      final authRepo = container.read(authRepositoryProvider);<br><br>      final result = await authRepo.signIn(&#39;email&#39;, &#39;password&#39;);<br><br>      expect(result, isNull);<br><br>      verifyOnly(mockAuthRemoteDataSource,<br>          () =&gt; mockAuthRemoteDataSource.signIn(&#39;email&#39;, &#39;password&#39;));<br>    });<br>  });<br>  group(<br>    &#39;signIn&#39;,<br>    () {<br>      test(<br>        &#39;should return remote data &#39;<br>        &#39;when the call to remote data source is successful&#39;,<br>        () async {<br>          // GIVEN<br>          when(() =&gt; mockAuthRemoteDataSource.signIn(&quot;email&quot;, &quot;password&quot;))<br>              .thenAnswer((_) async =&gt; tUserDto);<br><br>          when(() =&gt; mockAuthLocalDataSource<br>                  .saveUserData(jsonEncode(tUserDto.toJson())))<br>              .thenAnswer((_) async =&gt; Future.value());<br><br>          final container = setUpContainer();<br><br>          // WHEN<br>          final authRepo = container.read(authRepositoryProvider);<br>          final result = await authRepo.signIn(&quot;email&quot;, &quot;password&quot;);<br><br>          expect(result, tUser);<br><br>          // THEN<br>          verifyOnly(<br>            mockAuthRemoteDataSource,<br>            () =&gt; mockAuthRemoteDataSource.signIn(&quot;email&quot;, &quot;password&quot;),<br>          );<br>        },<br>      );<br><br>      test(<br>        &#39;should throw same Exception &#39;<br>        &#39;when the call to remote data source is unsuccessful&#39;,<br>        () async {<br>          // GIVEN<br>          when(() =&gt; mockAuthRemoteDataSource.signIn(&quot;email&quot;, &quot;password&quot;))<br>              .thenThrow(tException);<br><br>          final container = setUpContainer();<br><br>          // WHEN<br>          final authRepo = container.read(authRepositoryProvider);<br>          final call = authRepo.signIn(&quot;email&quot;, &quot;password&quot;);<br><br>          // THEN<br>          await expectLater(call, throwsA(tException));<br>          verifyOnly(<br>            mockAuthRemoteDataSource,<br>            () =&gt; mockAuthRemoteDataSource.signIn(&quot;email&quot;, &quot;password&quot;),<br>          );<br>        },<br>      );<br><br>      test(&#39;signOut - calls signOut on both remote and local data sources&#39;,<br>          () async {<br>        // GIVEN<br>        when(() =&gt; mockAuthRemoteDataSource.signOut()).thenAnswer((_) async {});<br>        when(() =&gt; mockAuthLocalDataSource.signOut()).thenAnswer((_) async {});<br><br>        final container = setUpContainer();<br><br>        // WHEN<br>        final authRepo = container.read(authRepositoryProvider);<br>        final call = authRepo.signOut();<br><br>        // THEN<br>        await expectLater(call, completes);<br>        verifyOnly(<br>            mockAuthRemoteDataSource, () =&gt; mockAuthRemoteDataSource.signOut());<br>        verifyOnly(<br>            mockAuthLocalDataSource, () =&gt; mockAuthLocalDataSource.signOut());<br>      });<br>    },<br>  );<br>}</pre><h4>Conclusion</h4><p>While fully implementing DDD can be complex, incorporating its principles provides a solid foundation for building robust applications. By structuring the codebase into well-defined layers and focusing on testability, developers can create applications that are not only functional but also scalable and easy to maintain.</p><p>Embracing this architectural approach ensures that your Flutter applications remain clean, efficient, and ready to evolve with changing business needs.</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d681e5e7c0c6" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/flutter-app-architecture-inspiring-domain-driven-design-d681e5e7c0c6">Flutter App Architecture : Inspiring Domain Driven Design</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Riverpod Essentials: Mastering State Management in Flutter Apps]]></title>
            <link>https://medium.com/@kyawthetwam/riverpod-essentials-mastering-state-management-in-flutter-apps-879cfe68a4d7?source=rss-59f0ebe208c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/879cfe68a4d7</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[riverpod]]></category>
            <category><![CDATA[app-development]]></category>
            <dc:creator><![CDATA[Kyaw Thet Wam]]></dc:creator>
            <pubDate>Fri, 24 May 2024 04:45:46 GMT</pubDate>
            <atom:updated>2024-05-24T04:45:46.000Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Reactive Caching and Data-binding Framework</h4><p>· <a href="#d7bd">Introduction</a><br>· <a href="#06f2">What is Riverpod?</a><br>· <a href="#7e7d">Why Riverpod?</a><br>· <a href="#f731">Installing the Package</a><br>· <a href="#4c87">ProviderScope</a><br>· <a href="#9f8f">Defining a Provider</a><br>· <a href="#53c4">Consuming a Provider</a><br>· <a href="#3e5a">What is WidgetRef?</a><br>· <a href="#ae08">Exploring Different Types of Providers</a><br>· <a href="#c929">Additional Riverpod Features</a><br> ∘ <a href="#8479">Provider Lifecycles</a><br> ∘ <a href="#ebaa">Destruction of a provider</a><br> ∘ <a href="#c5b9">Debouncing and Cancelling network requests</a><br> ∘ <a href="#a11d">Scoping Providers</a><br> ∘ <a href="#1eb5">Filtering widget/provider rebuild using “select” and “selectAsync” .</a><br>· <a href="#7502">Conclusion</a><br>· <a href="#8c91">References</a></p><h3>Introduction</h3><p>State management is crucial in Flutter, ensuring the app’s UI reacts correctly to user interactions and data changes. In Flutter, state refers to the data affecting the UI at any given moment. This includes both ephemeral state (local to a single widget) and app state (shared across the app).</p><p>Managing state efficiently is essential for maintaining a responsive and interactive UI. It improves code organization, scalability, and reusability.</p><p>Choosing the right solution depends on app complexity and specific needs. For simple apps, <strong>setState </strong>or <strong>InheritedWidget </strong>may be sufficient. For more complex needs, Provider, Riverpod, or Bloc (which uses Provider mechanism internally) are more appropriate.</p><p>In this article, we will focus on Riverpod, exploring its features, benefits, and practical examples to help you implement effective state management in your Flutter applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*m6wPdUK2w1MFrQwKosDayg.png" /><figcaption>riverpod.dev</figcaption></figure><h3>What is Riverpod?</h3><p>Riverpod, an anagram of <a href="https://pub.dev/packages/provider">Provider</a>, is a reactive caching framework for Flutter and Dart and a comprehensive rewrite of the Provider package, designed to introduce significant improvements and new capabilities that were previously unattainable. It simplifies application logic by leveraging declarative and reactive programming paradigms. Riverpod efficiently handles network requests with built-in error handling and caching mechanisms, and it automatically re-fetches data when needed.</p><h3>Why Riverpod?</h3><p>The Riverpod package, as the successor of Provider, addresses several limitations of its predecessor:</p><p><strong>Single Type Limitation:</strong></p><p>Provider, being an InheritedWidget wrapper, can only obtain one of two different providers using the same type, due to the constraints of the InheritedWidget API. <a href="https://pub.dev/packages/provider#can-i-obtain-two-different-providers-using-the-same-type">Details</a>.</p><p><strong>Single Value Emission:</strong></p><p>Providers emit only one value at a time, which means users cannot immediately see existing data while new data is being loaded. This impacts UI transitions, making them less smooth, and increases perceived waiting times.</p><p><strong>Combining Providers:</strong></p><ul><li>Manual Dependency Management: Managing dependencies manually when multiple providers depend on each other is complex and error-prone.</li><li>Verbose and Redundant Code: Combining multiple providers often results in boilerplate code, making the codebase verbose and harder to maintain.</li><li>Initialization Order Issues: Ensuring the correct initialization order of providers is tricky and can lead to runtime errors if a provider is used before it’s ready.</li><li>Difficulty in Debugging: Debugging becomes challenging with multiple interdependent providers, as identifying the root cause requires tracing through numerous providers and their interactions.</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftenor.com%2Fembed%2F7272048&amp;display_name=Tenor&amp;url=https%3A%2F%2Ftenor.com%2Fview%2Fcomputer-rage-gif-7272048&amp;image=https%3A%2F%2Fmedia.tenor.com%2FfXv2V5FrTQ0AAAAF%2Fcomputer-rage.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=tenor" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/17225135734c4865b0b3b172ecf1d9c9/href">https://medium.com/media/17225135734c4865b0b3b172ecf1d9c9/href</a></iframe><p><strong>Lack of Safety:</strong></p><p>Provider relies on the widget tree, which can lead to ProviderNotFoundException errors. This dependency on the widget tree is a fundamental design flaw that affects its reliability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*HmnuSUuFQ58JoPiiJUVK_w.png" /><figcaption><a href="https://codewithandrea.com/"><strong>CODE WITH ANDREA</strong></a></figcaption></figure><p><strong>State Disposal Difficulty:</strong></p><p>Provider, as a wrapper around InheritedWidget, inherits its <a href="https://github.com/flutter/flutter/issues/106549">limitations</a>, such as the inability to dispose of state when no longer used, leading to memory leaks. Riverpod addresses this with intuitive APIs like autodispose and keepAlive, which support flexible and creative caching strategies.</p><p><strong>Triggering Side Effects:</strong></p><p>InheritedWidget, used by Provider for state management, lacks an onChange callback to notify value changes. This makes it difficult to trigger side effects (e.g., showing a snackbar) directly, complicating the code and reducing state management efficiency.</p><p>Riverpod overcomes these limitations with a more robust and user-friendly API, improving state management and overall app performance.</p><h3>Installing the Package</h3><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>  flutter_riverpod: ^2.5.1<br>  riverpod_annotation: ^2.3.5<br><br>dev_dependencies:<br>  build_runner:<br>  custom_lint:<br>  riverpod_generator: ^2.4.2<br>  riverpod_lint: ^2.3.12</pre><p><strong>riverpod_annotation</strong>: is a side package for riverpod_generator, exposing annotations</p><p><strong>custom_lint: </strong>serves to enhance code quality and consistency by allowing developers to define their own linting rules.</p><p><strong>riverpod_generator: </strong>is a side package for Riverpod, meant to offer a different syntax for defining “providers” by relying on code generation.</p><p><strong>riverpod_lint: </strong>Its primary purpose is to enforce best practices and guidelines specific to Riverpod usage.</p><h3>ProviderScope</h3><p>To enable widgets to read providers, the entire application needs to be wrapped in a ProviderScope widget. This ensures that the state of all providers is properly stored and managed.</p><pre>void main() async {<br>  runApp(const ProviderScope(child: AppWidget()));<br>}</pre><h3>Defining a Provider</h3><p>When defining providers via code generation, you can choose between annotated functions or classes. Class-based providers offer the advantage of including public methods for external state modification, enabling side-effects. Functional providers, essentially shorthand for class-based ones with just a build method, lack this flexibility for UI modification.</p><pre>// Functional (Can’t perform side-effects using public methods)<br>@riverpod<br>String helloWorld(HelloWorldRef ref) {<br>  return &#39;Hello world&#39;;<br>}<br><br>// Class-Based (Can perform side-effects using public methods)<br>@riverpod<br>class Example extends _$Example {<br>  @override<br>  String build() {<br>    return &#39;foo&#39;;<br>  }<br><br>  // Add methods to mutate the state<br>}</pre><h3>Consuming a Provider</h3><p>When accessing a provider’s value, we utilize widgets like Consumer, ConsumerWidget, or ConsumerStatefulWidget from the Riverpod package. These widgets enable us to observe changes in one or more providers and update relevant parts of our UI accordingly. They handle subscription management to the provider(s) automatically, triggering the build method whenever there’s a data change.<br>Why do we need ConsumerWidget instead of StatelessWidget or StatefulWidget? See the <a href="https://github.com/flutter/flutter/issues/106549">answer</a>.</p><pre>// Extend ConsumerWidget instead of StatelessWidget, which is exposed by Riverpod<br>class MyApp extends ConsumerWidget {<br>  @override<br>  Widget build(BuildContext context, WidgetRef ref) {<br>    final String value = ref.watch(helloWorldProvider);<br><br>    return MaterialApp(<br>      home: Scaffold(<br>        appBar: AppBar(title: const Text(&#39;Example&#39;)),<br>        body: Center(<br>          child: Text(value),<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><h3>What is WidgetRef?</h3><p>An object that allows widgets to interact with providers,<strong> be it from a widget or another provider. </strong>We can use ref to interact with providers in several ways:</p><ol><li>Obtaining the value and listening to changes: Use <strong>ref.watch</strong> to obtain the value of a provider and <strong>automatically rebuild the widget or provider when the value changes.</strong></li><li>Adding a listener: Use <strong>ref.listen</strong> to add a listener to a provider, allowing you to execute actions (like navigating to a new page or showing a modal) whenever the provider&#39;s value changes.</li><li>Obtaining the value without listening to changes: Use <strong>ref.read</strong> to get the current value of a provider without subscribing to updates, useful for events like &quot;on click.&quot;</li></ol><p>All the methods mentioned above can be utilized within either a widget or another provider.</p><pre><br>@riverpod<br>String value(ValueRef ref) {<br>  // use ref to obtain other providers<br>  final repository = ref.watch(repositoryProvider);<br>  return repository.get();<br>}</pre><h3>Exploring Different Types of Providers</h3><p>Riverpod offers eight different types of providers, each suited for specific use cases. However, some of them, such as StateProvider, StateNotifierProvider, and ChangeNotifierProvider, are considered legacy and will be deprecated in future versions. Therefore, we will not discuss those providers.</p><h4>Provider</h4><pre>class UserRepository{<br>  Future&lt;List&lt;User&gt;&gt; getUsers(String companyId){...}<br>    <br>  Future&lt;User&gt; create(User user) async {...}<br><br>  Future&lt;User&gt; update(User user) async {...}<br><br>  Future&lt;void&gt; delete(User user) async {...}<br>  // some methods.<br>}</pre><pre>// The syntax for defining a provider is as followed:<br><br>@rivperpod<br>UserRepository userRepository(UserRepositoryRef ref){<br>    return UserRepository();<br>}<br></pre><blockquote>Riverpod replaces design patterns such as singletons, service locators, dependency injection, and InheritedWidgets.</blockquote><h4>FutureProvider</h4><pre>// you can pass arguments to your requests like normal function.<br>@riverpod<br>Future&lt;List&lt;User&gt;&gt; user(UserRef ref, String companyId) async {<br>  final users = ref.watch(userRepositoryProvider).getUsers(companyId);<br>  return users;<br>}</pre><p>In the code snippets, we fetch user data from the UserRepository and return the user information. You might ask how error and loading states are handled. All these states are natively managed by providers.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftenor.com%2Fembed%2F25585329&amp;display_name=Tenor&amp;url=https%3A%2F%2Ftenor.com%2Fview%2Fchris-pratt-andy-dwyer-omg-shocked-face-meme-gif-25585329&amp;image=https%3A%2F%2Fmedia.tenor.com%2F9CJaHEmyKPAAAAAF%2Fchris-pratt-andy-dwyer.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=tenor" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/a48f0a5c94e73b36134f85fcc5a35048/href">https://medium.com/media/a48f0a5c94e73b36134f85fcc5a35048/href</a></iframe><p>Another key feature is that providers are lazy; they will not execute until they are read by the UI at least once. Subsequent reads will not re-execute the network request but will instead return the previously fetched data. If the UI stops using this provider, the cache will be destroyed. Then, if the UI uses the provider again, a new network request will be made.</p><p>Let’s see how the UI renders our FutureProvider.</p><pre>class Home extends ConsumerWidget {<br>  const Home({super.key,required this.id});<br>  String id;<br>  @override<br>  Widget build(BuildContext context) {<br>        final user = ref.watch(userProvider(id));<br><br>        return Center(<br>          child: switch (user) {<br>            AsyncData(:final value){<br>               return ListView.builder(<br>                itemCount: value.length,<br>                itemBuilder: (context, index) {<br>                 return UserWidget(user:value[index]);<br>              });<br>            },<br>            AsyncError() =&gt; const Text(&#39;Oops, something unexpected happened&#39;),<br>            _ =&gt; const CircularProgressIndicator(),<br>          },<br>        );<br>  }<br>}</pre><p>We retrieved user info by making HTTP GET requests. But how do we handle changing user data (side-effects) using POST, PUT, or DELETE methods? Let’s explore the AsyncNotifierProvider.</p><h4>AsyncNotifierProvider</h4><p>For AsyncNotifierProvider, you can refer to the official <a href="https://riverpod.dev/docs/essentials/side_effects">documentation</a>. However, it may not be convenient for showing dialogs or snackbars. So, we will demonstrate a different approach.</p><p>First, we create an AsyncNotifierProvider to perform our POST request.</p><pre>@riverpod<br>class AsyncUserFormNotifier extends _$AsyncUserFormNotifier {<br><br>  // use fpdart package<br>  // To leverage functional programming concepts and constructs within your Flutter application. <br>  // Fpdart provides a set of functional programming utilities and data types, <br>  // such as Option, Either, Task, and more, <br>  // which can help you write more robust, predictable, and maintainable code.<br><br>  @override<br>  FutureOr&lt;Option&lt;Unit&gt;&gt; build() =&gt; const None();<br><br>  Future&lt;void&gt; createUser(User val) async {<br>    state = const AsyncValue.loading();<br><br>    state = await state.guardX(() async {<br>      final user =<br>          await ref.watch(userRepositoryProvider).create(val);<br>  <br>      return const Some(unit);<br>    });<br>  }<br><br>  Future&lt;void&gt; updateUser(User val) async {<br>      state = const AsyncValue.loading();<br>  <br>      state = await state.guardX(() async {<br>        final user =<br>            await ref.watch(userRepositoryProvider).update(val);<br>    <br>        return const Some(unit);<br>      });<br>    }<br><br>  Future&lt;void&gt; deleteUser(User val) async {<br>      state = const AsyncValue.loading();<br>  <br>      state = await state.guardX(() async {<br>        final user =<br>            await ref.watch(userRepositoryProvider).delete(val);<br>    <br>        return const Some(unit);<br>      });<br>    }<br>}</pre><p>We need to change our userProvider from a function-based approach to a class-based approach because we need to update our local cache.</p><pre>@riverpod<br>class User extends _$User {<br>  @override<br>  Future&lt;List&lt;User&gt;&gt; build(String companyId) async {<br>    final users = ref.watch(userRepositoryProvider).getUsers(companyId);<br>    return users;<br>  }<br>}</pre><p>And then, add methods to perform side-effects.</p><pre>@riverpod<br>class User extends _$User {<br>  @override<br>  Future&lt;List&lt;User&gt;&gt; build(String companyId) async {<br>    final users = ref.watch(userRepositoryProvider).getUsers(companyId);<br>    return users;<br>  }<br><br>  Future&lt;void&gt; createUser(User user)async{<br>    // If your backend responds with a user object, <br>    // you should update your local cache to reflect this new data. <br>    final previousValue = state.requireValue;<br><br>    state = AsyncValue.data([...previousValue, user]);<br><br>    // Or<br>    // to re-execute the GET request<br>    ref.invalidateSelf();<br>  }<br><br>  Future&lt;void&gt; updateUser(User user)async{<br>    // If your backend responds with a user object, <br>    // you should update your local cache to reflect this new data. <br>    final previousValue = state.requireValue;<br><br>    state = AsyncValue.data([<br>        for (final v in previousValue)<br>          if (user.id == user.id) user else v,<br>      ]);<br><br>    // Or<br>    // to re-execute the GET request<br>    ref.invalidateSelf();<br>  }<br><br>  Future&lt;void&gt; deleteUser(User user)async{<br>    // If your backend responds with a user object, <br>    // you should update your local cache to reflect this new data. <br>    final previousValue = state.requireValue;<br><br>    state = AsyncValue.data([<br>        for (final v in previousValue.items)<br>          if (v.id != val.id) v,<br>      ]);<br><br>    // Or<br>    // to re-execute the GET request<br>    ref.invalidateSelf();<br>  }<br>}</pre><p>Then we add these methods to our AsyncUserFormNotifier.</p><pre>@riverpod<br>class AsyncUserFormNotifier extends _$AsyncUserFormNotifier {<br><br>  // use fpdart package<br>  // To leverage functional programming concepts and constructs within your Flutter application. <br>  // Fpdart provides a set of functional programming utilities and data types, <br>  // such as Option, Either, Task, and more, <br>  // which can help you write more robust, predictable, and maintainable code.<br><br>  @override<br>  FutureOr&lt;Option&lt;Unit&gt;&gt; build() =&gt; const None();<br><br>  Future&lt;void&gt; createUser(User val) async {<br>    state = const AsyncValue.loading();<br><br>    state = await state.guardX(() async {<br>      final user =<br>          await ref.watch(userRepositoryProvider).create(val);<br>      // call create method from userProvider to update local data.<br>      ref.read(userProvider.notifier).createUser(user);<br>      return const Some(unit);<br>    });<br>  }<br><br>  Future&lt;void&gt; updateUser(User val) async {<br>      state = const AsyncValue.loading();<br>  <br>      state = await state.guardX(() async {<br>        final user =<br>            await ref.watch(userRepositoryProvider).update(val);<br>        // call update method from userProvider to update local data.<br>        ref.read(userProvider.notifier).updateUser(user);<br>        return const Some(unit);<br>      });<br>    }<br><br>  Future&lt;void&gt; deleteUser(User val) async {<br>      state = const AsyncValue.loading();<br>  <br>      state = await state.guardX(() async {<br>        final user =<br>            await ref.watch(userRepositoryProvider).delete(val);<br>        // call delete method from userProvider to update local data.<br>        ref.read(userProvider.notifier).deleteUser(user);<br>        return const Some(unit);<br>      });<br>    }<br>}</pre><p>Then, our UI will look like this.</p><pre>class Home extends ConsumerWidget {<br>  const Home({super.key,required this.id});<br>  String id;<br>  @override<br>  Widget build(BuildContext context) {<br>        final user = ref.watch(userProvider(id));<br>        <br>        // To illustrate state changes using an imperative approach,<br><br>        ref.listen(asyncUserFormNotifierProvider, (_,state)){<br>            state.unwrapPrevious().maybeWhen(<br>            orElse: () {},<br>            loading: () =&gt; LoadingOverlay.show(),<br>            data: (data) {<br>              // replace your widget<br>              LoadingOverlay.hide();<br>              // show snackbar or dialog<br>            },<br>            error: (e, stack) {<br>              // replace your widget<br>              LoadingOverlay.hide();<br>             // show snackbar or dialog<br>            },<br>          );<br>        }<br><br>        return Center(<br>          child: switch (user) {<br>           AsyncData(:final value){<br>               return ListView.builder(<br>                itemCount: value.length,<br>                itemBuilder: (context, index) {<br>                 final user = value[index];<br>                 return UserWidget(<br>                    user: user,<br>                    // call delete method to delete user.<br>                    // Notice that we exclusively utilize the ref.read method, as mentioned earlier.<br>                    onDelete: () =&gt; ref.read(asyncUserFormNotifierProvider.notifer).delete(user);<br><br>                  );<br>              });<br>            },<br>            AsyncError() =&gt; const Text(&#39;Oops, something unexpected happened&#39;),<br>            _ =&gt; const CircularProgressIndicator(),<br>          },<br>        );<br>  }<br>}</pre><h4>StreamProvider and StreamNotifierProvider</h4><p>SreamProvider and StreamNotifierProvider are similar to FutureProvider and AsyncNotifierProvider, respectively.</p><pre>@riverpod<br>Stream&lt;String&gt; example(ExampleRef ref) async* {<br>  yield &#39;foo&#39;;<br>}</pre><pre>@riverpod<br>class Example extends _$Example {<br>  @override<br>  Stream&lt;String&gt; build() async* {<br>    yield &#39;foo&#39;;<br>  }<br><br>  // Add methods to mutate the state<br>}</pre><p>Therefore, we will not explain them in detail. You can refer to the above example and the official <a href="https://riverpod.dev/docs/essentials/websockets_sync">documentation</a>.</p><h4>NotifierProvider</h4><p>NotifierProvider can be used to mutate state, such as adding a new item to a list, updating the list, deleting an item from a list, and more. It can also be used in form validation, onSaved callbacks to save the current form field state, and can be accessed from anywhere. Let’s see how to define a Notifier.</p><pre>@riverpod<br>class Counter extends _$Counter {<br>  @override<br>  int build() =&gt; 0;<br><br>  void increment() =&gt; state++;<br>  void decrement() =&gt; state--;<br>}</pre><pre>class CounterWidget extends ConsumerWidget {<br>  @override<br>  Widget build(BuildContext context, WidgetRef ref) {<br>   <br>    final counter = ref.watch(counterProvider);<br>    return ElevatedButton(<br>     <br>      child: Text(&#39;Value: $counter&#39;),<br>      <br>      onPressed: () =&gt; ref.read(counterProvider.notifier).increment(),<br>    );<br>  }<br>}</pre><p>Well, this covers the different types of providers in Riverpod.</p><h3>Additional Riverpod Features</h3><h4><strong>Provider </strong>Lifecycles</h4><p>So far, we’ve seen how to create/update some state. But we have yet to talk about when state destruction occurs.</p><p>Riverpod offers various ways to interact with state disposal. This ranges from delaying the disposal of state to reacting to destruction.</p><pre>// We can specify &quot;keepAlive&quot; in the annotation to disable<br>// the automatic state destruction<br>// It will retain the data indefinitely unless the user closes the app.<br>@Riverpod(keepAlive: true)<br>int example(ExampleRef ref) {<br>  return 0;<br>}</pre><p>If we don’t specify <strong>keepAlive: true</strong>, the state will automatically be destroyed when there are no active listeners. For example, if the user leaves the screen, the state will be destroyed, and a new state will be created when the user returns. ( @riverpod and @Riverpod(keepAlive: false) are equivalent. )</p><p>But what if we want to hold the state for a specific amount of time? While Riverpod currently doesn’t support this directly, you can achieve it using a <strong>Timer</strong> and <strong>ref.keepAlive</strong>. By implementing this logic in an extension method, you can make it reusable.</p><pre>// Keep in mind that this method only works with AutoDisposeRef, not with Ref.<br>extension CacheForExtension on AutoDisposeRef&lt;Object?&gt; {<br>  /// Keeps the provider alive for [duration].<br>  void cacheFor(Duration duration) {<br>    // Immediately prevent the state from getting destroyed.<br>    final link = keepAlive();<br>    // After duration has elapsed, we re-enable automatic disposal.<br>    final timer = Timer(duration, link.close);<br><br>    // Optional: when the provider is recomputed (such as with ref.watch),<br>    // we cancel the pending timer.<br>    onDispose(timer.cancel);<br>  }<br>}</pre><p>Then, we can use it like so:</p><pre>@riverpod<br>Future&lt;Object&gt; example(ExampleRef ref) async {<br>  /// Keeps the state alive for 5 minutes<br>  ref.cacheFor(const Duration(minutes: 5));<br><br>  return http.get(Uri.https(&#39;example.com&#39;));<br>}</pre><p>You can find more information about this in the following article: <a href="https://codewithandrea.com/articles/flutter-riverpod-data-caching-providers-lifecycle/">Flutter Riverpod Data Caching Providers Lifecycle</a>.</p><h4>Destruction of a provider</h4><p>Sometimes, you may want to invalidate a provider. This can be done using <strong>ref.invalidate</strong>, which can be triggered from a widget or another provider. When invoked, it destroys the current state of the provider. Two possible outcomes follow: if the provider has active listeners, a new state will be created; if not, the provider will be fully destroyed.</p><pre>class Home extends ConsumerWidget {<br>  const Home({super.key,required this.id});<br>  String id;<br>  @override<br>  Widget build(BuildContext context) {<br>        final user = ref.watch(userProvider(id));<br><br>        return Center(<br>          child: switch (user) {<br>            AsyncData(:final value){...},<br>            AsyncError() =&gt; const TextButton(child: Text(&#39;Oops, something unexpected happened&#39;),<br>            // here it will destory current state and refetch the data again. <br>            onPressed:()=&gt; ref.invalidate(userProvider(id)))),<br>            _ =&gt; const CircularProgressIndicator(),<br>          },<br>        );<br>  }<br>}</pre><h4>Debouncing and Cancelling network requests</h4><p>Debouncing a request is a technique used to delay the execution of an action (like sending a request or triggering an event) until a specified time has elapsed since the last input or event. It’s commonly used to optimize performance and prevent unnecessary actions, especially in scenarios with frequent or rapid inputs/events, like typing in a search box or scrolling a page.</p><p>Canceling a request involves terminating an ongoing operation before it completes. For example, if the user navigates away from the page before the request finishes. This ensures that you don’t waste time processing a response that the user will never see.</p><pre><br>extension DebounceAndCancelExtension on AutoDisposeRef {<br> <br>  /// That client will automatically be closed when the provider is disposed.<br>  Future&lt;DioClient&gt; getDebouncedHttpClient([Duration? duration]) async {<br>    // First, we handle debouncing.<br>    var didDispose = false;<br>    onDispose(() =&gt; didDispose = true);<br><br>    // We delay the request by 500ms, to wait for the user to stop refreshing<br>    // or keep scorlling or keep typing.<br>    await Future&lt;void&gt;.delayed(duration ?? const Duration(milliseconds: 500));<br><br>    // If the provider was disposed during the delay, it means that the user<br>    // refreshed again. We throw an exception to cancel the request.<br>    // It is safe to use an exception here, as it will be caught by Riverpod.<br>    if (didDispose) {<br>      throw Exception(&#39;Cancelled&#39;);<br>    }<br><br>    // We now create the client and close it when the provider is disposed.<br>    final dioClient = watch(dioClientProvider);<br><br>    onDispose(dioClient.dio.close);<br><br>    // Finally, we return the client to allow our provider to make the request.<br>    return dioClient;<br>  }<br>}</pre><p>The above method is only suitable when you use your Dio object in an AutoDisposeProvider.</p><p>When injecting your Dio class into your remote data source, it’s not convenient to handle cancellation. You’ll need to manually create a <strong>CancelToken</strong> object, pass it to your request, and call <strong>cancelToken.cancel</strong> in the <strong>ref.onDispose</strong> method to cancel the request.</p><p>For use cases like pagination with search, you may need to debounce requests. Add these lines to your provider:</p><pre>await Future.delayed(const Duration(milliseconds: 500));<br>if (cancelToken.isCancelled) {<br>  throw AbortedException();<br>}</pre><p>To learn how to implement pagination with search features, and how to debounce and cancel requests, please follow the <a href="https://medium.com/@kyawthetwam/flutter-pagination-with-performing-side-effects-in-riverpod-494a0b861532">link</a>.</p><h4>Scoping Providers</h4><p>Scoping in Riverpod has various use cases, detailed in the <a href="https://riverpod.dev/docs/concepts/scopes">official documentation</a>. We will focus on optimizing widget rebuilds by removing parameters from widget constructors, allowing you to make them const.</p><pre><br>// 1. Declare a Provider<br>final currentProductIndex = Provider&lt;int&gt;((_) =&gt; throw UnimplementedError());<br><br>class ProductList extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return ListView.builder(itemBuilder: (context, index) {<br>      // 2. Add a parent ProviderScope<br>      return ProviderScope(<br>        overrides: [<br>          // 3. Add a dependency override on the index<br>          currentProductIndex.overrideWithValue(index),<br>        ],<br>        // 4. return a **const** ProductItem with no constructor arguments<br>        child: const ProductItem(),<br>      );<br>    });<br>  }<br>}<br><br>class ProductItem extends ConsumerWidget {<br>  const ProductItem({super.key});<br><br>  @override<br>  Widget build(BuildContext context, WidgetRef ref) {<br>    // 5. Access the index via WidgetRef<br>    final index = ref.watch(currentProductIndex);<br>    // do something with the index<br>  }<br>}</pre><p>This improves performance because <strong>ProductItem </strong>can be a const widget in <strong>ListView.builder</strong>. It will only rebuild if its index changes, even if the <strong>ListView</strong> rebuilds.</p><h4>Filtering widget/provider rebuild using “select” and “selectAsync” .</h4><p>By default, using <strong>ref.watch</strong> causes consumers/providers to rebuild whenever any property of an object changes. For example, watching a User and only using its &quot;name&quot; will still cause the consumer to rebuild if the &quot;age&quot; changes. To prevent this and only rebuild when specific properties change, we can use the <strong>select</strong> functionality of providers.</p><pre><br>@riverpod<br>User example(ExampleRef ref) =&gt; User(name:&quot;Joe&quot;,age: 50);<br><br>class ConsumerExample extends ConsumerWidget {<br>  @override<br>  Widget build(BuildContext context, WidgetRef ref) {<br>   <br>    String name = ref.watch(exampleProvider.select((it) =&gt; it.name));<br>    // This will cause the widget to only listen to changes on &quot;name&quot;.<br><br>    return Text(&#39;Hello $name&#39;);<br>  }<br>}</pre><p>The usage of <strong>selectAsync</strong> is similar to that of <strong>select</strong>, but it returns a Future instead:</p><pre>@riverpod<br>Object? example(ExampleRef ref) async {<br>  // Wait for a user to be available, and listen to only the &quot;name&quot; property<br>  final firstName = await ref.watch(<br>    userProvider.selectAsync((it) =&gt; it.name),<br>  );<br>}</pre><h3>Conclusion</h3><p>In this article, you’ll see how Riverpod’s flexibility and features help developers create flutter apps more effectively and manage state safely. we cannot cover everything about Riverpod, but it provides enough information for every use case and makes it easy to start with if you have no prior experience. Lastly, I recommend reading the official documentation, following the examples, and joining the Riverpod Discord channels to better understand and use Riverpod effectively. Happy coding!</p><h3>References</h3><ol><li><a href="https://riverpod.dev/">Riverpod Documentation</a></li><li><a href="https://codewithandrea.com/">Code With Andrea</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=879cfe68a4d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Pagination with Performing side effects in Riverpod]]></title>
            <link>https://medium.com/@kyawthetwam/flutter-pagination-with-performing-side-effects-in-riverpod-494a0b861532?source=rss-59f0ebe208c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/494a0b861532</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[side-effects]]></category>
            <category><![CDATA[pagination]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[riverpod]]></category>
            <dc:creator><![CDATA[Kyaw Thet Wam]]></dc:creator>
            <pubDate>Sat, 11 May 2024 17:28:13 GMT</pubDate>
            <atom:updated>2024-05-31T10:31:39.594Z</atom:updated>
            <content:encoded><![CDATA[<p>Unlock the power of Riverpod for seamless infinite pagination in Flutter</p><p>In the realm of modern app development, seamless user experiences are paramount. Whether it’s a social media feed, an e-commerce product list, or a news aggregator, users expect smooth and uninterrupted scrolling through content.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fdLeozmS48Mh24KqPULLBQ.jpeg" /><figcaption>Photo by cottonbro studio: <a href="https://www.pexels.com/photo/person-using-a-smartphone-5077039/">https://www.pexels.com/photo/person-using-a-smartphone-5077039/</a></figcaption></figure><p>In this article, we dive into the world of infinite pagination, exploring how it can be efficiently implemented using Riverpod, a state management solution for Flutter applications. By leveraging the power and simplicity of Riverpod, developers can effortlessly integrate infinite pagination into their Flutter projects.</p><h4>Unlocking Intermediate Complexity: Insights for Experienced Flutter Developers</h4><p>Before we dive into the trick of infinite pagination with Riverpod, it’s essential to note that this article is designed for those with some experience in flutter app development. Intended for developers familiar with Flutter and state management concepts, we’ll be exploring complex topics related to dynamic data loading.</p><h4>Evaluating Riverpod Pagination Strategies: Understanding Resource Variance and Project Alignment</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Izfc_R6IftaGYLKF8WBUA.jpeg" /><figcaption>Photo by Lukas: <a href="https://www.pexels.com/photo/laptop-computer-showing-c-application-574069/">https://www.pexels.com/photo/laptop-computer-showing-c-application-574069/</a></figcaption></figure><p>While there are numerous articles and videos available on pagination with Riverpod, many of them offer valuable insights. One such notable example is <a href="https://codewithandrea.com/articles/flutter-riverpod-pagination/"><strong>Andrea’s latest article</strong></a>, which is based on Riverpod official pub example and is widely regarded as one of the best resources, particularly for applications such as social media platforms. However, despite the excellence of these resources, their approaches may not always align perfectly with specific project requirements. In this article, we will delve into the reasons why this is the case.</p><h4>Navigating Riverpod Pagination Challenges: Strategies for Enhancing Data Fetching Efficiency and Overcoming Persistent Flutter Issues</h4><p>In the Riverpod official pub example, everything is streamlined with less boilerplate code, providing an almost perfect solution. However, there is one Flutter issue that persists, which can be found at <a href="https://github.com/flutter/flutter/issues/130658"><strong>this link</strong></a>. Fortunately, there are two tricks that can mitigate this issue. The first involves using a keep-alive, which necessitates manually invalidating the family provider upon screen popping. The second workaround employs a combination of a Timer and <strong>ref.keepAlive</strong>, enabling the state to remain alive for a set duration before disposing and fetching data again. Additional explanations can be found in <a href="https://github.com/rrousselGit/riverpod/discussions/2887#discussioncomment-6949745"><strong>this discussion</strong></a>.</p><p>These approaches may be particularly suitable for scenarios such as continuously fetching data and displaying a Shimmer widget upon scrolling back up to obtain up-to-date data. If Flutter has addressed the issue, following the Riverpod official pub example would suffice. For this article’s purposes, however, we will exclusively use the list mutation approach.</p><h4>Implementation of Pagination</h4><p>First defines an abstract class named PaginatedDataItem. Here&#39;s what it does:</p><pre>abstract class PagingDataItem {<br>  int get id;<br>}</pre><ul><li>The purpose of this abstract class is to serve as a blueprint for data items used in a paging mechanism.</li></ul><p>Create a user class that implements the PagingDataItem interface by providing an implementation for the id using <a href="https://pub.dev/packages/freezed">Freezed</a>.</p><pre>@freezed<br>class User with _$User implements PagingDataItem {<br>  const factory Person({<br>    required int id,<br>    required String name,<br>    required String email,<br>    required int address,<br>  }) = _User;<br><br>  factory User.fromJson(Map&lt;String, Object?&gt; json)<br>      =&gt; _$UserFromJson(json);<br>}</pre><p>Next, create a repository class named UserRepository to fetch data from the backend API.</p><pre><br>class UserRepository {<br>  const UserRepository({required this.client, required this.apiKey});<br>  final Dio dio;<br><br>  Future&lt;User&gt; users(<br>      {required int page, CancelToken? cancelToken}) async {<br>    <br>    final response = await dio.get(&#39;${Enpoints}users?page=$page&#39;, cancelToken: cancelToken);<br>    return User.fromJson(response.data);<br>  }<br><br>  Future&lt;User&gt; searchUsers(<br>      {required Pagination pagination, CancelToken? cancelToken}) async {<br>    <br>    final response = await dio.get(&#39;${Enpoints}users?page=${pagination.page}&amp;query=${pagination.query}&#39;, cancelToken: cancelToken);<br>    return User.fromJson(response.data);<br>  }<br><br>  Future&lt;User&gt; userById(<br>      {required int id, CancelToken? cancelToken}) async {...}<br><br>  Future&lt;User&gt; create(User user) async {...}<br><br>  Future&lt;User&gt; update(User user) async {...}<br><br>  Future&lt;void&gt; delete(User user) async {...}<br><br>}<br><br>@riverpod<br>UserRepository userRepository(UserRepositoryRef ref) =&gt; UserRepository(<br>      dio: ref.watch(dioProvider));</pre><p>Next, create PaginatedData model.</p><ul><li>The purpose of this class is to represent paginated data in a structured format.</li><li>It encapsulates a list of items (items), the current page number (page), and a boolean flag indicating if there are more pages (hasMore).</li><li>By using generics, it allows for flexibility in the type of items contained in the paginated data, as long as they conform to the PagingDataItem interface.</li></ul><pre>@freezed<br>class PaginatedData&lt;T extends PagingDataItem&gt; with _$PaginatedData&lt;T&gt; {<br>  const factory PaginatedData({<br>    required List&lt;T&gt; items,<br>    required int page,<br>    required bool hasMore,<br>  }) = _PaginatedData&lt;T&gt;;<br>}</pre><p>Then create an abstract class PaginatedAsyncNotifierthat extends AutoDisposeAsyncNotifier and specifies a generic type T that extends PagingDataItem.</p><ul><li>Method fetchNext is declared as abstract, meaning any concrete subclass must provide an implementation.</li><li>Method loadNext is implemented with default behavior but can be overridden by subclasses, asynchronously loads the next page of data annd checks the current state, handles error states, and loads the next page if hasMore is true.</li></ul><pre><br>abstract class PaginatedAsyncNotifier&lt;T extends PagingDataItem&gt;<br>    extends AutoDisposeAsyncNotifier&lt;PaginatedData&lt;T&gt;&gt; {<br>  Future&lt;PaginatedData&lt;T&gt;&gt; fetchNext(int page);<br><br>  Future&lt;void&gt; loadNext() async {<br>    final value = state.valueOrNull;<br><br>    if (value == null) {<br>      return;<br>    }<br><br>    if (state.unwrapPrevious().hasError) {<br>      state = AsyncValue.data(value);<br>      return;<br>    }<br><br>    if (value.hasMore) {<br>      state = AsyncLoading&lt;PaginatedData&lt;T&gt;&gt;().copyWithPrevious(state);<br><br>      state = await state.guardX(<br>        () async {<br>          final next = await fetchNext(value.page + 1);<br><br>          return value.copyWith(<br>            items: [...value.items, ...next.items],<br>            page: value.page + 1,<br>            hasMore: next.hasMore,<br>          );<br>        },<br>      );<br>    }<br>  }<br>}</pre><p>The guardX method is simply an extension of the Riverpod AsyncValue.</p><pre><br>extension AsyncValueX&lt;T&gt; on AsyncValue&lt;T&gt; {<br>  Future&lt;AsyncValue&lt;T&gt;&gt; guardX(Future&lt;T&gt; Function() future) async {<br>    try {<br>      return AsyncValue.data(await future());<br>    } on DioException catch (e, stack) {<br>      // here DioException is custom error handling implementing Exception Class.<br>      final error = DioExceptions.fromDioError(e);<br>      return AsyncValue&lt;T&gt;.error(error, stack).copyWithPrevious(this);<br>    } catch (err, stack) {<br>      return AsyncValue&lt;T&gt;.error(&quot;Something went wrong!&quot;, stack)<br>          .copyWithPrevious(this);<br>    }<br>  }</pre><p>Now that we’ve finished all the required components, all we need to do is create a provider for the user model.</p><pre>typedef PaginatedUserState = PaginatedData&lt;User&gt;;<br><br>@riverpod<br>class PaginatedUserNotifier extends PaginatedAsyncNotifier&lt;User&gt; {<br>  @override<br>  Future&lt;PaginatedUserState&gt; build() async {<br>    final userRepo = ref.watch(userRepositoryProvider);<br>    final query = ref.watch(userSearchQueryNotifierProvider);<br><br>    final cancelToken = CancelToken();<br><br>    ref.onDispose(() {<br>      cancelToken.cancel();<br>    });<br><br>    if (query.isEmpty) {<br>      final res = await userRepo.users(<br>        page: 1,<br>        cancelToken: cancelToken,<br>      );<br><br>      return PaginatedUserState(<br>        items: res.results,<br>        page: 1,<br>        hasMore: res.results.length &gt;= pageSize,<br>      );<br>    } else {<br>      // Debounce the request. See details https://riverpod.dev/docs/<br>      await Future.delayed(const Duration(milliseconds: 500));<br>      if (cancelToken.isCancelled) {<br>        throw AbortedException();<br>      }<br>      // using search endpoint<br>      final res = await userRepo.searchUsers(<br>        pagination: (page: 1, query: query),<br>        cancelToken: cancelToken,<br>      );<br>      return PaginatedUserState(<br>        items: res.results,<br>        page: 1,<br>        hasMore: res.results.length &gt;= pageSize,<br>      );<br>    }<br>  }<br><br>  @override<br>  Future&lt;PaginatedUserState&gt; fetchNext(int page) async {<br>    final userRepo = ref.watch(userRepositoryProvider);<br>    final query = ref.watch(userSearchQueryNotifierProvider);<br><br>    final cancelToken = CancelToken();<br>    final currentPage = page + 1;<br><br>    ref.onDispose(() {<br>      cancelToken.cancel();<br>    });<br><br>    if (query.isEmpty) {<br>      final res = await userRepo.users(<br>        page: page,<br>        cancelToken: cancelToken,<br>      );<br><br>      return PaginatedUserState(<br>        items: res.results,<br>        page: currentPage,<br>        hasMore: res.results.length &gt;= pageSize,<br>      );<br><br>    } else {<br><br>      final res = await userRepo.searchUsers(<br>        pagination: (page: page, query: query),<br>        cancelToken: cancelToken,<br>      );<br><br>      return PaginatedUserState(<br>        items: res.results,<br>        page: currentPage,<br>        hasMore: res.results.length &gt;= pageSize,<br>      );<br>    }<br>    <br>  }<br>}</pre><p>UserSearchQueryNotifier:</p><pre><br>@riverpod<br>class UserSearchQueryNotifier extends _$UserSearchQueryNotifier {<br>  @override<br>  String build() {<br>    // by default, return an empty query<br>    return &#39;&#39;;<br>  }<br><br>  void setQuery(String query) {<br>    state = query;<br>  }<br>}</pre><p>Then, all we have left to do is implement the User interface.</p><pre><br>class UserScreen extends HookConsumerWidget {<br>  const UserScreen({super.key});<br><br>  @override<br>  Widget build(BuildContext context, WidgetRef ref) {<br>    final userNotifier = ref.read(paginatedUserNotifierProvider.notifier);<br><br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&#39;Users&#39;),<br>      ),<br>      body: Column(<br>        children: [<br>          const UserSearchBar(),<br>          Expanded(<br>            child: ref.watch(paginatedUserNotifierProvider).whenPlus(<br>                  data: (data, hasError) {<br>                    final endItem = data.hasMore &amp;&amp; !hasError<br>                        ? BottomWidget(<br>                            onScrollEnd: () =&gt; userNotifier.loadNext())<br>                        : data.hasMore &amp;&amp; hasError<br>                            ? ErrorWidget(<br>                                retryCallback: () =&gt; userNotifier.loadNext())<br>                            : null;<br>                    return RefreshIndicator(<br>                      onRefresh: () =&gt;<br>                          ref.refresh(paginatedUserNotifierProvider.future),<br>                      child: ListView.builder(<br>                        key: const PageStorageKey(&#39;pageKey&#39;),<br>                        itemCount:<br>                            data.items.length + (endItem != null ? 1 : 0),<br>                        itemBuilder: (context, index) {<br>                          if (endItem != null &amp;&amp; index == data.items.length) {<br>                            return endItem;<br>                          }<br><br>                          return ListTile(<br>                            title: Text(data.items[index].name),<br>                            subtitle: Text(data.items[index].email),<br>                          );<br>                        },<br>                      ),<br>                    );<br>                  },<br>                  loading: () =&gt; ListOfShimmerWidget(),<br>                  error: (e, st) =&gt; Center(<br>                    child: Column(<br>                      mainAxisSize: MainAxisSize.min,<br>                      children: [<br>                        IconButton(<br>                          onPressed: () =&gt;<br>                              ref.invalidate(paginatedUserNotifierProvider),<br>                          icon: const Icon(Icons.refresh),<br>                        ),<br>                        Text(e.toString()),<br>                      ],<br>                    ),<br>                  ),<br>                  skipErrorOnHasValue: true,<br>                ),<br>          ),<br>        ],<br>      ),<br>    );<br>  }<br>}<br><br><br>class BottomWidget extends StatelessWidget {<br>  final VoidCallback onScrollEnd;<br>  const BottomWidget({<br>    super.key,<br>    required this.onScrollEnd,<br>  });<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return VisibilityDetector(<br>      key: key ?? const Key(&#39;Bottom&#39;),<br>      onVisibilityChanged: (info) {<br>        if (info.visibleFraction &gt; 0.1) {<br>          onScrollEnd();<br>        }<br>      },<br>      child: const ShimmerWidget() or CircularProgressIndicator(),<br>    );<br>  }<br>}<br><br><br><br>class ErrorWidget extends StatelessWidget {<br>  const ErrorWidget({super.key, required this.retryCallback});<br><br>  final VoidCallback retryCallback;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Column(<br>      children: [<br>        const Text(&quot;Something went wrong&quot;),<br>        TextButton(<br>          onPressed: retryCallback,<br>          child: const Text(&quot;Retry&quot;),<br>        ),<br>      ],<br>    );<br>  }<br>}<br><br><br>class UserSearchbar extends ConsumerWidget {<br>  const UserSearchbar({super.key});<br><br>  @override<br>  Widget build(BuildContext context, WidgetRef ref) {<br>    return TextField(<br>      onChanged: (text) =&gt;<br>          ref.read(userSearchQueryNotifierProvider.notifier).setQuery(text),<br>    );<br>  }<br>}<br></pre><p>The whenPlus method is an extension of Riverpod AsyncValue, used to explore the hasError field when fetching the next set of data. If it’s true, it displays an error widget at the bottom with a retryCallback.</p><pre>extension AsyncValueX&lt;T&gt; on AsyncValue&lt;T&gt; {<br>  R whenPlus&lt;R&gt;({<br>    bool skipLoadingOnReload = false,<br>    bool skipLoadingOnRefresh = true,<br>    bool skipError = false,<br>    bool skipErrorOnHasValue = false,<br>    required R Function(T data, bool hasError) data,<br>    required R Function(Object error, StackTrace stackTrace) error,<br>    required R Function() loading,<br>  }) {<br>    if (skipErrorOnHasValue) {<br>      if (hasValue &amp;&amp; hasError) {<br>        return data(requireValue, true);<br>      }<br>    }<br><br>    return when(<br>      skipLoadingOnReload: skipLoadingOnReload,<br>      skipLoadingOnRefresh: skipLoadingOnRefresh,<br>      skipError: skipError,<br>      data: (d) =&gt; data(d, hasError),<br>      error: error,<br>      loading: loading,<br>    );<br>  }<br>}</pre><p>That’s all about pagination. Next, we’ll focus on implementing side effects, such as CRUD (Create, Read, Update, Delete) API operations. When implementing these, it’s common for an update request (typically a POST) to also update the local cache, ensuring that the UI reflects the new state.</p><h4>Implementation of Performing side effects</h4><p>Now that we have a user form Notifier, we can start adding methods to enable performing side effects (such as <em>POST</em> requests). This could be achieved by incorporating addUser, updateUser, and deleteUser methods into our notifier.</p><pre><br>@riverpod<br>class AsyncUserFormNotifier extends _$AsyncUserFormNotifier {<br><br>  // use fpdart package<br>  // To leverage functional programming concepts and constructs within your Flutter application. <br>  // Fpdart provides a set of functional programming utilities and data types, <br>  // such as Option, Either, Task, and more, <br>  // which can help you write more robust, predictable, and maintainable code.<br><br>  @override<br>  FutureOr&lt;Option&lt;Unit&gt;&gt; build() =&gt; const None();<br><br>  Future&lt;void&gt; createUser(User val) async {<br>    state = const AsyncValue.loading();<br><br>    state = await state.guardX(() async {<br>      final user =<br>          await ref.watch(userRepositoryProvider).create(val);<br>  <br>      return const Some(unit);<br>    });<br>  }<br><br>  Future&lt;void&gt; updateUser(User val) async {<br>      state = const AsyncValue.loading();<br>  <br>      state = await state.guardX(() async {<br>        final user =<br>            await ref.watch(userRepositoryProvider).update(val);<br>    <br>        return const Some(unit);<br>      });<br>    }<br><br>  Future&lt;void&gt; deleteUser(User val) async {<br>      state = const AsyncValue.loading();<br>  <br>      state = await state.guardX(() async {<br>        final user =<br>            await ref.watch(userRepositoryProvider).delete(val);<br>    <br>        return const Some(unit);<br>      });<br>    }<br>}</pre><p>Then, we need to listen to the user form state and display a loading overlay, success snackbar, or error snackbar accordingly.</p><pre>class UserScreen extends HookConsumerWidget {<br>  const UserScreen({super.key});<br><br>  @override<br>  Widget build(BuildContext context, WidgetRef ref) {<br>    final userNotifier = ref.read(paginatedUserNotifierProvider.notifier);<br><br>    ref.listen(asyncUserFormNotifierProvider, (_,state)){<br>        state.unwrapPrevious().maybeWhen(<br>            orElse: () {},<br>            loading: () =&gt; LoadingOverlay.show(),<br>            data: (data) {<br>              // replace your widget<br>              LoadingOverlay.hide();<br>              ShowSnackbarOnSuccess(context); <br>            },<br>            error: (e, stack) {<br>              // replace your widget<br>              LoadingOverlay.hide();<br>              ShowSnackbarOnError(context);<br>            },<br>          );<br>     }<br><br>    return Scaffold(...)<br>  }<br>}</pre><p>Alright, we’re almost there. But wait, we need to update our user list when we finish updating user information. How do we handle that? It’s actually quite straightforward. We just need to add some mutation methods in our PaginatedAsyncNotifier.</p><pre>abstract class PaginatedAsyncNotifier&lt;T extends PagingDataItem&gt;<br>    extends AutoDisposeAsyncNotifier&lt;PaginatedData&lt;T&gt;&gt; {<br>  Future&lt;PaginatedData&lt;T&gt;&gt; fetchNext(int page);<br><br>  Future&lt;void&gt; loadNext() async {...}<br>  <br>  // create<br>  void createItem(T val) {<br>    final previousValue = state.requireValue;<br><br>    state = AsyncValue.data(previousValue.copyWith(<br>      items: [...previousValue.items, val],<br>    ));<br>  }<br>  <br>  // update<br>  void updateItem(T val) {<br>    final previousValue = state.requireValue;<br><br>    state = AsyncValue.data(previousValue.copyWith(<br>      items: [<br>        for (final v in previousValue.items)<br>          if (v.id == val.id) val else v,<br>      ],<br>    ));<br>  }<br><br>  // delete<br>  void deleteItem(T val) {<br>    final previousValue = state.requireValue;<br><br>    state = AsyncValue.data(previousValue.copyWith(<br>      items: [<br>        for (final v in previousValue.items)<br>          if (v.id != val.id) v,<br>      ],<br>    ));<br>  }<br>   <br>}</pre><p>Next, we simply call these methods on our AsyncUserFormNotifier accordingly.</p><pre>@riverpod<br>class AsyncUserFormNotifier extends _$AsyncUserFormNotifier {<br><br>  // use fpdart package<br>  // To leverage functional programming concepts and constructs within your Flutter application. <br>  // Fpdart provides a set of functional programming utilities and data types, <br>  // such as Option, Either, Task, and more, <br>  // which can help you write more robust, predictable, and maintainable code.<br><br>  @override<br>  FutureOr&lt;Option&lt;Unit&gt;&gt; build() =&gt; const None();<br><br>  Future&lt;void&gt; createUser(User val) async {<br>    state = const AsyncValue.loading();<br><br>    state = await state.guardX(() async {<br>      final user =<br>          await ref.watch(userRepositoryProvider).create(val);<br>      // call create method to effect user list<br>      ref.read(paginatedUserNotifierProvider.notifier).createItem(user);<br>      return const Some(unit);<br>    });<br>  }<br><br>  Future&lt;void&gt; updateUser(User val) async {<br>      state = const AsyncValue.loading();<br>  <br>      state = await state.guardX(() async {<br>        final user =<br>            await ref.watch(userRepositoryProvider).update(val);<br>        // call update method to effect user list<br>        ref.read(paginatedUserNotifierProvider.notifier).updateItem(user);<br>        return const Some(unit);<br>      });<br>    }<br><br>  Future&lt;void&gt; deleteUser(User val) async {<br>      state = const AsyncValue.loading();<br>  <br>      state = await state.guardX(() async {<br>        final user =<br>            await ref.watch(userRepositoryProvider).delete(val);<br>        // call delete method to effect user list<br>        ref.read(paginatedUserNotifierProvider.notifier).deleteItem(user);<br>        return const Some(unit);<br>      });<br>    }<br>}</pre><p>Congratulations! That’s all we’ve done.</p><h4>Conclusion</h4><p>In conclusion, implementing pagination with performing side effects in Riverpod provides a powerful and efficient solution for managing data in Flutter applications. By leveraging Riverpod state management capabilities and its asynchronous operations, developers can seamlessly fetch and display paginated data while handling side effects such as loading indicators and error states. With Riverpod’s flexibility, reactive caching and simplicity, developers have a reliable toolset to streamline the implementation of pagination with performing side effects, empowering them to create high-quality Flutter applications with ease.</p><h4>References:</h4><p>z<a href="https://zenn.dev/k9i/articles/b8c333e1bb8b9b">enn.dev</a>, <a href="https://riverpod.dev/">riverpod.dev</a>, <a href="https://codewithandrea.com/">Code With Andrea</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=494a0b861532" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>