<?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 Ademola Kolawole on Medium]]></title>
        <description><![CDATA[Stories by Ademola Kolawole on Medium]]></description>
        <link>https://medium.com/@ademolakolawole?source=rss-97299a8a410e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*nO9qDtQwylgwASlPLzbXKA.png</url>
            <title>Stories by Ademola Kolawole on Medium</title>
            <link>https://medium.com/@ademolakolawole?source=rss-97299a8a410e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 17:51:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ademolakolawole/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[Embracing Boredom]]></title>
            <link>https://medium.com/@ademolakolawole/embracing-boredom-bbfcda63ff1c?source=rss-97299a8a410e------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbfcda63ff1c</guid>
            <category><![CDATA[self-reflection]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[boredom]]></category>
            <category><![CDATA[personal-development]]></category>
            <dc:creator><![CDATA[Ademola Kolawole]]></dc:creator>
            <pubDate>Fri, 12 Jun 2026 08:06:00 GMT</pubDate>
            <atom:updated>2026-06-12T08:06:00.658Z</atom:updated>
            <content:encoded><![CDATA[<p>For most of my twenties, I have lived in a constant haze of self-stimulation. Constantly reaching for my phone, constantly trying to fill every gap, a new YouTube video, podcasts, doom scrolling on Instagram or Twitter, watching movies while eating, listening to music while taking a walk, or constantly needing to talk to someone, almost like some sort of addiction.</p><p>Even while performing tasks I should otherwise be focused on, there is rarely a moment where my brain isn’t being dosed with something or craving more stimulation. It feels normal, natural even. It creates the illusion of being productive and busy, while in reality, nothing meaningful is getting done.</p><p>In a way, we have optimised away boredom. We actively fill every space with stimulation, constantly engaging in different activities to avoid silence or stillness. I started to question whether my thoughts were really my own anymore. Maybe they were just things I heard from a movie, a tweet, a podcast, or a YouTube video.</p><p>I don’t know if I have original thoughts anymore, thoughts that aren’t borrowed conclusions formed by other people’s opinions. Reviews of movies I had seen before I had enough time to sit with my own feelings. Perspectives were handed to me before I could internalise and fully form my own thoughts.</p><p>Recently, I began noticing how allergic my brain had become to boredom. I became impatient with slow tasks and wanted rapid answers for everything. Instead of allowing myself to experience time, I wanted to consume it constantly.</p><blockquote>“All of humanity’s problems stem from man’s inability to sit quietly in a room alone.” ~ Blaise Pascal’s</blockquote><p>I came across the quote above, and I decided to let myself be bored. Going on walks without my phone. Working without music. Sitting in silence and allowing myself to experience the discomfort of mundane moments instead of immediately escaping them. At first, the silence feels unbearable. Your brain revolts against it. There’s this constant urge to fill the emptiness with noise, stimulation, distraction, anything.</p><p>But something strange started happening.</p><p>I began connecting ideas better. The mental fog slowly reduced. I became clearer in my thinking and more focused during tasks. I got more done in less time. I could describe problems more clearly and think through solutions without immediately outsourcing every thought to AI or external validation. I started noticing mistakes that would normally slip past me. Even creativity slowly returned, and I had forgotten how to come up with things on my own.</p><p>Boredom is a muscle. If you never use it, it atrophies. Eventually, you lose the patience and ability to simply sit with your own thoughts. Your mind begins to revolt against stillness.</p><p>By allowing myself to become bored again, I started reconnecting with my own feelings and thoughts. It reminded me of being a child when my mother would force me to sit down and do homework or chores. Those moments felt painfully boring back then, but they were often more productive than endlessly consuming entertainment or pretending to multitask.</p><p>Maybe that’s why some of our clearest thoughts happen in the shower or during those brief moments when our phones die. For a second, the noise disappears, and clarity slips through.</p><blockquote>The Danish philosopher Søren Kierkegaard once wrote in Either/Or<br>“boredom is the root of all evil and also the root of all great deeds.”</blockquote><p>I think I finally understand what he meant.</p><p>Boredom is not the enemy. It is something we should learn to value and intentionally incorporate into our lives again. This doesn’t mean we should live in boredom, but we should occasionally allow ourselves the space to experience it.</p><p>To walk without music.</p><p>To eat without watching something.</p><p>To sit in silence without immediately reaching for stimulation.</p><p>Because sometimes, boredom is where we reconnect with ourselves again.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbfcda63ff1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Actual Cost of Using AI as a Software Engineer]]></title>
            <link>https://medium.com/@ademolakolawole/the-actual-cost-of-using-ai-as-a-software-engineer-37dababc48db?source=rss-97299a8a410e------2</link>
            <guid isPermaLink="false">https://medium.com/p/37dababc48db</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Ademola Kolawole]]></dc:creator>
            <pubDate>Tue, 26 May 2026 06:11:15 GMT</pubDate>
            <atom:updated>2026-05-26T06:11:15.288Z</atom:updated>
            <content:encoded><![CDATA[<p>As software engineers, we are often told that the best thing to happen to us was the invention of AI.</p><p>I’ve used AI heavily for the past couple of months in both my workflow and personal projects, and honestly, I can’t deny that it helps. Tasks get done faster, implementations take less time, and sometimes things that would have taken hours now take minutes.</p><p>But I’ve started noticing that it comes at a cost. Not just to my craft, but to my personal growth and overall understanding of what is actually being implemented. Yes, I feel more productive, but I’m starting to question if I truly am. Even when I plan before coding, break down features properly, review generated code, and try to understand what’s happening, I still feel like something is slipping away slowly. It feels like I no longer have full control or confidence over my own code the way I used to.</p><p>The more prompts I write to complete tasks faster, the more code gets generated that I don’t fully understand deeply enough to confidently rebuild from scratch myself and sometimes there’s also the illusion that more work is getting done when in reality a lot of time is spent correcting AI mistakes, restructuring generated code, debugging weird implementations, or trying to force generated solutions to actually fit the architecture of the project properly.</p><p>So while it feels faster initially, part of that speed is artificial. You save time generating code, then spend another chunk of time reviewing, correcting, rewriting, and trying to understand what was generated in the first place, and I think that’s the part that bothers me the most.</p><p>Because the reason I got into programming was never just to generate working code. It was solving problems. Sitting down with something difficult, struggling through it, making mistakes, understanding why something failed, and eventually figuring it out. That process shaped me.</p><p>Now AI removes a lot of that struggle, which sounds great at first, but I’m starting to wonder if it also removes part of the growth that comes with it. Because growth comes from pattern recognition. I’ve noticed myself becoming less patient when solving difficult problems manually. Sometimes my first instinct is no longer “let me think deeply about this,” but “let me prompt this quickly”, and while the answer might work, there’s a difference between using something and truly understanding it.<br> <br>I think that difference matters more than we admit. Software engineering is not just about shipping features fast. It’s about judgment, understanding tradeoffs, knowing why something works, knowing what breaks, and being able to think through problems independently when there’s no perfect answer available.</p><p>That confidence only comes from experience and deep problem-solving.<br> Ironically, while AI makes me faster, I sometimes feel less connected to the actual engineering process itself. And maybe that’s the hidden cost nobody really talks about.</p><p>I don’t think AI is bad. Honestly, I think it’s one of the most useful tools we’ve ever had as engineers. But I also think there’s a dangerous line between using AI as an assistant and slowly depending on it to think for us.<br> Because the scary part is that you still look productive while it’s happening.</p><ul><li>You still ship.</li><li>You still close tickets.</li><li>You still move fast.</li></ul><p>But internally, your ability to reason deeply and solve things independently might slowly be weakening without you noticing it immediately.<br> Maybe the answer isn’t abandoning AI completely.<br> Maybe it’s learning when to slow down and struggle through things ourselves again.<br> Maybe it’s spending more time understanding before generating.</p><p>Because at the end of the day, the goal was never just writing code faster. It was becoming a better engineer, and if AI slowly takes away the part of engineering that actually develops us, then maybe we need to be more careful about how much of the thinking we hand over to it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37dababc48db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part One: Designing and Building a Microservice with Golang, Python, and Clean Architecture]]></title>
            <link>https://medium.com/@ademolakolawole/part-one-designing-and-building-a-microservice-with-golang-python-and-clean-architecture-30c03c821a96?source=rss-97299a8a410e------2</link>
            <guid isPermaLink="false">https://medium.com/p/30c03c821a96</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[microservice-architecture]]></category>
            <dc:creator><![CDATA[Ademola Kolawole]]></dc:creator>
            <pubDate>Mon, 13 Jan 2025 19:37:11 GMT</pubDate>
            <atom:updated>2025-01-15T16:26:35.463Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VcrK7t0wQFbH2vJkcEZO0w.png" /></figure><h3>Introduction</h3><blockquote>💡 I started learning Go three years ago as a second programming language, seeking a scalable, efficient, and versatile technology with great potential. Since then, I’ve been captivated by its power and simplicity. Realio reflects my passion for creating feature-rich applications that not only simulate real-world use cases but also serve as learning experiences for myself and others.</blockquote><h3>What is Realio?</h3><p>Realio is an innovative property management and investment platform designed to transform the real estate industry. Inspired by leading solutions like Zillow and Airbnb, it enables seamless property exploration, personalized recommendations, and efficient appointment scheduling. Built with a robust microservices architecture, Realio ensures unparalleled scalability, maintainability, and performance, making it the go-to platform for users and agents.</p><h3>Why Golang for Realio?</h3><p>Golang, or Go, is an open-source programming language developed and supported by Google. It is designed for simplicity, scalability, and high performance, making it an excellent choice for building modern, distributed systems like Realio.</p><ul><li><strong>Adoption by Big Tech:</strong> Companies like Google, Netflix, Dropbox, Uber, Meta, and Twitch leverage Go for cloud and network services, web applications, and command-line tools.</li><li><strong>Ease of Use:</strong> Go’s straightforward syntax and rich standard library make it beginner-friendly while offering advanced capabilities.</li><li><strong>Performance:</strong> Its compiled nature ensures fast execution, while concurrency primitives like goroutines and channels simplify building scalable, high-performance applications.</li></ul><h3>Why Microservices?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SWRt50N9Cozmjs60jBYGww.gif" /><figcaption>Monolithic vs Microservice Architecture</figcaption></figure><p>Microservices architecture divides a complex application into smaller, autonomous services, each focusing on specific functionalities. This approach offers:</p><ol><li><strong>Scalability:</strong> Services can scale independently to handle varying loads.</li><li><strong>Resilience:</strong> Failures in one service do not impact others, ensuring system reliability.</li><li><strong>Flexibility:</strong> Teams can choose the most suitable technologies for individual services.</li><li><strong>Faster Development:</strong> Independent services allow parallel development, accelerating delivery cycles.</li></ol><h3>System Requirements</h3><h3>Objective</h3><p>To deliver a scalable, user-friendly property management solution that caters to:</p><ol><li><strong>Property Listings:</strong> Streamlined CRUD operations with advanced filtering options.</li><li><strong>User Interactions:</strong> AI-powered recommendations, real-time messaging, and instant notifications.</li><li><strong>High Traffic Management:</strong> Support millions of daily users with optimal performance.</li></ol><h3>Functional Requirements</h3><h3>For Customers:</h3><ul><li>Advanced property search and filtering.</li><li>Seamless booking and management of property viewings.</li><li>Personalized notifications for updates and reminders.</li></ul><h3>For Agents:</h3><ul><li>Easy property listing management.</li><li>Comprehensive tracking of customer appointments.</li><li>Real-time communication with potential buyers or renters.</li></ul><h3>Non-Functional Requirements</h3><ul><li><strong>Performance:</strong> Maintain low latency under high traffic conditions.</li><li><strong>Reliability:</strong> Ensure minimal downtime with robust failover mechanisms.</li><li><strong>Security:</strong> Implement best practices to safeguard user data.</li><li><strong>Usability:</strong> Offer an intuitive and accessible interface across devices.</li></ul><h3>Architectural Principles</h3><h3>Clean Architecture</h3><p>Clean Architecture is a design approach that emphasizes the separation of concerns, making software more maintainable, testable, and scalable. It organizes code into distinct layers, each with specific responsibilities, ensuring that the business logic remains independent of frameworks, databases, and external systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SZet46uljVminqT1GJH5gA.png" /></figure><h3>Core Principles:</h3><ol><li><strong>Separation of Concerns:</strong></li></ol><ul><li>Each layer focuses on a specific aspect of the application, avoiding overlap and reducing dependencies between them.</li></ul><p><strong>2. Dependency Inversion:</strong></p><ul><li>High-level modules (e.g., business rules) do not depend on low-level modules (e.g., frameworks). Instead, both depend on abstractions, implemented in the outer layers.</li></ul><p><strong>3. Testability:</strong></p><ul><li>By isolating business logic and abstracting external dependencies, the core functionality can be easily tested without requiring access to databases, APIs, or frameworks.</li></ul><p><strong>4. Independence:</strong></p><ul><li><strong>Framework Independence:</strong> The architecture does not depend on specific frameworks. Frameworks are treated as tools, not the foundation.</li><li><strong>UI Independence:</strong> The user interface can change without affecting the core business logic.</li><li><strong>Database Independence:</strong> The core application logic is not tied to a specific database or storage system.</li></ul><h3>Layered Design:</h3><p>Clean Architecture organizes the application into concentric circles, with each layer encapsulating a different level of responsibility:</p><ol><li><strong>Entities (Core Business Rules):</strong></li></ol><ul><li>These are the most abstract and stable parts of the application.</li><li>Define business rules, policies, and domain objects (e.g., Property, User, Booking).</li><li>Example: A Property the entity might have attributes like name, price, location, and methods for domain-specific logic such as calculateTax().</li></ul><p><strong>2. Use Cases (Application Logic):</strong></p><ul><li>Contain application-specific business rules.</li><li>Coordinate between entities and orchestrate workflows.</li><li>Example: A ScheduleViewing use case might validate user permissions, check property availability, and notify the agent.</li></ul><p><strong>3. Interface Adapters:</strong></p><ul><li>Convert data between the use case and the external systems (e.g., APIs, databases, UI).</li><li>Example: An PropertyRepository adapter transforms database rows into Property domain objects.</li></ul><p><strong>4. Frameworks and Drivers:</strong></p><ul><li>The outermost layer includes frameworks, libraries, and tools.</li><li>Example: A REST controller or gRPC handler interacts with use cases but does not contain business logic.</li></ul><h3>Realio Application of Clean Architecture:</h3><ul><li><strong>Entities:</strong> Represent domain models like Property and User with core business logic (e.g., validation, computation).</li><li><strong>Use Cases:</strong> Manage workflows like GetPersonalizedRecommendations and BookPropertyViewing.</li><li><strong>Interface Adapters:</strong> Handle communication between the use cases and external systems like PostgreSQL or Kafka.</li><li><strong>Frameworks and Drivers:</strong> Incorporate tools such as Gin for HTTP handling, Kafka for messaging, and gRPC for inter-service communication.</li></ul><h3>Key Benefits for Realio:</h3><ol><li><strong>Flexibility:</strong> It’s Easy to switch frameworks or databases without impacting the core logic.</li><li><strong>Scalability:</strong> Allows independent scaling of services or components.</li><li><strong>Maintainability:</strong> Well-defined layers make it easier to understand and modify specific parts of the system.</li><li><strong>Testing:</strong> Clear boundaries make unit testing the core logic straightforward.</li></ol><h3>Example: Booking a Property</h3><p><strong>Entities Layer:</strong> Define an Booking entity with fields like propertyID, userID, status, and methods for validation.</p><p><strong>Use Case Layer:</strong> Implement a BookProperty use case that:</p><ul><li>Check if the property is available.</li><li>Updates the booking status.</li><li>Triggers an event in Kafka for notifications.</li></ul><p><strong>Interface Adapters Layer:</strong> Create a repository for Booking that interacts with PostgreSQL.</p><p><strong>Frameworks Layer:</strong> Use a Gin HTTP handler to expose the BookProperty use case via a REST API.</p><h3>Microservices Communication</h3><ol><li><strong>gRPC:</strong> For high-performance, binary-based inter-service communication.</li><li><strong>Kafka:</strong> Enables event-driven architecture with asynchronous messaging for real-time updates.</li></ol><h3>Core Technologies</h3><h3>Backend Development</h3><ul><li><strong>Go:</strong> High-performance services for user management and property operations.</li><li><strong>Python:</strong> Advanced data processing and recommendation services leveraging libraries like Scikit-learn.</li></ul><h3>Communication and Event-Driven Architecture</h3><ul><li><strong>gRPC:</strong> Efficient protocol for inter-service requests.</li><li><strong>Kafka:</strong> Handles asynchronous data streaming for events like bookings and notifications.</li></ul><h3>Databases and Caching</h3><ul><li><strong>PostgreSQL:</strong> Reliable, relational database for structured data.</li><li><strong>MongoDB:</strong> NoSQL database that can handle large amounts of data and it can also handle heavy writing and reading.</li><li><strong>Redis:</strong> In-memory caching to enhance response times.</li><li><strong>Elasticsearch:</strong> Optimized search engine for complex property filtering.</li></ul><h3>Infrastructure and DevOps</h3><ul><li><strong>Docker:</strong> Containerization for consistent deployments.</li><li><strong>Kubernetes:</strong> Orchestration of containerized services for scalability and fault tolerance.</li><li><strong>Prometheus &amp; Grafana:</strong> Real-time monitoring and visualization.</li><li><strong>Open-Telemetry:</strong> Directly measure the performance and behaviour of your software and send this data to observability platforms.</li></ul><h3>High-Level Design</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*okAXOGYS3y48FwR9s1o1TA.png" /><figcaption>System Design With Go and Python Microservice</figcaption></figure><ol><li><strong>API Gateway:</strong> Single entry point for routing, authentication, and rate limiting.</li><li><strong>Service Communication:</strong> Combines gRPC for synchronous calls and Kafka for event-driven processes.</li><li><strong>Database Layer:</strong> Distributed PostgreSQL and Redis for fast, reliable data storage and retrieval.</li><li><strong>Event Streaming:</strong> Kafka streams enable real-time updates and notifications.</li></ol><h3>Low-Level Design</h3><ol><li><strong>Caching Strategy:</strong> Redis caches frequently accessed data.</li><li><strong>Service Discovery:</strong> API Gateway dynamically routes requests to available service instances.</li><li><strong>Data Flow:</strong> Example: A booking triggers events for notifications and updates the recommendation engine.</li></ol><h3>Key Features</h3><h3>Personalized Recommendations</h3><ul><li>Machine learning models trained on Scikit-learn.</li><li>Real-time updates based on user interactions.</li></ul><h3>Real-Time Messaging</h3><ul><li>WebSockets enable instant communication between customers and agents.</li></ul><h3>Advanced Search Filters</h3><ul><li>Elasticsearch powers lightning-fast queries and complex filters.</li></ul><h3>Infrastructure and Deployment</h3><h3>DevOps Stack</h3><ul><li><strong>CI/CD Pipelines:</strong> Automates testing, deployment, and scaling.</li><li><strong>Containerization:</strong> Docker ensures consistent environments.</li><li><strong>Monitoring Tools:</strong> Prometheus tracks metrics; Grafana visualizes real-time data.</li></ul><h3>Monitoring and Maintenance</h3><ol><li><strong>Logging:</strong> Centralized using the ELK stack for detailed analytics.</li><li><strong>Alerting:</strong> Prometheus triggers alerts for performance anomalies.</li></ol><h3>Challenges and Solutions</h3><h3>Scaling Challenges</h3><ul><li><strong>Issue:</strong> Sudden traffic spikes.</li><li><strong>Solution:</strong> Auto-scaling Kubernetes clusters and distributed caching.</li></ul><h3>Data Consistency Across Services</h3><ul><li><strong>Issue:</strong> Ensuring real-time updates across microservices.</li><li><strong>Solution:</strong> Implementing Kafka for event-driven consistency and idempotent operations</li></ul><h3>Future Enhancements</h3><p>In the Next part of this article, We will explore how to set up Clean architecture with Golang, Setting up our Authentication Service.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30c03c821a96" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring gRPC and Flutter for Modern App Development]]></title>
            <link>https://blog.stackademic.com/exploring-grpc-and-flutter-for-modern-app-development-ad2d890bfe95?source=rss-97299a8a410e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad2d890bfe95</guid>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[grpc-client]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Ademola Kolawole]]></dc:creator>
            <pubDate>Mon, 22 Apr 2024 11:44:32 GMT</pubDate>
            <atom:updated>2024-04-26T04:30:19.650Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2xRyPiQg5uQmueVoY6E7Xg.png" /></figure><p>Recent developments have made the demand for more robust and distributed tools that can function across multiple teams increasingly evident. gRPC tools are particularly potent in these scenarios. They can generate server-side code for Golang or Dart and support various server-side languages such as Python, Ruby, Node.js, PHP, and . NET. In addition, they can generate code for client-side languages including Dart, Swift, Objective-C, Java, and Kotlin.</p><p>Utilizing gRPC enables you to outline an API, and generate network and object model code for usage on your server and any client.</p><p>In this tutorial, you’ll learn how to define an API using gRPC and how to use its tools to generate code for server-side Golang and client Flutter apps. You’ll learn how to:</p><ul><li>Read and modify a <strong><em>.proto</em></strong> file that describes an API.</li><li>Use <strong><em>Evans</em></strong> to interact with a gRPC API.</li><li>Use the <strong><em>protoc</em></strong> command line tool to generate Dart code for your Flutter application.</li><li>Communicate directly with gRPC in your Flutter application.</li></ul><p>Note: The server-side code used in this tutorial was built with Go. You can get the code in the <a href="https://github.com/demola234/go_task_grpc"><strong>repository</strong></a>.</p><h3>Getting Started</h3><h3>Installing Evans</h3><p><a href="https://github.com/ktr0731/evans">Evans</a> is the gRPC version to the likes of <a href="https://curl.se/">cURL</a> or <a href="https://insomnia.rest/">Insomnia</a> which allows you to make calls to a server that uses gRPC without having to write an entire client app first. Evans is also a quick way to check a <strong><em>.proto</em></strong> file for errors.</p><p>To install Evans on macOS, you can leverage Homebrew, a package manager for macOS. Follow these steps to install Evans:</p><pre>brew tap ktr0731/evans &amp;&amp; brew install evans</pre><p>After the installation completes, you can verify that Evans is installed correctly by running:</p><pre>evans --version</pre><p><strong>Installing Protoc and the Dart Plugin</strong></p><p>To install Dart SDK: Before installing the Dart plugin, ensure you have the Dart SDK installed on your system. You can download it from the <a href="https://dart.dev/get-dart"><strong><em>Dart Official Website</em></strong></a>.</p><p>To generate the Dart code from a gRPC spec file you need :</p><ul><li><strong><em>The </em></strong><strong><em>protoc executable</em></strong>.</li><li><strong><em>The plug-ins for Dart</em></strong>: one for generating Dart code for Message items and one for generating Service items.</li></ul><p>Make sure you have Dart installed then run:</p><pre>dart pub global activate protoc_plugin</pre><h3>Learning About gRPC</h3><p>gRPC is a technology developed at Google to help you define and maintain an app interface. It has tools and plugins that generate native networking and object model code for the server and client to use with the interface.</p><p>gRPC generates server and client code from the same spec, encoded in a <strong><em>.proto</em></strong> file, regardless of the programming language used.</p><p>Using gRPC is language-agnostic in nature, meaning developers can define the service interface in a .proto file using Protocol Buffers, a language-neutral, platform-neutral mechanism for serializing structured data. gRPC then generates code for various programming languages, allowing developers to work in their preferred language while ensuring consistency across different system components.</p><p>By abstracting away the complexities of network communication, gRPC minimizes the chance of errors caused by the manual implementation of network protocols. It handles tasks such as serialization, deserialization, and network transport, enabling developers to focus on building the core functionality of their applications</p><h3>How is gRPC Different from REST?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0WnPTc3iEVU6oJjlb7ncCQ.png" /><figcaption>image: gRPC vs Rest API</figcaption></figure><h3>Learning the Difference Between gRPC and JSON?</h3><p>For encoding and decoding data objects, gRPC uses <strong><em>Protocol Buffers</em></strong>.</p><p>Unlike the plain text files used by JSON, Protocol Buffers are a binary file type, not human-readable. They enable the exchange of smaller payloads, which are more efficient and suitable for low-bandwidth use cases.</p><p>First, you must define gRPC messages and data models in a <strong><em>.proto</em></strong> file.</p><h3>Working with a .proto File</h3><p>A <strong><em>.proto</em></strong> file is a text file containing definitions for all your APIs. In this tutorial, the domain revolves around <strong><em>Messages</em></strong> and <strong><em>Services</em></strong>. Messages are the data objects that get sent between the client and server. Services define how messages get transported. A <strong><em>.proto</em></strong> file can also have some metadata to help the various code generators.</p><p>Most exciting to anyone who has ever struggled with comments in JSON: a <strong><em>.proto</em></strong> file can have comments! It supports both // style and /* ... */ style comments!</p><p>Open the <strong><em>todo.proto</em></strong> file in the project&#39;s root directory to explore it a bit. The first line of the file specifies the version of gRPC to use. It looks like this:</p><pre>syntax = &quot;proto2&quot;;</pre><p>If this line is missing, the gRPC system will assume that you’re using version 2, not version 3. After that, some options will assist the code generator in naming things.</p><h3>Defining the Services</h3><p>Next, you’ll see the service definition. The rpc entries will each become an function in the generated Dart code.</p><pre>syntax = &quot;proto3&quot;;<br>package pb;<br>service TodoGrpc {<br>    rpc CreateTask(CreateTaskRequest) returns (CreateTaskResponse){}<br>    rpc GetTask(Empty) returns (GetAllTaskResponse){}<br>    rpc DeleteTask(DeleteTaskRequest) returns (Empty){}<br>    rpc UpdateTask(UpdateTaskRequest) returns (UpdateTaskResponse){}<br>}</pre><ol><li><strong>Syntax Declaration</strong>:</li></ol><ul><li><strong>syntax = &quot;proto3&quot;;</strong>: This line specifies the version of Protocol Buffers being used, in this case, proto3. Proto3 is the latest version at the time of writing and offers several improvements over its predecessors.</li></ul><p><strong>2. Package Declaration</strong>:</p><ul><li><strong>package pb;</strong>: The <strong>package</strong> keyword helps in organizing Protocol Buffers files into namespaces. Here, <strong>pb</strong> is the namespace for this service definition.</li></ul><p><strong>3. Service Declaration</strong>:</p><ul><li><strong>service TodoGrpc { ... }</strong>: This block defines a gRPC service named <strong>TodoGrpc</strong>. A gRPC service is essentially a collection of remote methods (also called RPCs) that can be called by clients.</li></ul><p><strong>4. RPCs (Remote Procedure Calls)</strong>:</p><ul><li><strong>rpc CreateTask(CreateTaskRequest) returns (CreateTaskResponse){}</strong>: This line declares an RPC method named <strong>CreateTask</strong> that takes a <strong>CreateTaskRequest</strong> message as input and returns a <strong>CreateTaskResponse</strong> message.</li><li><strong>rpc GetTask(EmptyGetRequest) returns (GetAllTaskResponse){}</strong>: Similarly, this RPC method <strong>GetTask</strong> takes no input (denoted by <strong>Empty</strong>) and returns a <strong>GetAllTaskResponse</strong>.</li><li><strong>rpc DeleteTask(DeleteTaskRequest) returns (Empty){}</strong>: This RPC method <strong>DeleteTask</strong> takes a <strong>DeleteTaskRequest</strong> and returns an <strong>EmptyTaskRequest</strong>.</li><li><strong>rpc UpdateTask(UpdateTaskRequest) returns (UpdateTaskResponse){}</strong>: Lastly, this RPC method <strong>UpdateTask</strong> takes an <strong>UpdateTaskRequest</strong> and returns an <strong>UpdateTaskResponse</strong>.</li></ul><h3>Defining the Messages</h3><p>Here is the message spec for the Task object:</p><pre>syntax = &quot;proto3&quot;;<br>package pb;</pre><ul><li><strong>CreateTaskRequest</strong>:</li></ul><pre>message CreateTaskRequest {<br>    string task_name = 1;<br>    string task_description = 2;<br>    string task_deadline = 3;<br>    optional string task_status = 4;<br>    optional string task_priority = 5;<br>    optional google.protobuf.Timestamp task_createdAt = 6;<br>}</pre><ul><li>Defines a message used to create a new task. It includes fields for task name, description, deadline, status, priority, and creation timestamp.</li></ul><p><strong>CreateTaskResponse</strong>:</p><pre>message CreateTaskResponse {<br>    string task_name = 1;<br>    string task_description = 2;<br>    string task_deadline = 3;<br>    optional string task_status = 4;<br>    optional string task_priority = 5;<br>    google.protobuf.Timestamp task_createdAt = 6;<br>    optional google.protobuf.Timestamp task_updatedAt = 7;<br>}</pre><ul><li>Represents the response after creating a task. It contains similar fields to CreateTaskRequest, along with an optional field for the updated timestamp.</li></ul><p>Task:</p><pre>message Task {<br>    string task_name = 1;<br>    optional string task_description = 2;<br>    optional string task_deadline = 3;<br>    optional string task_status = 4;<br>    optional string task_priority = 5;<br>    optional google.protobuf.Timestamp task_createdAt = 6;<br>    optional google.protobuf.Timestamp task_updatedAt = 7;<br>}</pre><p>Represents a task entity with fields like name, description, deadline, status, priority, and timestamps for creation and update.</p><ul><li><strong>Empty</strong>:</li></ul><pre>message Empty {}</pre><p>Represents an empty message, often used as a placeholder or to indicate a lack of data.</p><ul><li><strong>GetAllTaskResponse</strong>:</li></ul><pre>message GetAllTaskResponse {<br>    repeated Task tasks = 1;<br>}</pre><p>Represents a response containing multiple tasks. It includes a repeated field of type <strong>Task</strong>.</p><ul><li><strong>DeleteTaskRequest</strong>:</li></ul><pre>message DeleteTaskRequest {<br>    int64 id = 1;<br>}</pre><p>Represents a request to delete a task identified by its ID.</p><ul><li><strong>UpdateTaskRequest</strong>:</li></ul><pre>message UpdateTaskRequest {<br>    int64 id = 1;<br>    string title = 2;<br>    optional string description = 3;<br>    optional string task_status = 4;<br>    optional string task_priority = 5;<br>}</pre><p>Represents a request to update a task. It includes fields for task ID, title, description, status, and priority.</p><ul><li><strong>UpdateTaskResponse</strong>:</li></ul><pre>message UpdateTaskResponse {<br>    Task task = 1;<br>}</pre><p>Represents the response after updating a task. It contains the updated <strong>Task</strong> entity.</p><p>The first field is marked as optional. It won’t have a value until it’s been stored in the database. The code generator keeps track of each field in a message by assigning it a number.</p><p>In addition to the string type, a field can be many different <a href="https://developers.google.com/protocol-buffers/docs/proto#scalar">scalar types</a> and each language generator will make the appropriate translations. Fields can be enumerations or even other messages.</p><p>The repeated keyword means that the code will generate an array of Taskss. You can learn more about the different options in the <a href="https://developers.google.com/protocol-buffers/docs/proto3">proto3 language guide</a>.</p><p>Google provides many well-known types including: Empty, Timestamp, BoolValue and many more. You can <a href="https://developers.google.com/protocol-buffers/docs/reference/google.protobuf">read the documentation</a> to learn about them. Since the homebrew version of protoc isn’t bundled with them, this tutorial uses a custom one. Both strategies, using Google’s or making your own, are common.</p><h3>Exercising a .proto File With Evans</h3><p>In a Terminal window, navigate to the root directory of the project. This is the directory that contains the <strong><em>to-do.proto</em></strong> file. Launch Evans in REPL mode using this command:</p><pre>evans repl --host localhost --port 1234 --proto ./todo.proto</pre><p>You’ll see the Evans prompt, similar to this:</p><pre>  ______<br> |  ____|<br> | |__    __   __   __ _   _ __    ___<br> |  __|   \ \ / /  / _. | | &#39;_ \  / __|<br> | |____   \ V /  | (_| | | | | | \__ \<br> |______|   \_/    \__,_| |_| |_| |___/<br><br> more expressive universal gRPC client</pre><pre>pb.TodoGrpc@localhost:9090&gt;</pre><p>Even though you don’t have a running gRPC server yet and haven’t generated the gRPC Golang code, Evans uses the <strong><em>todo.proto</em></strong> file to provide information about the services.</p><p>Recall from the <strong><em>todo.proto</em></strong> file that you have four messages:</p><p>Now type the following command in the Evans prompt:</p><pre>show message</pre><p>You’ll see the four defined messages, like this:</p><pre>+--------------------+<br>|      MESSAGE       |<br>+--------------------+<br>| CreateTaskRequest  |<br>| CreateTaskResponse |<br>| DeleteTaskRequest  |<br>| Empty              |<br>| GetAllTaskResponse |<br>| UpdateTaskRequest  |<br>| UpdateTaskResponse |<br>+--------------------+</pre><p>Now type show service to see the list of services. Evans will show:</p><pre>+----------+------------+-------------------+--------------------+<br>| SERVICE  |    RPC     |   REQUEST TYPE    |   RESPONSE TYPE    |<br>+----------+------------+-------------------+--------------------+<br>| TodoGrpc | CreateTask | CreateTaskRequest | CreateTaskResponse |<br>| TodoGrpc | GetTask    | Empty             | GetAllTaskResponse |<br>| TodoGrpc | DeleteTask | DeleteTaskRequest | Empty              |<br>| TodoGrpc | UpdateTask | UpdateTaskRequest | UpdateTaskResponse |<br>+----------+------------+-------------------+--------------------+</pre><p>To close Evans and return to Terminal type: exit.</p><p>You are on the right track. The next step is to generate some Dart code.</p><h3>Generating Dart Code From a .proto file</h3><p>Make sure the Terminal is in the directory with the <strong><em>todo.proto</em></strong> file and type the following:</p><pre>protoc --dart_out=grpc:lib/core/proto/generate \\<br> -Ilib/core/proto lib/core/proto/*.proto</pre><h3>Working with proto in your flutter application</h3><p>First Create a new Flutter project name with</p><pre>Flutter create todogrpc</pre><p>Then add the following packages and import the necessary for working with gRPC in Flutter:</p><pre>dependencies:<br>  protobuf: ^latest<br>  get_it: ^latest<br>  grpc: ^latest<br>  dartz: ^latest<br>  flutter_riverpod: ^latest<br>  fixnum: ^latest<br><br> dev_dependencies:<br>  freezed: ^latest</pre><ol><li><strong>protobuf</strong>: This package provides support for Protocol Buffers, a method of serializing structured data. It’s commonly used for efficient communication between services in distributed systems.</li><li><strong>get_it</strong>: <strong>get_it</strong> is a simple yet powerful dependency injection framework for Dart and Flutter. It allows for loosely coupling components in an application by providing a way to obtain instances of dependencies without directly referencing them.</li><li><strong>grpc</strong>:<strong>grpc</strong> is a package that allows Dart applications to communicate with gRPC (Remote Procedure Call) servers. It provides tools for generating client and server code from protobuf service definitions, enabling seamless communication between different services.</li><li><strong>dartz</strong>: <strong>dartz</strong> is a functional programming library for Dart. It provides utilities for working with common functional programming concepts such as Option, Either, Try, and more. It helps in writing more concise and expressive code, especially in asynchronous and error-prone scenarios.</li><li><strong>flutter_riverpod</strong>: <strong>flutter_riverpod</strong> is a state management library for Flutter, built on top of the Provider package. It offers a simple and flexible way to manage application state, dependencies, and UI updates, making it easier to build scalable and maintainable Flutter applications.</li><li><strong>freezed</strong>: <strong>freezed</strong> is a code generation library for Dart and Flutter that simplifies creating immutable classes. Based on annotated classes, it automatically generates boilerplate code for value equality, copyWith methods, and more. This helps in reducing code verbosity and ensuring type safety.</li></ol><p>Create a new file called <strong>grpc_handler.dart</strong> under your server folder and define your <strong>GrpcHandlerService</strong> Class</p><pre>import &#39;../proto/generate/todo.pbgrpc.dart&#39;;<br>import &#39;package:grpc/grpc.dart&#39;;<br>class GrpcHandlerService {<br>  late TodoGrpcClient client;<br><br>static final GrpcHandlerService _grpcHandlerService =<br>      GrpcHandlerService._internal();<br><br>factory GrpcHandlerService() {<br>    return _grpcHandlerService;<br>  }<br><br> GrpcHandlerService._internal();<br><br> static Future&lt;GrpcHandlerService&gt; init() async {<br>    final channel = ClientChannel(&#39;localhost&#39;,<br>        port: 9090,<br>        options: const ChannelOptions(<br>          credentials: ChannelCredentials.insecure(),<br>          idleTimeout: Duration(minutes: 30),<br>        ));<br><br>try {<br>      await channel.getConnection();<br><br> _grpcHandlerService.client = TodoGrpcClient(channel,<br>          options: CallOptions(<br>            timeout: const Duration(minutes: 30),<br>          ));<br>    } catch (e) {<br>      print(&#39;unable to conntect&#39;);<br>      rethrow;<br>    }<br><br> return GrpcHandlerService();<br>  }<br>}</pre><ol><li><strong>GrpcHandlerService Class</strong>:</li></ol><ul><li>This class is responsible for handling gRPC communication.</li><li>It contains a late-initialized instance variable <strong>client</strong> of type <strong>TodoGrpcClient</strong>. The <strong>client</strong> will be initialized later after creating a gRPC channel.</li><li>It also defines a private constructor <strong>_internal()</strong> and a factory constructor <strong>GrpcHandlerService()</strong>. The factory constructor returns a single instance of <strong>GrpcHandlerService</strong> using a Singleton pattern.</li><li>There’s a static method <strong>init()</strong> which is used to initialize the <strong>GrpcHandlerService</strong>. It returns a Future that completes with an instance of <strong>GrpcHandlerService</strong>.</li></ul><p>2. <strong>init() Method</strong>:</p><ul><li>Inside the <strong>init()</strong> method, a gRPC <strong>ClientChannel</strong> is created with the address <strong>&#39;localhost&#39;</strong> and port <strong>9090</strong>. The channel is configured with insecure credentials and an idle timeout of 30 minutes.</li><li>A connection to the channel is established using <strong>channel.getConnection()</strong>.</li><li>If the connection is successful, a <strong>TodoGrpcClient</strong> is created using the initialized channel and call options with a timeout of 30 minutes.</li><li>If an error occurs during initialization, it is caught, printed, and rethrown.</li><li>Finally, an instance <strong>GrpcHandlerService</strong> is returned.</li></ul><p>Create a new <strong>folder</strong> called <strong>failures</strong> and add your file <strong>failure.dart</strong></p><p>This used to be used to handle our various failure case</p><pre>import &#39;package:freezed_annotation/freezed_annotation.dart&#39;;<br>part &#39;failure.freezed.dart&#39;;<br><br>@freezed<br>class Failure with _$Failure {<br>  const factory Failure.failure(final String message) = _Failure;<br>  const factory Failure.notFoundFailure(final String message) = _NotFoundFailure;<br>  const factory Failure.errorFailure(final String message) = _ErrorFailure;<br>}</pre><p>Run the following command in your terminal to generate your failure freezed class:</p><p>Create a new file called <strong>gapi.dart</strong> under your <strong>server</strong> folder and define your Abstract <strong>Class </strong><strong>TodoFacade</strong> and implement your functions in <strong>ITodoFacade</strong></p><pre>import &#39;package:dartz/dartz.dart&#39;;<br><br>import &#39;../../error/failure.dart&#39;;<br>import &#39;../../proto/generate/todo.pb.dart&#39; as $pb;<br>import &#39;../grpc_handler.dart&#39;;<br><br>abstract class TodoFacade {<br>  Future&lt;Either&lt;Failure, Unit&gt;&gt; createTodo(<br>      $pb.CreateTaskRequest createTaskRequest);<br>  Future&lt;Either&lt;Failure, Unit&gt;&gt; updateTodo(<br>      $pb.UpdateTaskRequest updateTaskRequest);<br>  Future&lt;Either&lt;Failure, Unit&gt;&gt; deleteTodo(<br>      $pb.DeleteTaskRequest deleteTaskRequest);<br><br>  Future&lt;Either&lt;Failure, $pb.GetAllTaskResponse&gt;&gt; listTodo();<br>}<br><br>class ITodoFacade implements TodoFacade {<br>  final GrpcHandlerService _grpcHandlerService;<br><br>  ITodoFacade(this._grpcHandlerService);<br><br>  @override<br>  Future&lt;Either&lt;Failure, Unit&gt;&gt; createTodo(<br>      $pb.CreateTaskRequest createTaskRequest) async {<br>    final response =<br>        await _grpcHandlerService.client.createTask(createTaskRequest);<br><br>    if (response.isInitialized()) {<br>      return right(unit);<br>    } else {<br>      return left(const Failure.errorFailure(&#39;An Error Occurred&#39;));<br>    }<br>  }<br><br>  @override<br>  Future&lt;Either&lt;Failure, Unit&gt;&gt; deleteTodo(<br>      $pb.DeleteTaskRequest deleteTaskRequest) async {<br>    final response =<br>        await _grpcHandlerService.client.deleteTask(deleteTaskRequest);<br><br>    if (response.isInitialized()) {<br>      return right(unit);<br>    } else {<br>      return left(const Failure.errorFailure(&#39;An Error Occurred&#39;));<br>    }<br>  }<br><br>  @override<br>  Future&lt;Either&lt;Failure, $pb.GetAllTaskResponse&gt;&gt; listTodo() async {<br>    print(_grpcHandlerService.client.getTask($pb.EmptyGetRequest()));<br>    final response =<br>        await _grpcHandlerService.client.getTask($pb.EmptyGetRequest());<br><br>     if (response.isInitialized()) {<br>      return right(response);<br>    } else {<br>      return left(const Failure.errorFailure(&#39;An Error Occurred&#39;));<br>    }<br>  }<br><br>  @override<br>  Future&lt;Either&lt;Failure, Unit&gt;&gt; updateTodo(<br>      $pb.UpdateTaskRequest updateTaskRequest) async {<br>    final response =<br>        await _grpcHandlerService.client.updateTask(updateTaskRequest);<br><br>    if (response.isInitialized()) {<br>      return right(unit);<br>    } else {<br>      return left(const Failure.errorFailure(&#39;An Error Occurred&#39;));<br>    }<br>  }<br>}</pre><ol><li><strong>Imports</strong>:</li></ol><ul><li><strong>dartz</strong>: Importing Dartz library which provides functional programming constructs <strong>Either</strong> for error handling.</li><li><strong>failure.dart</strong>: Importing a custom <strong>Failure</strong> class which represents various failure scenarios in the application.</li><li><strong>todo.pb.dart</strong>: Importing generated protobuf classes which define request and response message types for Todo tasks.</li><li><strong>grpc_handler.dart</strong>: Importing a custom <strong>GrpcHandlerService</strong> class which handles gRPC communication.</li></ul><p>2. <strong>TodoFacade Abstract Class</strong>:</p><ul><li>Declares four abstract methods representing CRUD operations for Todo tasks: <strong>createTodo</strong>, <strong>updateTodo</strong>, <strong>deleteTodo</strong>, and <strong>listTodo</strong>.</li></ul><p>3. <strong>ITodoFacade Class</strong>:</p><ul><li>Implements the <strong>TodoFacade</strong> abstract class.</li><li>Takes an instance of <strong>GrpcHandlerService</strong> in its constructor for handling gRPC communication.</li><li>Implements each abstract method using gRPC client methods provided by <strong>GrpcHandlerService</strong>.</li></ul><p>4. <strong>createTodo Method</strong>:</p><ul><li>Calls the <strong>createTask</strong> method of the gRPC client to create a new Todo task.</li><li>Checks if the response is successful (frozen) and returns <strong>Right(unit)</strong> indicating success otherwise returns a <strong>Failure</strong> with an error message.</li></ul><p>5. <strong>deleteTodo Method</strong>:</p><ul><li>Calls the <strong>deleteTask</strong> method of the gRPC client to delete a Todo task.</li><li>Similar to <strong>createTodo</strong>, checks if the response is successful and returns appropriate <strong>Either</strong> result.</li></ul><p>6. <strong>listTodo Method</strong>:</p><ul><li>Calls the <strong>getTask</strong> method of the gRPC client to fetch all Todo tasks.</li><li>Returns the response as <strong>Right(response)</strong> if successful, else returns a <strong>Failure</strong>.</li></ul><p>7. <strong>updateTodo Method</strong>:</p><ul><li>Calls the <strong>updateTask</strong> method of the gRPC client to update a Todo task.</li><li>Similar to <strong>createTodo</strong> and <strong>deleteTodo</strong>, checks if the response is successful and returns the appropriate <strong>Either</strong> result.</li></ul><p>Creates a global instance <strong>sl</strong> of <strong>GetIt</strong> by accessing the <strong>I</strong> static member. This instance will be used for registering and retrieving dependencies throughout the application.</p><p>Implement State Management, For this Article we will be using Riverpod to Handle our states:</p><pre>import &#39;package:freezed_annotation/freezed_annotation.dart&#39;;<br>import &#39;core/proto/generate/todo.pb.dart&#39;;<br><br>part &#39;todo_states.freezed.dart&#39;;<br><br>@freezed<br>class TodoState with _$TodoState {<br>  const factory TodoState.initial() = _Initial;<br>  const factory TodoState.loading() = _Loading;<br>  const factory TodoState.getTodo({required GetAllTaskResponse data}) =<br>      _Success;<br>  const factory TodoState.error({required String message}) = _Error;<br>}</pre><p>Run the following command in your terminal to generate your Todo States class:</p><pre>dart run build_runner build</pre><p>Now Let&#39;s Implement our StateManagement with Riverpod</p><pre>import &#39;package:flutter_riverpod/flutter_riverpod.dart&#39;;<br>import &#39;core/grpc/api/todo.dart&#39;;<br>import &#39;core/injector/injector.dart&#39;;<br>import &#39;core/proto/generate/todo.pb.dart&#39;;<br>import &#39;todo_states.dart&#39;;<br><br>class TodoNotifier extends StateNotifier&lt;TodoState&gt; {<br>  TodoNotifier() : super(const TodoState.initial()){<br>  getTodo();<br>  }<br><br>  final todoList = sl&lt;TodoFacade&gt;();<br><br>  getTodo() async {<br>    final todo = await todoList.listTodo();<br><br>    todo.fold((l) {<br>      state = TodoState.error(message: l.message);<br>    }, (r) {<br>      state = TodoState.getTodo(data: r);<br>    });<br>  }<br><br>  createTodo({required CreateTaskRequest createTaskRequest}) async {<br>    state = const TodoState.loading();<br><br>    final todoList = sl&lt;TodoFacade&gt;();<br><br>    final todo = await todoList.createTodo(createTaskRequest);<br><br>    todo.fold((l) {<br>      state = TodoState.error(message: l.message);<br>    }, (r) {<br>      getTodo();<br>    });<br>  }<br><br>  updateTodo({required UpdateTaskRequest updateTaskRequest}) async {<br>    state = const TodoState.loading();<br><br>    final todoList = sl&lt;TodoFacade&gt;();<br><br>    final todo = await todoList.updateTodo(updateTaskRequest);<br><br>todo.fold((l) {<br>      state = TodoState.error(message: l.message);<br>    }, (r) {<br>      getTodo();<br>    });<br>  }<br><br>  deleteTodo({required DeleteTaskRequest deleteTaskRequest}) async {<br>    state = const TodoState.loading();<br><br>final todoList = sl&lt;TodoFacade&gt;();<br><br>final todo = await todoList.deleteTodo(deleteTaskRequest);<br><br><br>todo.fold((l) {<br>      state = TodoState.error(message: l.message);<br>    }, (r) {<br>      getTodo();<br>    });<br>  }<br>}</pre><p>Create Your Provider for <strong>StateNotifier</strong></p><pre>final todoNotifierProvider =<br>    StateNotifierProvider&lt;TodoNotifier, TodoState&gt;((ref) =&gt; TodoNotifier());</pre><p>Now in our <strong>main.dart</strong> to build a simple UI</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter/services.dart&#39;;<br>import &#39;package:flutter_riverpod/flutter_riverpod.dart&#39;;<br>import &#39;core/injector/injector.dart&#39;;<br>import &#39;core/localization/generated/strings.dart&#39;;<br>import &#39;core/proto/generate/google/protobuf/timestamp.pb.dart&#39;;<br>import &#39;core/proto/generate/todo.pbgrpc.dart&#39;;<br>import &#39;todo_notifier.dart&#39;;<br><br>void main() async {<br>  WidgetsFlutterBinding.ensureInitialized();<br>  SystemChrome.setPreferredOrientations(<br>      [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);<br><br>  await injector();<br>  runApp(const ProviderScope(child: MyHomePage()));<br>}<br><br>class MyHomePage extends ConsumerStatefulWidget {<br>  const MyHomePage({super.key});<br><br> @override<br>  ConsumerState&lt;MyHomePage&gt; createState() =&gt; _MyHomePageState();<br>}<br><br>class _MyHomePageState extends ConsumerState&lt;MyHomePage&gt; {<br>  @override<br>  void initState() {<br>    super.initState();<br>    ref.read(todoNotifierProvider.notifier).getTodo();<br>  }<br><br>@override<br>  Widget build(BuildContext context) {<br>    return<br>    MaterialApp(<br>        title: &#39;gRPC Demo&#39;,<br>        debugShowCheckedModeBanner: false,<br>      home: const Scaffold(<br>      appBar: AppBar(<br>        backgroundColor: Theme.of(context).colorScheme.inversePrimary,<br>        title: Text(&quot;gRPC Demo&quot;),<br>        centerTitle: true,<br>      ),<br>      body: Column(<br>        mainAxisSize: MainAxisSize.min,<br>        children: [<br>          ref.watch(todoNotifierProvider).maybeWhen(<br>            orElse: () {<br>              return const CircularProgressIndicator();<br>            },<br>            loading: () {<br>              return const Center(child: CircularProgressIndicator());<br>            },<br>            getTodo: (data) {<br>              return Expanded(<br>                child: ListView.builder(<br>                    itemCount: data.tasks.length,<br>                    itemBuilder: (context, index) {<br>                      return ListTile(<br>                        title: Text(data.tasks[index].taskName),<br>                        onLongPress: () {<br>                          ref.read(todoNotifierProvider.notifier).deleteTodo(<br>                              deleteTaskRequest: DeleteTaskRequest(<br>                                  id: data.tasks[index].taskId));<br>                        },<br>                        subtitle: Text(data.tasks[index].taskDescription),<br>                      );<br>                    }),<br>              );<br>            },<br>            error: (error) {<br>              return Text(error.toString());<br>            },<br>          ),<br>        ],<br>      ),<br>      floatingActionButton: FloatingActionButton(<br>        onPressed: () {<br>          // Add dummy todo to the list<br><br>          DateTime currentDate = DateTime.now(); //DateTime<br><br>          ref.read(todoNotifierProvider.notifier).createTodo(<br>              createTaskRequest: CreateTaskRequest(<br>                  taskName: &#39;Hello&#39;,<br>                  taskCreatedAt: Timestamp.fromDateTime(currentDate),<br>                  taskDeadline: &#39;Tomorrow&#39;,<br>                  taskDescription: &#39;A short Tasks&#39;,<br>                  taskPriority: &#39;High&#39;,<br>                  taskStatus: &#39;Not Started&#39;));<br>        },<br>            tooltip: &quot;Add Todo&quot;,<br>            child: const Icon(Icons.add),<br>          ),<br>          ),<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><p>Let&#39;s run our Flutter App</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*rD13TvXkYumF9_F_Fy-BeA.gif" /><figcaption>gRPC UI Demo</figcaption></figure><h3>Where to Go from Here?</h3><p>In this tutorial, you learned the basics of working with a <strong><em>.proto</em></strong> file to describe a gRPC API. You also learned how to generate Dart code using <strong><em>protoc</em></strong> and how to modify a Flutter app to use gRPC instead of HTTP.</p><p>The GitHub projects for <strong><em>protobuf</em></strong>, <strong><em>grpc-dart</em></strong> and <strong><em>protoc</em></strong> all contain more documentation and tutorials:</p><ul><li><a href="https://github.com/protocolbuffers/protobuf">Protobuf github project</a></li><li><a href="https://github.com/fullstorydev/grpcui">Official gRPC_dart Example</a></li><li><a href="https://protobuf.dev/programming-guides/proto3/">Official gRPC Proto3 Guide</a></li></ul><p>THANK YOU FOR VIEWING!</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><strong> | </strong><a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><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><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</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=ad2d890bfe95" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/exploring-grpc-and-flutter-for-modern-app-development-ad2d890bfe95">Exploring gRPC and Flutter for Modern App Development</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[Taming the Dependencies: Mastering Dependency Injection in Go with Uber Fx]]></title>
            <link>https://medium.com/@ademolakolawole/taming-the-dependencies-mastering-dependency-injection-in-go-with-uber-fx-b3c3600e822d?source=rss-97299a8a410e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3c3600e822d</guid>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[dependency-inversion]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[uber-fx]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Ademola Kolawole]]></dc:creator>
            <pubDate>Mon, 08 Apr 2024 11:55:27 GMT</pubDate>
            <atom:updated>2024-12-31T13:51:44.282Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vrSZvPW8eeZgdhKvV4IX-g.png" /></figure><h3>What is Dependency Injection</h3><p>Dependency injection might sound like a complex concept, but at its core, it’s all about making your code more flexible, reusable, and easier to test. If you’ve struggled to grasp dependency injection in Go (or any other programming language), fear not! By the end of this article, you’ll clearly understand what dependency injection is and how to use it effectively in your Go projects.</p><h3>Benefits of Dependency Injection</h3><ol><li><strong>Loose Coupling</strong>: By injecting dependencies from the outside, we reduce the tight coupling between components, making our code more modular and easier to understand.</li><li><strong>Reusability</strong>: When our code is not tightly bound to specific dependencies, we can reuse it in different contexts or projects more easily.</li><li><strong>Testability</strong>: Since dependencies are passed into our code, we can easily substitute them with mock or fake implementations during testing, making our code more testable.</li></ol><h3>Understanding Basic Dependency Injection</h3><p>Let’s break it down in simple terms. Imagine you have a piece of code, let’s call it <strong>A</strong>, that needs to use another piece of code, let&#39;s call it <strong>B</strong>, to perform some task. Instead of <strong>A</strong> creating <strong>B</strong> directly inside itself, we &quot;inject&quot; <strong>B</strong> into <strong>A</strong>. In other words, <strong>A</strong> relies on <strong>B</strong>, but <strong>B</strong> is provided to <strong>A</strong> from the outside.</p><p>So why is this useful? Well, by injecting <strong>B</strong> into, we make <strong>A</strong> independent of <strong>B</strong>. This means we can easily swap out <strong>B</strong> for a different implementation without having to modify <strong>A</strong>. This flexibility is what makes our code loosely coupled and easier to maintain.</p><p>Now, let’s see how we can implement dependency injection in Go:</p><p><strong>Define an Interface</strong>:</p><pre>package main<br>import &quot;fmt&quot;<br>type User interface {<br> GetUserName() string<br> GetPassword() string<br> GetAge() int<br>}</pre><p>We define a <strong>User</strong> interface. This interface represents the functionality that any type must implement to be considered a user.</p><p><strong>Create a Struct</strong>:</p><pre>type Student struct {<br>name     string<br>age      int<br>password string<br>}</pre><p>We define a <strong>Student</strong> struct that represents a user of type <strong>Student</strong>. The <strong>Student</strong> struct contains fields for <strong>name</strong>, <strong>age</strong>, and <strong>password</strong>.</p><p><strong>Implement the Interface</strong>:</p><pre>func (s *Student) GetUserName() string {<br>	return s.name<br>}<br>func (s *Student) GetPassword() string {<br> return s.password<br>}<br>func (s *Student) GetAge() int {<br> return s.age<br>}</pre><p><strong>Implement the Main Function:</strong></p><pre>func main() {<br>	student := Student{<br>		name:     &quot;zhangsan&quot;,<br>		age:      18,<br>		password: &quot;&lt;PASSWORD&gt;&quot;,<br>	}<br><br> fmt.Println(student.GetUserName())<br> fmt.Println(student.GetPassword())<br> fmt.Println(student.GetAge())</pre><p>Now run your code, by doing this we have successfully decoupled the <strong>struct Student</strong> and allow for flexible implementation in many other cases.</p><h3>Understanding the Dependency Inversion Principle</h3><p>The dependency Inversion principle suggests that software modules should depend on abstractions (interfaces or abstract classes) rather than concrete implementations. Dependency Inversion enables us to decouple our code in such a way that higher-level functions don’t depend on lower-level functions. This helps in decoupling, flexibility, testability, modularity and separation of your code. Now let&#39;s try to inverse our code written above.</p><pre>package main<br>import &quot;fmt&quot;<br><br>// UserRepository is a high-level module that depends on the User interface<br>type UserRepository interface {<br> GetUser() User<br>}<br><br>// User is a low-level module that does not depend on the UserRepository interface<br>type User interface {<br> GetUserName() string<br> GetPassword() string<br> GetAge() int<br>}<br><br>// Student is a low-level module that does not depend on the UserRepository interface<br>type Student struct {<br> name     string<br> age      int<br> password string<br>}<br><br>func (s *Student) GetUserName() string {<br> return s.name<br>}<br><br>func (s *Student) GetPassword() string {<br> return s.password<br>}<br><br>func (s *Student) GetAge() int {<br> return s.age<br>}<br><br>// UserRepositoryImpl implements the UserRepository interface<br>type UserRepositoryImpl struct{}<br><br>func (u UserRepositoryImpl) GetUser() User {<br> return &amp;Student{<br>  name:     &quot;zhangsan&quot;,<br>  age:      18,<br>  password: &quot;&lt;PASSWORD&gt;&quot;,<br> }<br>}<br><br>func main() {<br> // Dependency inversion: UserRepository is a high-level module that depends on the User interface<br> var userRepository UserRepository = UserRepositoryImpl{}<br> // User is a low-level module that depends on the UserRepository interface<br> var user User = userRepository.GetUser()<br> fmt.Println(user.GetUserName())<br> fmt.Println(user.GetPassword())<br> fmt.Println(user.GetAge())<br>}</pre><ul><li><strong>UserRepository</strong> the interface defines a method <strong>GetUser()</strong>, which returns a <strong>User</strong>.</li><li><strong>User</strong> interface defines methods <strong>GetUserName()</strong>, <strong>GetPassword()</strong>, and <strong>GetAge()</strong>.</li><li><strong>Student</strong> struct implements the <strong>User</strong> interface. It has fields for a user&#39;s name, age, and password, and methods to get these details.</li><li><strong>UserRepositoryImpl</strong> is a struct implementing the <strong>UserRepository</strong> interface. It provides a concrete implementation of <strong>GetUser()</strong> the method, returning an <strong>User</strong> object, which is an <strong>Student</strong> in this case.</li></ul><h3>What is Uber FX?</h3><p>Uber Fx is a dependency injection (DI) system for Go, developed by Uber. Its primary purpose is to simplify the setup of applications by reducing boilerplate code, eliminating global state, and facilitating the easy addition of new components that are instantly accessible across the application. Additionally, it enables the creation of general-purpose, shareable modules that seamlessly integrate into the application.</p><p>Key features and benefits of Uber Fx include:</p><ol><li><strong>Boilerplate Reduction</strong>: Uber Fx streamlines the setup of applications by minimizing the amount of repetitive and boilerplate code required, thus improving developer productivity.</li><li><strong>Elimination of Global State</strong>: By implementing a dependency injection approach, Uber Fx helps eliminate global states within the application, which can lead to cleaner and more maintainable code.</li><li><strong>Instant Accessibility of Components</strong>: With Uber Fx, new components can be easily added to the application and are instantly accessible throughout the codebase without the need for explicit configuration or management.</li><li><strong>General-Purpose Shareable Modules</strong>: Uber Fx allows developers to build modules that are designed to be shareable and reusable across different parts of the application or even across multiple projects. This promotes code reusability and modularity.</li></ol><h3>Why use Uber Fx?</h3><ol><li>Makes dependency injection easy.</li><li>Eliminates the need for a global state and func init()</li></ol><h3>Let&#39;s go</h3><p>The first step is to install the library via:</p><pre>go get go.uber.org/fx</pre><p>Now on your <strong>main.go</strong> file add</p><pre>package main<br>import &quot;go.uber.org/fx&quot;<br><br>func main() {<br>  fx.New().Run()<br>}</pre><pre>go run main.go</pre><p>Once you run the code you should see this</p><pre>[Fx] PROVIDE    fx.Lifecycle &lt;= go.uber.org/fx.New.func1()<br>[Fx] PROVIDE    fx.Shutdowner &lt;= go.uber.org/fx.(*App).shutdowner-fm()<br>[Fx] PROVIDE    fx.DotGraph &lt;= go.uber.org/fx.(*App).dotGraph-fm()<br>[Fx] RUNNING</pre><h3>What is fx.New?</h3><p>We then run this application with the App.Run method. This method blocks until it receives a signal to stop, and it then runs any cleanup operations necessary before exiting.</p><p>So now let’s convert our <strong>UserRepository</strong> to use Uber.FX</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;go.uber.org/fx&quot;<br>)<br><br>// UserRepository is a high-level module that depends on the User interface<br>type UserRepository interface {<br> GetUser() User<br>}<br><br>// User is a low-level module that does not depend on the UserRepository interface<br>type User interface {<br> GetUserName() string<br> GetPassword() string<br> GetAge() int<br>}<br><br>// Student is a low-level module that does not depend on the UserRepository interface<br>type Student struct {<br> name     string<br> age      int<br> password string<br>}<br><br>func (s *Student) GetUserName() string {<br> return s.name<br>}<br><br>func (s *Student) GetPassword() string {<br> return s.password<br>}<br><br>func (s *Student) GetAge() int {<br> return s.age<br>}<br><br>// UserRepositoryImpl implements the UserRepository interface<br>type UserRepositoryImpl struct{}<br>func (u UserRepositoryImpl) GetUser() User {<br> return &amp;Student{<br>  name:     &quot;zhangsan&quot;,<br>  age:      18,<br>  password: &quot;&lt;PASSWORD&gt;&quot;,<br> }<br>}<br><br>// ProvideUserRepository is a function to provide the UserRepository<br>func ProvideUserRepository() UserRepository {<br> return UserRepositoryImpl{}<br>}<br><br>func main() {<br> fx.New(<br>  fx.Provide(ProvideUserRepository),<br>  fx.Invoke(func(u UserRepository) {<br>   user := u.GetUser()<br>   println(user.GetUserName())<br>   println(user.GetPassword())<br>   println(user.GetAge())<br>  }),<br> ).Run()<br>}</pre><p>We initialize the FX application using <strong>fx.New()</strong>.<strong>fx.Provide(ProvideUserRepository)</strong> registers <strong>ProvideUserRepository</strong> as a provider of <strong>UserRepository</strong>.<strong>app.Run()</strong> runs the application, injecting the <strong>UserRepository</strong> dependency into the provided function. Inside the function, we retrieve a <strong>User</strong> instance using the <strong>GetUser()</strong> method and print its properties using methods from the <strong>User</strong> interface. fx.Invoke() helps to print the user details.</p><h3>Uber FX Gin Framework</h3><p>Let&#39;s Explore other uses of Uber Fx by Implementing a simple <a href="https://github.com/gin-gonic/gin">Gin</a>. Gin is one of the most popular frameworks for creating servers in Golang.</p><p>Let&#39;s import the Gin package</p><pre>go get github.com/gin-gonic/gin</pre><p>Write a function to build our GinServer</p><pre>package main<br><br>import (<br> &quot;context&quot;<br> &quot;fmt&quot;<br> &quot;net/http&quot;<br> &quot;github.com/gin-gonic/gin&quot;<br> &quot;go.uber.org/fx&quot;<br>)<br><br>func GinServer(lc fx.Lifecycle) *gin.Engine {<br>r := gin.Default()<br>return r<br>}</pre><p>Now we need to add the add a <em>lifecycle hook</em> to the application with the fx.Lifecycle object. This tells Fx how to start and stop the Gin server.</p><pre>func GinServer(lc fx.Lifecycle) *gin.Engine {<br>r := gin.Default()<br>srv := &amp;http.Server{<br>  Addr:    &quot;:8080&quot;,<br>  Handler: r,<br> }<br><br> lc.Append(fx.Hook{<br>  OnStart: func(ctx context.Context) error {<br>   srv.ListenAndServe()<br>   return nil<br>  },<br><br>  OnStop: func(ctx context.Context) error {<br>   srv.Shutdown(ctx)<br>   return nil<br>  },<br> })<br> return r<br>}</pre><p>Now let’s Create a struct to handle our routes</p><pre>type Handler struct {<br>	GinServer *gin.Engine<br>}<br><br>func (s *Handler) Say() {<br> s.GinServer.GET(&quot;/ping&quot;, func(c *gin.Context) {<br>  c.JSON(http.StatusOK, gin.H{<br>   &quot;message&quot;: &quot;pong&quot;,<br>  })<br> })<br>}<br><br>func GinServer(lc fx.Lifecycle) *gin.Engine {<br>    r := gin.Default()<br>    srv := &amp;http.Server{<br>        Addr:    &quot;:8080&quot;,<br>        Handler: r,<br>    }<br><br>    lc.Append(fx.Hook{<br>        OnStart: func(ctx context.Context) error {<br>            go func() {<br>                if err := srv.ListenAndServe(); err != nil &amp;&amp; err != http.ErrServerClosed {<br>                    fmt.Printf(&quot;Error starting server: %s\n&quot;, err)<br>                }<br>            }()<br>            fmt.Println(&quot;Gin server started on :8080&quot;)<br>            return nil<br>        },<br>        OnStop: func(ctx context.Context) error {<br>            fmt.Println(&quot;Stopping Gin server...&quot;)<br>            return srv.Shutdown(ctx)<br>        },<br>    })<br><br>    return r<br>}Now Let&#39;s provide this to your Fx application above with fx.Provide.</pre><pre>func main() {<br>	app := fx.New(<br>	fx.Provide(GinServer),<br>	)	<br>	app.Run()<br>	}</pre><p>Provide this to your Fx application above with fx.Provide</p><pre>func main() {<br>    app := fx.New(<br>        fx.Provide(GinServer),<br>        fx.Invoke(func(r *gin.Engine) {<br>            r.GET(&quot;/ping&quot;, func(c *gin.Context) {<br>                c.JSON(http.StatusOK, gin.H{<br>                    &quot;message&quot;: &quot;pong&quot;,<br>                })<br>            })<br>        }),<br>    )<br><br>    app.Run()<br>}</pre><p>Now let&#39;s run our application</p><pre>go run main.go</pre><pre>[Fx] PROVIDE    *gin.Engine &lt;= main.GinServer()<br>[Fx] PROVIDE    fx.Lifecycle &lt;= go.uber.org/fx.New.func1()<br>[Fx] PROVIDE    fx.Shutdowner &lt;= go.uber.org/fx.(*App).shutdowner-fm()<br>[Fx] PROVIDE    fx.DotGraph &lt;= go.uber.org/fx.(*App).dotGraph-fm()<br>[Fx] INVOKE             main.main.func1()<br>[Fx] RUN        provide: go.uber.org/fx.New.func1()<br>[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.<br>[GIN-debug] [WARNING] Running in &quot;debug&quot; mode. Switch to &quot;release&quot; mode in production.<br> - using env:   export GIN_MODE=release<br> - using code:  gin.SetMode(gin.ReleaseMode)<br>[Fx] RUN        provide: main.GinServer()<br>Server is running on port 8080[Fx] HOOK OnStart         main.GinServer.func1() executing (caller: main.GinServer)<br>[GIN-debug] GET    /ping                    --&gt; main.(*Handler).Say.func1 (3 handlers)<br>A failed Route Gracefully Shutdown our application<br>[Fx] ERROR              Failed to start: context deadline exceeded</pre><h3>Thank you for reading</h3><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=b3c3600e822d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Unit tests for Riverpod]]></title>
            <link>https://medium.com/@ademolakolawole/implementing-unit-tests-for-riverpod-9e73613db384?source=rss-97299a8a410e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e73613db384</guid>
            <dc:creator><![CDATA[Ademola Kolawole]]></dc:creator>
            <pubDate>Sun, 12 Feb 2023 16:37:22 GMT</pubDate>
            <atom:updated>2024-06-06T09:35:57.296Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6uV-X6ZsEJsdue4yRwwFtQ.jpeg" /></figure><p>Unit testing in Flutter is a great way to ensure the quality of your code. It helps to identify bugs early on and reduce the risk of them making it to production. Unit tests can be written quickly and easily, and they provide a comprehensive overview of the code&#39;s functionality. By running unit tests regularly, you can be sure that your code is working as expected and that any changes you make don&#39;t cause unexpected issues.</p><h3>Adding dependencies</h3><p>Add the following dependencies to the pubspec.yaml file.</p><pre>dependencies:<br>  state_notifier_test: ^latest_version<br>  flutter_riverpod: ^latest_version<br>  riverpod: ^latest_version<br>  dartz: ^latest_version<br><br>dev_dependencies:<br>  build_runner: any<br>  flutter_test:<br>    sdk: flutter<br>  freezed: ^latest_version<br>  freezed_annotation: ^latest_version<br>  mocktail: ^latest_version</pre><p>The state_notifier_test dependency is necessary for running the unit tests. It will be useful for writing them.. To make sure the tests are running correctly, the flutter_test package should be imported as well. Finally, freezed and freezed_annotation should be imported so the unit tests can access the model classes. These packages help to provide a solid foundation for the unit tests and a way to test the data models. With these packages set up, the unit tests for Riverpod can be written.</p><p>It is important to import flutter_riverpod and riverpod package as our state management dependencies. The build_runner packages is an essential tool for our code generation process. It provides us with a robust and reliable way of creating and managing our code, allowing us to quickly and easily build applications that are both efficient and maintainable.</p><p>To write our unit tests, we will need to define our test methods, create our mocks, and define our assertions. Mocktailsenable us to create mock objects that imitate the behaviour of our real objects. This allows us to test our code without having to connect to an actual server or database. Mockito also provides us with an easy way to mock our data models and check that the data we expect is returned. Additionally, we can use assertions to verify that our code is working as expected. By using these tools, we can quickly and efficiently write unit tests for Riverpod.</p><p>We rely on dartz for our functional programming needs in Dart. It provides us with a range of powerful tools that enable us to write concise and expressive code. For example, the library provides us with an immutable data type called Either, which allows us to chain computations and recover from errors with ease. Additionally, dartz also comes with a wide variety of built-in functions that make it easy to manipulate data and create complex logic. All in all, dartz is an essential part of our toolkit when it comes to functional programming in Dart.</p><h3>Getting started</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*_g9KZN86UIuvaymXnUQGpQ.gif" /></figure><p>First, let&#39;s create our StateNotifier and State classes using the incredibly powerful freezed package. This package helps us to easily manage our states and avoid bugs that can be caused by complex state management. With the help of freezed, we will be able to define a set of states, define transitions between them, and set the initial state. Additionally, it provides a great way to detect any invalid state transitions and to handle these cases gracefully. This makes our state management a breeze and allows us to focus on the important parts of our app.</p><pre>part &#39;get_weather_state.freezed.dart&#39;;<br><br>@freezed<br>class WeatherState with _$WeatherState {<br>  const factory WeatherState.initial() = _Initial;<br>  const factory WeatherState.loading() = Loading;<br>  const factory WeatherState.getWeather(<br>      {required WeatherEntity weatherEntity}) = GetWeather;<br>  const factory WeatherState.error({required Failure error}) = _Error;<br>}</pre><p>Run flutter pub run build_runner build -delete-conflicting-outputs to generate our states.</p><h3>Handling tests</h3><p>Let&#39;s create our class of WeatherNotifier</p><pre>class WeatherNotifier extends StateNotifier&lt;WeatherState&gt; {<br>final GetWeatherInfo getWeatherInfo;<br>  WeatherNotifier(this.getWeatherInfo) : super(const WeatherState.initial());<br><br>		Future&lt;void&gt; getWeather({required String cityName}) async {}<br><br>}</pre><p>Following Tdd principles, it is important to write our tests before we write more code:</p><pre>import &#39;weather_notifier_test.mocks.dart&#39;;<br><br>class MockGetWeatherInfo extends Mock implements GetWeatherInfo {}<br><br>void main() {<br>	late MockGetWeatherInfo mockGetWeatherInfo;<br>  late String tCityName;<br>  late WeatherEntity tWeatherEntity;<br>	setUp(() {<br>    mockGetWeatherInfo = MockGetWeatherInfo();<br>    tCityName = &quot;London&quot;;<br>  });<br>  tWeatherEntity = const WeatherEntity(weather: [Weather()]);<br>}</pre><p>tWeatherEntity is our default weather entity, check the click in the read me below to find the model</p><p>First, let&#39;s put our API to the test and check out what happens when we are able to successfully retrieve the weather. We can use this as a gauge to determine how reliable our API is, and if it is providing us with the data we need. If the results are satisfactory, then we can be assured that we can rely on the information that is being delivered, which is a key factor in any successful business operation. With a reliable API, we can be sure to make accurate predictions and decisions based on the data we receive.</p><pre>import &#39;package:state_notifier_test/state_notifier_test.dart&#39;;<br><br>group(&#39;get Weather&#39;, () {<br>    stateNotifierTest&lt;WeatherNotifier, WeatherState&gt;(<br>      &#39;state is GetWeatherLoading when getWeather is called&#39;,<br>      // Arrange - create notifier<br>      build: () =&gt; WeatherNotifier(mockGetWeatherInfo),<br>      // Arrange - set up dependencies<br>      setUp: () {<br>        when(() =&gt; mockGetWeatherInfo(Params(cityName: tCityName)))<br>            .thenAnswer((_) async {<br>          return Future&lt;Either&lt;Failure, WeatherEntity&gt;&gt;(<br>            () =&gt; Future.value(Right(tWeatherEntity)),<br>          );<br>        });<br>      },<br>      // Act - call the methods<br>      actions: (WeatherNotifier stateNotifier) async {<br>        await stateNotifier.getWeather(cityName: tCityName);<br>      },<br>      // Assert<br>      expect: () =&gt; [<br>        const WeatherState.loading(),<br>        WeatherState.getWeather(weatherEntity: tWeatherEntity),<br>      ],<br>    );</pre><p>Now lets break this down,</p><ul><li>We imported our state_notifier_test earlier, which we added to our pubsec.yaml file.</li><li>After determining the use case, we create a group to store all associated tests, so that we can easily keep track of them and make sure they are running properly. This will allow us to make sure that all tests related to this use case are being executed and that any issues can be quickly addressed. By having a group for each use case, it also makes it easier to review the results and make sure everything is working as expected.</li><li>stateNotifierTest is a function that takes a notifier and a state as parameters. It ensures that the notifier is triggered when the state changes. we can use this function to write unit tests for our Riverpod code.</li><li>The build function should construct the stateNotifier object being tested, initializing its attributes and data members with the necessary values.</li><li>The setUp method is an optional step that can be taken prior to initializing the stateNotifier for testing. This is done to guarantee that the desired state is created and ready for the test case to be executed.</li><li>action is an optional callback which, when invoked, provides you with the chance to explore its capabilities.</li><li>expect is an optional Function that returns a Matcher which the stateNotifier under test is expected to emit after action is executed. In our case we expect the state to be loading before fetching the data.</li></ul><p>Of course, if we run our test, it will likely fail since we have not implemented our notifier function.</p><pre>Future&lt;void&gt; getWeather({required String cityName}) async {<br>    state = const WeatherState.loading();<br><br>    final result = await getWeatherInfo(Params(cityName: cityName));<br>    result.fold(<br>      (l) {<br>        // Failure case<br>      },<br>      (r) {<br>        state = WeatherState.getWeather(weatherEntity: r);<br>      },<br>    );<br>  }</pre><p>Now, when we run our test, it should pass without a doubt.</p><h3>Test Result</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JOmt0eFdQQi1Vk6lA5KkLg.png" /></figure><p>We can now test if our data fails to fetch, which might happen when a user attempts to retrieve a city that does not exist.</p><pre>stateNotifierTest&lt;WeatherNotifier, WeatherState&gt;(<br>      &#39;state is GetWeatherError when getWeather is called&#39;,<br>      // Arrange - create notifier<br>      build: () =&gt; WeatherNotifier(mockGetWeatherInfo),<br>      // Arrange - set up dependencies<br>      setUp: () {<br>        when(() =&gt; mockGetWeatherInfo(Params(cityName: tCityName)))<br>            .thenAnswer((_) async {<br>          return Future&lt;Either&lt;Failure, WeatherEntity&gt;&gt;(<br>              () =&gt; Future.value(Left(ServerFailure())));<br>        });<br>      },<br>      // Act - call the methods<br>      actions: (WeatherNotifier stateNotifier) async {<br>        await stateNotifier.getWeather(cityName: tCityName);<br>      },<br>      // Assert<br>      expect: () =&gt; [<br>        const WeatherState.loading(),<br>        WeatherState.error(error: ServerFailure()),<br>      ],<br>    );</pre><p>The Left to be called and a failure occured! and it is expected for the data to try loading before ultimatly failing!</p><p>Now lets write our state in the getWeather function:</p><pre>class WeatherNotifier extends StateNotifier&lt;WeatherState&gt; {<br>  final GetWeatherInfo getWeatherInfo;<br>  WeatherNotifier(this.getWeatherInfo) : super(const WeatherState.initial());<br><br>  Future&lt;void&gt; getWeather({required String cityName}) async {<br>    state = const WeatherState.loading();<br><br>    final result = await getWeatherInfo(Params(cityName: cityName));<br>    result.fold(<br>      (l) {<br>        state = WeatherState.error(error: ServerFailure());<br>      },<br>      (r) {<br>        state = WeatherState.getWeather(weatherEntity: r);<br>      },<br>    );<br>  }<br>}</pre><h3>Test Result</h3><p>And when we run our test it should all pass:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wimeH8dCFlrABy4skOZMXw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Q2UiGwPWlU_4I9C__1utw.gif" /></figure><h3>Thanks for reading</h3><p>For more information on writing integration tests, refer to the documentation. This will provide more detailed information on how to write unit tests for Riverpod and the tools available to help. Additionally, there are many tutorials available online that can help guide you through the process of writing unit tests in Dart. With the right resources, you can easily create comprehensive unit tests for your Riverpod code.</p><p>Check out the full code <a href="https://github.com/demola234/tdd_weather"><strong>here</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*XxC4K2MK8VgnS-XLD7qb8Q.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e73613db384" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>