<?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 5MinsLearn on Medium]]></title>
        <description><![CDATA[Stories by 5MinsLearn on Medium]]></description>
        <link>https://medium.com/@5minslearn?source=rss-36827e865e1f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xhMn8mp5AGP2EkSJYAe6IA.png</url>
            <title>Stories by 5MinsLearn on Medium</title>
            <link>https://medium.com/@5minslearn?source=rss-36827e865e1f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 22:08:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@5minslearn/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[How to simplify database operations using MySQL stored procedures]]></title>
            <link>https://5minslearn.medium.com/how-to-simplify-database-operations-using-mysql-stored-procedures-28b74eb689ff?source=rss-36827e865e1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/28b74eb689ff</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[stored-procedure]]></category>
            <category><![CDATA[dbms]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[5minslearn]]></category>
            <dc:creator><![CDATA[5MinsLearn]]></dc:creator>
            <pubDate>Fri, 01 Sep 2023 04:58:11 GMT</pubDate>
            <atom:updated>2023-09-01T04:58:11.155Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7aLnLdEQeWXVZvSdnUbZHA.png" /></figure><p>In the realm of database management, MySQL has emerged as one of the most popular and reliable choices. MySQL not only offers robust data storage capabilities but also provides a powerful feature called “procedures” that allows developers to streamline complex database operations. In this blog post, we will delve into the concept of MySQL procedures, explore their benefits, and provide a step-by-step guide on how to use them effectively.</p><h3>SQL Procedures</h3><p>SQL procedures are a set of SQL statements grouped together to form a logical unit of work. They are similar to functions or methods in programming languages, enabling you to encapsulate complex queries and operations into a single reusable entity. Procedures enhance code modularity, readability, and maintainability, making it easier to manage and execute repetitive or intricate database tasks.</p><h3>When to use stored procedures</h3><p>Let’s consider an e-commerce website, where we have the functionality to Generate sales reporting. For that let’s consider a Table called sales.</p><p>Generating sales reports in real-time can be resource-intensive, especially when dealing with large datasets. By creating stored procedures that aggregate and summarize sales data, we can optimize the reporting process. These procedures can calculate metrics like total sales, top-selling products, or revenue by category, making it easier to retrieve valuable insights quickly and efficiently.</p><p>Here’s the schema of sales table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*Dv3lh2-Edi7Y0ytU09QyLQ.png" /><figcaption>DB Schema of sales table</figcaption></figure><p>To illustrate a simple example, let’s consider a table called “sales” that is populated with 1 million rows of mock data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/0*JFxwCRa_KzTleEmB.png" /><figcaption>Sales table data count</figcaption></figure><pre>select count(*) from sales;</pre><p>Now, The goal is to get sales reports for a particular period of time.</p><pre>CREATE PROCEDURE GenerateSalesReport (<br>    IN start_date DATE,<br>    IN end_date DATE<br>)<br>BEGIN<br>    SELECT DATE_FORMAT(order_date, &#39;%Y-%m-%d&#39;) AS Date,<br>           COUNT(order_id) AS TotalOrders,<br>           SUM(total_amount) AS TotalSales<br>    FROM orders<br>    WHERE order_date BETWEEN start_date AND end_date<br>    GROUP BY DATE_FORMAT(order_date, &#39;%Y-%m-%d&#39;);<br>END</pre><p>The example stored procedure GenerateSalesReport takes two input parameters: start_date and end_date, which defines the date range for the sales report. The procedure selects the order date, counts the number of orders, and calculates the total sales amount within the specified date range. The result is grouped by the date, using the DATE_FORMAT function to display it in the desired format.</p><p>Now, you might have a question:</p><p>“<strong>Can’t we achieve the same outcome using a simple query instead of creating a stored procedure?</strong>” While it’s true that using a simple query is a viable option, there are several compelling reasons to consider utilizing a stored procedure.</p><p>Here are few reasons that feels promising to use stored procedures at some places.</p><ol><li>A stored procedure offers the advantage of code reusability. By encapsulating the query logic within a stored procedure, we can reuse it multiple times without duplicating the code.</li><li>Instead of rewriting the same query in different parts of the application, we can simply call the stored procedure whenever needed, streamlining the codebase and making it easier to manage and update.</li><li>Using a stored procedure can lead to improved performance in certain scenarios. When a stored procedure is executed, the database server can optimize the execution plan and cache it for subsequent invocations. This optimization can result in faster execution times, as the database engine leverages the cached plan.</li><li>Furthermore, stored procedures can minimize network round trips by combining multiple queries into a single call, reducing the overhead associated with individual query executions. This optimization can significantly enhance overall performance, especially when dealing with complex operations or large datasets.</li><li>Another significant advantage of stored procedures is enhanced security. By granting execution privileges only to the stored procedure and not directly to underlying tables, you can enforce access control and protect sensitive data.</li></ol><p>In summary, while a simple query can achieve the desired outcome, utilizing a stored procedure offers distinct benefits such as code reusability, improved performance through query optimization and reduced network overhead, and enhanced security.</p><h3>Building blocks of Stored Procedures</h3><p>Let’s break down the stored procedure and examine each component individually. We will understand creating and running the stored procedure in MySQL. There are several MySQL IDEs available, and I recommend using MySQL Workbench. However, you are free to choose any IDE that suits your preference and needs.</p><p><strong>Procedure Name</strong></p><p>Every stored procedure has a unique name that identifies it within the database. The name should be descriptive and relevant to the procedure’s purpose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/0*svQkBoGGMQ5aI4Uz.png" /><figcaption>Create stored procedure</figcaption></figure><pre>CREATE PROCEDURE `GenerateSalesReport`()<br>BEGIN<br>END</pre><p><strong>Parameters</strong></p><p>Stored procedures can have input parameters that allow you to pass values into the procedure at runtime. We define start_date and end_date as our input parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/0*DnEhfGOANyRv4NlN.png" /><figcaption>Add parameter to the stored procedure</figcaption></figure><pre>CREATE PROCEDURE `GenerateSalesReport`(<br>    IN start_date DATE,<br>    IN end_date DATE<br>)<br>BEGIN<br>END</pre><p><strong>Variables</strong></p><p>Variables are used to store and manipulate data within the stored procedure. They can be declared and assigned values as needed. There are two types of variables in SQL.</p><p><strong>Session Variables</strong>: Session variables in MySQL are prefixed with the @ symbol (e.g., @variable_name). These variables are associated with the current session or connection and retain their values throughout the session until they are explicitly changed or the session ends.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/0*B3qpqpWW_oOMnOxo.png" /><figcaption>Using session variables in a stored procedure</figcaption></figure><pre>CREATE PROCEDURE `GenerateSalesReport`(<br>    IN start_date DATE,<br>    IN end_date DATE<br>)<br>BEGIN<br>   SELECT @totalSales := 0;<br>   SELECT SUM(sales_amount) INTO @totalSales FROM sales;<br>   SELECT @totalSales As total_sales;<br>END</pre><p><strong>Normal Variables</strong>: Normal variables, also known as local variables, are declared using the DECLARE keyword within the scope of a stored procedure. Unlike session variables, normal variables do not have the @ prefix (e.g., variable_name). They are temporary and exist only within the block of code where they are declared.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/0*IQ6dApG3rcdyyFXO.png" /><figcaption>Using normal variables in a stored procedure</figcaption></figure><pre>CREATE PROCEDURE `GenerateSalesReport`(<br>    IN start_date DATE,<br>    IN end_date DATE<br>)<br>BEGIN<br>   DECLARE totalSales INT;<br>   SELECT SUM(sales_amount) INTO totalSales FROM sales;<br>END</pre><p><strong>SQL Statements</strong></p><p>The core functionality of a stored procedure is defined by SQL statements. These statements can include SELECT, INSERT, UPDATE, DELETE, and other SQL commands to interact with the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/0*vmCTHjCgFVSdOf7H.png" /><figcaption>Using SQL queries in stored procedures</figcaption></figure><pre>CREATE PROCEDURE `GenerateSalesReport`(<br>    IN start_date DATE,<br>    IN end_date DATE<br>)<br>BEGIN<br>    SELECT DATE_FORMAT(saled_date, &#39;%d-%m-%Y&#39;) AS Date,<br>           COUNT(sale_id) AS TotalOrders,<br>           SUM(total_amount) AS TotalSales<br>    FROM sales<br>    WHERE saled_date BETWEEN start_date AND end_date<br>    GROUP BY DATE_FORMAT(saled_date, &#39;%d-%m-%Y&#39;);<br>END</pre><p><strong>Procedure Call</strong></p><p>To execute the stored procedure and generate a detailed sales report for a specific date range, we can use the following syntax:</p><pre>CALL (, ...);</pre><pre>CALL GenerateSalesReport(&#39;2021-01-01&#39;, &#39;2023-12-31&#39;);</pre><p>Result of the stored procedure, This query processed around 1 million data in a second.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WF4JceFanQLaYGh8.png" /><figcaption>Usage of calling a stored procedure</figcaption></figure><h3>Importance of using MySQL stored procedures</h3><h4>Improved Performance</h4><p>Stored procedures offer a significant performance advantage over ad-hoc SQL queries. Once a stored procedure is created, it is compiled and stored in a pre-optimized form. This compilation process eliminates the need for repetitive query parsing and optimization, resulting in faster execution times. By reducing the overhead associated with query processing, stored procedures enhance the overall performance of database operations.</p><h4>Enhanced Security</h4><p>Security is a critical aspect of database management. Stored procedures allow database administrators to define access rights and permissions for executing specific procedures. This fine-grained control ensures that only authorized users can interact with the database through the procedures, minimizing the risk of unauthorized data access or modifications. By encapsulating sensitive operations within stored procedures, security vulnerabilities are reduced, strengthening the overall database security posture.</p><h4>Code Reusability and Maintainability</h4><p>Stored procedures promote code reusability, modularity, and maintainability. By encapsulating frequently used SQL statements and operations within a single procedure, you can avoid code duplication and ensure consistent execution across multiple instances. This modularity makes it easier to maintain and update the database logic. Additionally, when modifications are required, changes can be made in a single location (the stored procedure) rather than in multiple places, simplifying the maintenance process.</p><h4>Transaction Control</h4><p>Stored procedures enable transaction control within the database. Transactions ensure data integrity by grouping multiple database operations into a single logical unit. By executing a series of operations within a transaction, you can ensure that either all the operations are successfully completed, or none of them are applied. This atomicity ensures data consistency and protects against data corruption. Stored procedures allow you to define transaction boundaries, ensuring that complex operations are handled reliably and consistently.</p><h4>Performance Optimization and Query Plan Caching</h4><p>Another advantage of using stored procedures is the ability to optimize query execution plans. Since stored procedures are compiled and stored, the database engine can generate optimized execution plans based on the stored procedure’s statistics and data distribution. These optimized plans can significantly improve query performance. Furthermore, the query execution plans for stored procedures are cached, which further reduces the overhead of plan generation for subsequent executions.</p><h3>Conclusion</h3><p>Stored procedures are a valuable tool in database management, and their usage should be considered in specific scenarios. When dealing with complex business logic, aiming for performance optimization, enhancing security and access control, promoting code reusability and maintainability, handling complex transactions, or integrating with legacy systems, stored procedures can provide significant benefits. By leveraging their power effectively, you can streamline your database operations, improve application performance, and simplify code maintenance, leading to a more efficient and scalable database environment.</p><p>Hope you enjoyed reading the article. If you wish to learn more about SQL, subscribe to my article by entering your email address <a href="https://5minslearn.gogosoon.com/">here</a>.</p><p>Have a look at my <a href="https://5minslearn.gogosoon.com/blogs/?ref=medium_sql_store_procedures">site</a> which has a consolidated list of all my blogs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28b74eb689ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is RabbitMQ and How to use it with NodeJS]]></title>
            <link>https://5minslearn.medium.com/what-is-rabbitmq-and-how-to-use-it-with-nodejs-eb0b08cd4900?source=rss-36827e865e1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb0b08cd4900</guid>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[5minslearn]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[5MinsLearn]]></dc:creator>
            <pubDate>Mon, 31 Jul 2023 05:33:39 GMT</pubDate>
            <atom:updated>2023-07-31T05:33:39.783Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MsjdEVnCvKXy7Px-hTZ5ig.png" /></figure><p>If you’re exploring the world of distributed systems and real-time data pipelines, it is likely that you would have come across the concept of message queues. Two names stand out among the pantheon of technologies in this field: RabbitMQ and Apache Kafka. While both are renowned for their robustness and reliability, they have unique features and use cases that make them distinct.</p><p>RabbitMQ, an open-source message broker, is widely recognized for its flexibility and support for various messaging protocols. On the other hand, Apache Kafka is rapidly gaining popularity and is known for its ability to handle real-time data feeds with low latency.</p><p>This blog post will focus on RabbitMQ, its core features, and how it can effectively build scalable, loosely coupled applications.</p><p>Stay with us as we explore into the world of RabbitMQ, its unique capabilities, and how it sets itself apart in the ever-evolving landscape of message queue technologies.</p><h3>What is RabbitMQ?</h3><p>RabbitMQ is an open-source message broker software (also called message-oriented middleware) that implements the Advanced Message Queuing Protocol (AMQP). It provides a common platform for sending and receiving messages. It supports multiple messaging protocols and can be deployed in distributed and federated configurations to meet high-scale, high-availability requirements.</p><h3>When to use RabbitMQ?</h3><p>Consider an e-commerce website (like Amazon) where users can place orders, which need to be processed. The order processing system might involve several steps, such as inventory checks, payment processing, shipping, etc., each of which can potentially take some time and are ideally handled asynchronously.</p><ol><li><strong>Inventory Checks:</strong> When a user places an order, the system should check whether the ordered products are in stock. You can send a message to a queue that is consumed by a service responsible for checking inventory. This way, even if the inventory service is temporarily down or overloaded, the order messages won’t be lost; they’ll be processed as soon as the service is available.</li><li><strong>Payment Processing:</strong> The payment processing might be done by another microservice. Once the inventory check is completed, a message can be sent to a queue for the payment service. This decouples the payment processing from the inventory checking, allowing these operations to scale independently.</li><li><strong>Shipping:</strong> After payment confirmation, a message can be sent to another queue that’s responsible for handling shipping. Again, this service might take some time, but because it’s decoupled from the rest of the system, it won’t slow down other operations.</li><li><strong>Notification system:</strong> After every successful order placement, payment, and shipment, notifications (Email or SMS) must be sent to the customer. This can be handled by separate services that listen to specific queues.</li></ol><h3>Install &amp; Run RabbitMQ</h3><p>In this example, I’ll be showcasing using Docker to run RabbitMQ. However, if you prefer, you can install and run it manually on your system. The official <a href="https://www.rabbitmq.com/install-windows.html">documentation</a> provides a detailed guide on how to do this.</p><p>I find Docker to be a convenient tool for running RabbitMQ because it simplifies the setup and management processes. If you’re new to Docker, I recommend (not mandatory) reading my <a href="https://www.freecodecamp.org/news/how-to-get-started-with-docker-using-nodejs/">previous</a> blog posts related to Docker for a thorough understanding.</p><p>To get started, you’ll need to pull the Docker image from Docker Hub.</p><pre>docker pull rabbitmq</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/0*ea7QPrlbp7yqIbgP.png" /></figure><p>Before running the image, We need to map the two port numbers (15672 and 5672).</p><ol><li><strong>Port 5672</strong>: This is the default port for RabbitMQ when using AMQP (Advanced Message Queuing Protocol). Clients that connect with AMQP typically use this port. So, if you’re using an AMQP client library to connect to RabbitMQ, it’s likely to connect on port 5672.</li><li><strong>Port 15672</strong>: This is the default port for the RabbitMQ Management UI, when using the rabbitmq_management plugin. The Management UI is a web-based interface that allows you to monitor and control your RabbitMQ server.</li></ol><p>I’m running the RabbitMQ on the Docker by adding the above-mentioned ports. Refer to the below screenshot for additional reference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/0*VQ4iv1UcZJfi7spE.png" /></figure><p>Our RabbitMQ Server is up and running in docker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/0*YJzCmtdVxb6JoMIc.png" /></figure><h3>Implement Message Queue in NodeJS</h3><p>I’ll be using amqplib, which is a popular NodeJS library that provides an API for interacting with RabbitMQ. It supports all the features of RabbitMQ’s AMQP 0-9-1 model, including things like confirm channels, exchanges, queues, bindings, and message properties.</p><p>I have been using the term AMQ Protocol in this blog and I feel this is the right time to give a quick introduction about it.</p><h3>What is AMQP</h3><p>AMQP stands for Advanced Message Queuing Protocol. It is an open-standard protocol for message-oriented middleware. The defining features of AMQP are message orientation, queuing, routing (including point-to-point and publish-and-subscribe), reliability, and security.</p><p>AMQP has the following components:</p><ol><li><strong>Producer</strong> — It’s an application that sends messages</li><li><strong>Consumer</strong> — It’s an application that receives messages</li><li><strong>Queue</strong> — It’s a buffer that stores the messages</li><li><strong>Message</strong> — Information that is sent from the producer to a consumer</li><li><strong>Exchange</strong> — Receives messages from producers and pushes them to queues depending on rules defined by the exchange type. The exchange type determines how messages are routed.</li><li><strong>Binding</strong> — Links the queue to the exchange</li></ol><p>The AMQP protocol enables standardized communication between different applications, making it a good choice for a messaging system in a micro-services architecture. This protocol can ensure that a message is delivered not just to the messaging system, but all the way to the correct consumer.</p><p>Remember the example that I described at the beginning of this blog about the high-level implementation of message queues in an E-commerce site?</p><p>Let’s go through the same but a bit deeper in the RabbitMQ context.</p><h4>Order Placement</h4><p>When a customer places an order on the e-commerce website, the order service produces a message to a RabbitMQ exchange. The message contains information about the product ID and the quantity ordered.</p><h4>Inventory Update</h4><p>An inventory service is set up for a consumer to receive messages from a queue bound to the exchange. Once it gets a message, it reduces the inventory for the specified product by the ordered quantity. If the inventory is insufficient, it can send a message back to the order service to indicate the problem.</p><h4>Order Confirmation</h4><p>Once the inventory service successfully updates the inventory, it’ll send a message to the order service. The order service, set up as a consumer for this exchange, can then update the order status and notify the customer.</p><h3>Benefits</h3><h4>Resilience</h4><p>Let’s assume your inventory service is down for some time, then the messages in the RabbitMQ queue will stay there and won’t be lost. Once the inventory service is back online, it’ll continue processing the messages from where it left off.</p><h4>Scalability</h4><p>During high traffic periods, more instances of the inventory service can be launched, all-consuming messages from the same queue, enabling load balancing and ensuring the system can handle the increased load.</p><p>Let’s come back to our implementation.</p><h3>Create a Sender / Producer</h3><p>This is the component or part of our application that creates and sends messages to the messaging queue. The sender does not send messages directly to the consumer. Instead, it sends the messages to an exchange in RabbitMQ. The exchange then routes the messages to the appropriate queue based on certain criteria.</p><p>Here I am Creating a queue called product_inventory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc36a41eee185ca8171d587bbeefaf39/href">https://medium.com/media/fc36a41eee185ca8171d587bbeefaf39/href</a></iframe><p>We can send only byte arrays in the message, So I convert the message object to a string and send it to the queue.</p><h3>Create a Receiver / Consumer</h3><p>This is the component or part of our application that receives and processes the messages from the queue. A consumer can continuously poll the queue for new messages or be set up to automatically trigger when a new message is added to the queue.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3142d5840a6ebd16c25a2970b354e0b/href">https://medium.com/media/c3142d5840a6ebd16c25a2970b354e0b/href</a></iframe><p>In the above code, we’re listening for messages (consume) and print them on the console once we receive it.</p><p>In the context of our specific use case, the file containing the message sender (or producer) should typically be located in the root directory of our e-commerce site project. This is where we generate and send messages based on user actions, such as placing an order.</p><p>On the other hand, the file containing the message receiver (or consumer) should ideally be located in the inventory management service. This is because the inventory management service is responsible for processing these messages, such as updating the inventory when an order is placed.</p><p>Let’s run our receiver service first,</p><pre>yarn start</pre><p>The initial output of the consumer service,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t-eam31HoyGh5TpR.png" /><figcaption>Initial output in the consumer service — Listening for messages</figcaption></figure><p>Once we run our sender, a message will be sent to the consumer.</p><p>Here’s the output of it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/0*jJHf3ptbjNeaiyRP.png" /><figcaption>Sending a message from the producer to the consumer</figcaption></figure><p>Hurray, We received a message from the RabbitMQ producer in our consumer service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JeIj0G1FJc00F0eY.png" /><figcaption>Received message from the RabbitMQ producer in our consumer service</figcaption></figure><h3>Conclusion</h3><p>In this article, we’ve explored the basics of RabbitMQ, a robust and efficient message broker, and demonstrated its application in a NodeJS environment. Using a simple e-commerce scenario, we showcased how to set up a sender (producer) and a consumer to handle asynchronous messages between different components of our application. However, in real-world applications, you will likely encounter more complex scenarios that require advanced integrations and the usage of RabbitMQ.</p><p>To navigate these complexities, it’s crucial to have a solid understanding of RabbitMQ’s underlying concepts and its AMQP protocol. As you delve deeper into RabbitMQ, you’ll find it to be an incredibly versatile tool, capable of handling a wide range of messaging needs, and ultimately, helping you build scalable, decoupled, and resilient applications.</p><p>Check out the source code of the project on GitHub: <a href="https://github.com/5minslearn/rabbit-sender">rabbit-sender</a>, <a href="https://github.com/5minslearn/rabbit-receiver">rabbit-receiver</a></p><p>If you wish to learn more about RabbitMQ, subscribe to my article at my <a href="https://5minslearn.gogosoon.com/?ref=medium_com_rabbitmq">site</a> which has a consolidated list of all my blogs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb0b08cd4900" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build a custom widget in Flutter — GoGoSoon]]></title>
            <link>https://5minslearn.medium.com/how-to-build-a-custom-widget-in-flutter-gogosoon-b7526a8053b5?source=rss-36827e865e1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7526a8053b5</guid>
            <category><![CDATA[custom-widget]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[5minslearn]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[5MinsLearn]]></dc:creator>
            <pubDate>Wed, 07 Jun 2023 04:52:42 GMT</pubDate>
            <atom:updated>2023-08-10T16:02:43.475Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to build a custom widget in Flutter — GoGoSoon</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tpuj80MkIE-_NJmxTtPEhA.png" /><figcaption>How to Build a Custom Widget in Flutter</figcaption></figure><p>As we all know Flutter is gaining more and more popularity day by day. Flutter apps has been loved by people for its smoothness. One such example app is Zerodha’s Kite. Kite is a trading app released by India’s biggest stock broker Zerodha. Similar to this there were many complex applications built with Flutter. However, building complex applications is not so simple. You have to refactor your code as and when needed to maintain the app’s performance. One such refactoring technique is extracting the duplicated code/component and reuse them at multiple places.</p><p>In this blog, we’ll be learning about replacing a duplicated component by building a custom widget in Flutter.</p><h3>What is a Custom Widget</h3><p>In Flutter, a custom widget refers to a user-defined widget that encapsulates a specific set of functionality or visual representation. Custom widgets are the building blocks of a Flutter application. They allow developers to create reusable UI components that can be used throughout the application.</p><p>If you’re switching from React Native, assume Custom Widget as a custom React component and what we call as props in React will be called as parameters in Flutter.</p><h3>Why Custom Widgets</h3><p>Custom widgets enable you to encapsulate complex UI elements, promote code re-usability, and enhance the maintainability of your Flutter applications. Developers should build custom widgets in Flutter for several reasons. Here are a few,</p><h4>Code Re-usability</h4><p>It allow developers to encapsulate complex functionality and appearance into reusable components. Once created, custom widgets can be used multiple times throughout the application, reducing code duplication and promoting a modular development approach.</p><h4>Maintainability</h4><p>It contribute to the maintainability of the codebase. By encapsulating specific functionality or visual representation, custom widgets create a separation of concerns. This separation makes it easier to locate, modify, and debug code related to a particular UI component.</p><h4>Consistent UI</h4><p>It enable developers to define a consistent and unified UI design across their application.</p><h4>Abstraction</h4><p>It provide a level of abstraction that hides the implementation details and complexity of a particular UI element. Developers can create high-level widgets that expose a simplified interface and handle the internal logic, allowing other developers to use the widget without worrying about its internal workings. This abstraction promotes modularity, making it easier to understand, test, and maintain the code.</p><h3>Build a Custom Widget</h3><p>Let’s start building our custom widget.</p><h4>Clone the repo</h4><p>Instead of starting from the scratch, I’ve created a Flutter app in Github and added a duplicated code/components in that repo. Let’s begin from there.</p><p>Pull the code from Github by running either of the below commands</p><pre>git clone https://github.com/5minslearn/Flutter-Custom-Widget.git</pre><pre>git clone [email protected]:5minslearn/Flutter-Custom-Widget.git</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RTmQpegPYL8vBMSy.png" /><figcaption>Clone the Flutter Custom Widget repo from GitHub</figcaption></figure><p>By default, it’ll be in master branch. I&#39;m switching to a refactor branch (you don&#39;t need to) because I want you all to have a look at my initial and final code. Initial code will be in master branch and final code will be in refactor branch.</p><p>Run the following command to install all the dependencies.</p><pre>cd Flutter-Custom-Widget/ </pre><pre>flutter pub get</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/0*nYRFs12kiVMDXU_i.png" /><figcaption>Install Flutter dependencies</figcaption></figure><h4>Run the app</h4><p>Open the repo in Visual Studio Code and spin up your emulator (you may connect your mobile device too). Once your emulator is up and running, press F5 to run the app in the emulator.</p><p>Here’s the view of your app on the first run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/0*8daCZpSW4l5M73Ww.png" /><figcaption>Initial app run screen</figcaption></figure><p>If you’ve come so far, that’s great.</p><h4>Analyze the code</h4><p>Let’s look at the code. Open lib/main.dart file.</p><p>We have MyApp class called at the beginning. This in-turn calls MyHomePage class.</p><p>Here we go. Our code for the entire UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/0*XwqzE5AXjXa1H3nW.png" /><figcaption>Code for the app UI</figcaption></figure><p>If you’re someone who loves writing clean code, you would definitely say that it’s a ugly code. Here’s the reason for it. Look at the code carefully where the lines from 44 to 56 and the lines from 58 to 70 are completely duplicated except a very few handpicked words. Example, the word “Twitter” has been replaced with “Instagram”.</p><p>The Clean coder will definitely refactor this code before working on adding new features/functionalities. Let us follow the clean coding practice too.</p><h4>Refactor — Build a custom widget</h4><p>We have to extract the text and button into a separate component. This component should accept the platform and onPressed as it&#39;s parameters. We can template out the common text from them.</p><p>So, our code to build the custom widget looks like below.</p><pre>class CustomButton extends StatelessWidget {<br>  final String platform;<br>  final VoidCallback onPressed;<br>  const CustomButton(<br>      {super.key, required this.platform, required this.onPressed});<br>  @override<br>  Widget build(BuildContext context) {<br>    return Center(<br>        child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [<br>      Text(&quot;Press the below button to follow me on $platform&quot;),<br>      ElevatedButton(<br>        onPressed: () {<br>          ScaffoldMessenger.of(context).showSnackBar(<br>            SnackBar(<br>              content: Text(&quot;Pressed Follow on $platform button&quot;),<br>              duration: const Duration(seconds: 1),<br>            ),<br>          );<br>          onPressed();<br>        },<br>        child: Text(&quot;Follow on $platform&quot;),<br>      )<br>    ]));<br>  }<br>}</pre><p>As we discussed above, we’ve the template text and accept platform and onPressed parameters. We replace platform wherever we need and call onPressed method as the extension of showing a snack bar.</p><p>Add the above code at the very end of the main.dart file.</p><h4>Integrate Custom Widget</h4><p>Let’s integrate our custom widget into our code.</p><p>Replace lines 44 to 56 with the following code,</p><pre>CustomButton(<br>  platform: &#39;Twitter&#39;,<br>  onPressed: () {<br>    // Open Twitter App<br>  },<br>),</pre><p>Replace lines 58 to 70 with the following code,</p><pre>CustomButton(<br>  platform: &#39;Instagram&#39;,<br>  onPressed: () {<br>    // Open Instagram App<br>  },<br>),</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/0*cO_KXebJg0iIAEKR.png" /><figcaption>After refactoring your code</figcaption></figure><p>Run your app now.</p><p>Unfortunately, you’ll not notice any change in the UI. However your underlying code has changed. That’s exactly what refactoring is.</p><p>Quoting from Martin Fowler,</p><blockquote><strong><em>Refactoring</em></strong><em> is a disciplined technique for restructuring an existing body of code, altering its internal structure without changing its external behavior.</em></blockquote><blockquote><a href="https://refactoring.com/"><em>https://refactoring.com/</em></a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/0*UHaugtuctYd0fa7Q.png" /><figcaption>Final app</figcaption></figure><p>You may ask a question by look at the above code. The line numbers 43 and 50 also contain the same code ( const SizedBox(height: 16),). Why don&#39;t you include that into your component.</p><p>That’s great if this question really hit your mind.</p><p>There is no need for the custom widget component to include the SizedBox component. Because, SizedBox component is added in the Home page to give some space between each component. It is not mandatory that whenever we use this button, we have to give a space at the top/bottom of the widget. However if such case arise, you can add the SizedBox widget inside your custom widget.</p><h3>What’s the benefit of building custom widget</h3><p>You don’t see a direct benefit right away. However, you may experience it in the future. Here’s a quick example for you.</p><p>Let’s assume you’ve built this app for a client. It has become a complex app and you’ve used this custom widget around 20 places in your app. The app is released and people enjoy using it. Around 6 months later, your client come back to you with the next version of changes. One of the items in the huge list is, “We’re coming up with a slight change in theme. Replace all the social media referral buttons to be in outlined shape and change the color to green”.</p><p>It is one simple configuration change in our custom widget. However assume, if you have not built the custom widget and copy/pasted the same code in all the 20 places. Then you have to carefully look at each place and replace them with care without touching other pieces of code.</p><p>These are the only 2 lines we have to change in the our custom widget</p><pre>OutlinedButton(<br>        style: OutlinedButton.styleFrom(foregroundColor: Colors.green),</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/0*XqT2_xuFeErbONEd.png" /><figcaption>After refactoring your code</figcaption></figure><p>If you have not refactored your code, you have to make this change in 20 places.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/0*zrIsIOA3oyFPXFJE.png" /><figcaption>Small change reflects everywhere</figcaption></figure><p>I’ve pushed my code to the same <a href="https://github.com/5minslearn/Flutter-Custom-Widget">Github repo</a>. Refer master branch for the non-refactored code and refactor branch for refactored code.</p><h4>Note</h4><p>Always use custom widgets for it’s specific use cases. For example, in our case, it is for Social media redirects. This widget should not be used at places which is unrelated to it’s context. If you do so, remember the above case where the client requirement was to change the design of only the social media referral buttons, but our change will be applied to all the other places where this widget has been used, leading to unexpected bugs. It is always advised to write unit test cases for Custom Widgets which will help us to mitigate the bugs earlier.</p><p>One more tip would be to name your component more readable. This makes the other developer know what the widget does just by reading it’s name. In our case, I’ve named it as CustomButton which makes no sense. Instead the best possible alternatives would be SocialMediaButton, SocialButton, etc. which fits into our use case.</p><h3>Conclusion</h3><p>In this blog, we learnt about building a custom widget by removing a duplicated code/component. Building custom widgets in Flutter promotes code re-usability, maintainability, consistency, abstraction, flexibility, and community collaboration. Custom widgets are a powerful tool in the Flutter developer’s toolkit, enabling the creation of beautiful and functional user interfaces while maximizing efficiency and maintainability.</p><p>Hope you enjoyed reading the article. If you wish to learn more about Flutter, subscribe to my article at my <a href="https://5minslearn.gogosoon.com/?ref=medium_flutter_custom_widget">site</a>.</p><p><em>Originally published at </em><a href="https://www.gogosoon.com/blog/how-to-build-a-custom-widget-in-flutter"><em>https://www.gogosoon.com</em></a><em> on June 7, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7526a8053b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn Networking in Flutter]]></title>
            <link>https://5minslearn.medium.com/learn-networking-in-flutter-d5bdc7ac37ce?source=rss-36827e865e1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5bdc7ac37ce</guid>
            <dc:creator><![CDATA[5MinsLearn]]></dc:creator>
            <pubDate>Tue, 16 May 2023 06:45:03 GMT</pubDate>
            <atom:updated>2023-07-20T04:59:18.610Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WR2ahTewLdaH5TRphUrhvQ.png" /><figcaption>Networking in Flutter</figcaption></figure><p>Almost all apps you use today will run by accessing the internet. You can hardly find an app that runs without connecting to the internet. Internet has become inevitable part of our life as it solves one of the most critical problems of humans i.e., data transfer. You either receive or send a data to someone. Be it a social media app, news app or whatever type it may be, there’s a data transfer.</p><p>Hence it is super important to learn networking if you’re learning mobile app development. In this article I’ll be sharing about building a super simple mobile app that fetches the data from internet and render it on the app.</p><h3>How to Create the Project</h3><p>Navigate to the folder where you want to create your project in the terminal and run the following command.</p><pre>git clone https://github.com/5minslearn/Flutter-Boilerplate.git</pre><p>Navigate to the Flutter-Boilerplate folder and run the flutter pub get command to install the dependencies.</p><pre>cd Flutter-Boilerplate/ <br>flutter pub get</pre><p>That’s it. We’ve got our dependencies installed.</p><p>Open the project in Visual Studio Code by running the code ./ command in the terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*v9J69-z71yd-LS0o.png" /></figure><p>Start your emulator/connect your device and press F5 in VS Code to run your app.</p><p>At the moment, the app will just contain an empty screen as shown in the below screenshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/0*xW4kqMQ08lhXup7Q.png" /></figure><p>Let’s build our networking app.</p><h3>Where to get the data</h3><p>It is the most obvious question. If we were to fetch something from the internet and render, we need an API server exposing the data we need. But, most people cannot afford to do that for learning purpose. To overcome this many people are offering free API services.</p><p>You can consume the data from their API services for learning purpose. However, we cannot validate the originality of the data as most of them will be random.</p><p>In this blog, we’ll be using the API exposed by <a href="https://sampleapis.com/">https://sampleapis.com/</a>. They expose an API endpoint that lists the Coding Resources. The URL of the endpoint is <a href="https://api.sampleapis.com/codingresources/codingResources">https://api.sampleapis.com/codingresources/codingResources</a>.</p><p>In our app, we’ll fetch the data from this endpoint and list them in our app.</p><h3>Install the dependencies</h3><p>Let’s install the dependencies needed to build this app. We need 2 dependencies. They are,</p><ol><li>http</li><li>url_launcher</li></ol><p>http package is used to make a call to the API endpoint. The url_launcher package is used to open a url in a external browser.</p><p>Open pubspec.yml file and add the following two packages in the dependencies section.</p><pre>http: ^0.13.6 <br>url_launcher: ^6.1.11</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/0*kpSrX8Hg55rEwXPs.png" /></figure><p>If you’re using VS Code as your IDE, the dependencies will be installed automatically by saving this file. For the other IDE’s, run flutter pub get on your project root folder to install the dependencies.</p><p>Import the http package in the lib/main.dart file</p><pre>import &#39;package:http/http.dart&#39; as http;</pre><p>Initialize a list object in the _MyHomePageState class by adding the following code.</p><pre>List _resources = [];</pre><p>Let’s write a method that makes a call to our API endpoint and decode them into a JSON object.</p><pre>void _fetchResources() async {<br>    final response = await http.get(Uri.parse(<br>        &#39;https://api.sampleapis.com/codingresources/codingResources&#39;));<br>    if (response.statusCode == 200) {<br>      final data = json.decode(response.body) as List;<br>      setState(() {<br>        _resources = data;<br>      });<br>    } else {<br>      throw Exception(&#39;Failed to load resources&#39;);<br>    }<br>  }</pre><p>Paste the above code into the _MyHomePageState class. In the above method, we&#39;re making a call to the API endpoint ( <a href="https://api.sampleapis.com/codingresources/codingResources">https://api.sampleapis.com/codingresources/codingResources</a>). From the response, we&#39;re validating if it is successful in receiving the data by checking if it&#39;s status code is 200 and throw error if it&#39;s not. We then decode the received data and save it in our app&#39;s state.</p><p>You may notice an error on pasting the above code at the json.decode part. In order to decode a JSON, we need import a convert package in our file. Add the following code at the top of the file.</p><pre>import &#39;dart:convert&#39;;</pre><p>Hopefully the error should be gone now.</p><p>We have a method that makes a call to the API endpoint and save the data in the state. Our next step is to trigger this method when we open the app.</p><p>We can do that by overriding the initState method.</p><pre>@override<br>  void initState() {<br>    super.initState();<br>    _fetchResources();<br>  }</pre><p>From the Flutter documentation,</p><blockquote><em>initState is called when this object is inserted into the tree. The framework will call this method exactly once for each </em><a href="https://api.flutter.dev/flutter/widgets/State-class.html"><em>State</em></a><em> object it creates.</em></blockquote><blockquote><a href="https://api.flutter.dev/flutter/widgets/State/initState.html"><em>https://api.flutter.dev/flutter/widgets/State/initState.html</em></a></blockquote><p>In the above code, we called our method _fetchResources() in the initState() method.</p><p>We got the list of items whenever we open the app. Our next step is to render them on UI.</p><p>Copy the below code and replace it with the build method of the _MyHomePageState class.</p><pre>@override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>        appBar: AppBar(<br>          title: Text(widget.title),<br>        ),<br>        body: _resources.isEmpty<br>            ? const Center(<br>                child: CircularProgressIndicator(),<br>              )<br>            : ListView.builder(<br>                itemCount: _resources.length,<br>                itemBuilder: (context, index) {<br>                  final resource = _resources[index];<br>                  return InkWell(<br>                      onTap: () =&amp;gt; {},<br>                      child: Card(<br>                          child: ListTile(<br>                        title: Text(resource[&#39;description&#39;]),<br>                        subtitle: Text(resource[&#39;url&#39;]),<br>                        leading: const CircleAvatar(<br>                            backgroundImage: NetworkImage(<br>                                &quot;https://images.unsplash.com/photo-1547721064-da6cfb341d50&quot;)),<br>                        trailing: Text(resource[&#39;types&#39;].join(&#39;, &#39;)),<br>                      )));<br>                }));<br>  }</pre><p>Let’s understand the above code.</p><p>We show a loader if our state has empty values. If it has some values in it, we’ll iterate through as a ListView builder and we render a Card widget for each item, displaying the description, url, and types of the resource.</p><p>That’s it.</p><p>Run the app by pressing F5 and you should be able to see the following screenshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/0*e4sp2D2CLhPrY0pd.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/0*Ln0vGbofXMC5wn-F.png" /></figure><p>That’s Awesome!!! Isn’t it?</p><p>But I feel there’s one small thing that’s missing in this. Briefing it here.</p><p>We’re able to see the list of the resources. But, we’re not able to view those resource. Some resources has small link that we can easily remember and type. But, few of them have a long url which is not possible for a typical human being to remember. Let’s add a small enhancement that when we press a resource, it’s link should be opened in our default browser.</p><p>The implementation of it is so simple in Flutter. This is the reason we added url_launcher package at the beginning of this blog.</p><p>Import the url_launcher package in our app.</p><pre>import &#39;package:url_launcher/url_launcher.dart&#39;;</pre><p>Add the following method in the _MyHomePageState class.</p><pre>_launchURL(String url) async {<br>    if (await canLaunch(url)) {<br>      await launch(url);<br>    } else {<br>      throw &#39;Could not launch $url&#39;;<br>    }<br>  }</pre><p>The above method accepts a url and validates the link and opens it in the browser.</p><p>We have to call this method on tapping the card. We can achieve that by calling this method in the onTap property of the InkWell widget.</p><p>Here’s the code for it.</p><pre>onTap: () =&gt; {_launchURL(resource[&#39;url&#39;])},</pre><p>Let’s run our app and test this.</p><p>Hope you were disappointed on tapping a card. Yes. I’m also disappointed while working on this.</p><p>You would have faced this error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/0*yIcpEaILH0KbbHFk.png" /></figure><p>Though the url is right, why is our system not opening this in a browser.</p><p>Well. We have to learn about intent action.</p><p>Quoting it from Android Developers documentation,</p><blockquote><em>An Intent provides a facility for performing late runtime binding between the code in different applications. Its most significant use is in the launching of activities, where it can be thought of as the glue between activities. It is basically a passive data structure holding an abstract description of an action to be performed.</em></blockquote><blockquote><a href="https://developer.android.com/reference/android/content/Intent"><em>https://developer.android.com/reference/android/content/Intent</em></a></blockquote><p>This basically means when we hand over something to the external app, we have to declare that in our app. For Android we have to define it in AndroidManifest.xml and for iOS most of these configurations go into Info.plist file.</p><p>Add the queries block in the following code to your AndroidManifest.xml file.</p><pre>&lt;manifest&gt;<br>    &lt;application&gt;<br>        ...<br>    &lt;/application&gt;<br>    &lt;queries&gt;<br>        &lt;intent&gt;<br>            &lt;action android:name=&quot;android.intent.action.VIEW&quot; /&gt;<br>            &lt;category android:name=&quot;android.intent.category.BROWSABLE&quot; /&gt;<br>            &lt;data android:scheme=&quot;https&quot; /&gt;<br>        &lt;/intent&gt;<br>    &lt;/queries&gt;<br>&lt;/manifest&gt;</pre><p>Uninstall the app from your mobile and run the app again.</p><p>Hopefully you should be able to see the link opened in the browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/0*7YFvfvdHRO5mL_a6.png" /></figure><h3>Conclusion</h3><p>In this article, you’ve learnt about networking in Flutter. We made a request to an API, render the list, and open the url in the browser.</p><p>This <a href="https://github.com/5minslearn/Flutter-Networking">repo</a> has my code. You can use it for your reference.</p><p>If you wish to learn more about Flutter, subscribe to my article by entering your email address in the below box.</p><p>Have a look at my <a href="https://5minslearn.gogosoon.com/?ref=medium_flutter_navigation_types">site</a> which has a consolidated list of all my blogs.</p><p><em>Originally published at </em><a href="https://www.gogosoon.com/blog/learn-networking-in-flutter"><em>https://www.gogosoon.com</em></a><em> on May 16, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5bdc7ac37ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use Elastic Beanstalk to deploy NodeJS app]]></title>
            <link>https://5minslearn.medium.com/how-to-use-elastic-beanstalk-to-deploy-nodejs-app-ef87ecbbaccb?source=rss-36827e865e1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef87ecbbaccb</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[elastic-beanstalk]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[5MinsLearn]]></dc:creator>
            <pubDate>Mon, 15 May 2023 13:50:28 GMT</pubDate>
            <atom:updated>2023-07-08T03:32:15.250Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xKNE-W4NRaJFyxosDji-8Q.png" /></figure><p>Building and managing applications on the cloud can be a daunting task, especially when it comes to handling different environments, scaling, and deploying updates. But there’s a service in AWS that can simplify this. AWS Elastic Beanstalk is here to make your life easier. It provides an easy-to-use platform for deploying, managing, and scaling your applications in the AWS Cloud.</p><p>In this blog post, we’ll dive into the basics of Elastic Beanstalk, and then walk you through the process of deploying a NodeJS app connected to RDS database. Let’s get started!</p><h3>What is Elastic Beanstalk?</h3><p>AWS Elastic Beanstalk is a fully managed service that helps you deploy, manage, and scale applications on AWS. It takes care of provisioning the required resources, such as EC2 instances, RDS databases, and load balancers. Elastic Beanstalk also handles application deployment, monitoring, and maintenance tasks so that you can focus on writing code and delivering features.</p><p>Elastic Beanstalk uses CloudFormation to provision resources. The good thing is you don’t need to write CloudFormation templates. It’ll be taken care by Elastic Beanstalk automatically.</p><p>Now that we have a basic understanding of Elastic Beanstalk, let’s dive into deploying our NodeJS app with an RDS connection.</p><h3>Preparing NodeJS source code</h3><p>We cannot deploy our app straight to Elastic Beanstalk (similar to deploying at EC2), we need to follow a few steps before deployment. It took hours for me to figure out this but I’ll help you to deploy it in 5 minutes.</p><p>In this blog, we’ll be deploying this <a href="https://github.com/5minslearn/eb-nodejs-rds">Node.js application</a>. But to deploy our code we don’t need a repo, instead we need a zip of our source code. You can download the zip file of the above repo <a href="https://github.com/5minslearn/eb-nodejs-rds/blob/master/nodejs-rds-sample.zip">here</a>.</p><p>Adding the steps here if you want to deploy your own app. But if you want to just deploy the above code, you can move to the next section (How to Create Elastic Beanstalk).</p><p>1. Ensure your package.json file has the start command and this start command should be configured to run your app. Beanstalk will execute npm start by default and throws error if it can&#39;t find it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/0*4pBNGV6kLWRXH3IF.png" /></figure><p>2. There’s super important thing about configuring environment variables. AWS follows pre-defined environment variables for RDS connections. Ensure you used the right naming. You can read this article by <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/using-features.managing.db.html">AWS</a> for additional information. A quick example for you if you don’t understand this point. To configure the hostname for the RDS, you have to use RDS_HOSTNAME environment variable. You app will not be able to connect if you used some other variable name (Eg. DB_HOSTNAME).</p><p>You can define custom environment variables in AWS Elastic Beanstalk console as per your need.</p><p>Here’s how your DB connection configuration should look like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/0*Js3mLN3zfuN9ffex.png" /></figure><p>3. Elastic Beanstalk (EBS) by default run on port 8080, so we have to configure our app to run on port 8080. It’s always best practice to add the port number in environment variables and configure it in the EBS console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/0*Wze8rwyCY6azKGli.png" /></figure><p>4. In order for Elastic Beanstalk to read our environment variables, we should add a file called .ebextensions in the project root directory with the following code.</p><pre>commands:<br>    setvars:<br>        command: /opt/elasticbeanstalk/bin/get-config environment | jq -r &#39;to_entries | .[] | &quot;export \(.key)=\&quot;\(.value)\&quot;&quot;&#39; &amp;gt; /etc/profile.d/sh.local<br>packages:<br>    yum:<br>        jq: []</pre><p>5. Install the dependencies by executing npm install and zip your code along with <strong>node_modules</strong> by executing the following command.</p><pre>zip [filename].zip -r ./</pre><p>Remember the zipped file should contain all files and subdirectories in the root folder and should not be inside any other folders. Because Elastic Beanstalk will check for package.json file in the root folder and throws error if it can&#39;t find it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/0*_5L6tJMUSuXHjnXS.png" /><figcaption>An example of correct folder structure</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/0*2RrBIl2XLUOJMY24.png" /><figcaption>Wrong folder structure (all files are inside the folder called source-code)</figcaption></figure><p>Now our app is ready lets create the Elastic Beanstalk application.</p><h3>How to Create Elastic Beanstalk</h3><h3>Step 1: Configure Your Environment</h3><ul><li>Navigate to the AWS Management Console and select Elastic Beanstalk from the Services menu. Click on “Create Application” button.</li><li>Select the Web server environment and provide a name for your app.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1RDRPNT1uzyUMR4w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P5ctV9IwQNojRRcIMpOekA.png" /></figure><ul><li>Choose Managed platform in “Platform type”, and Node.js in “Platform”, and leave the rest as it is.</li><li>Choose Upload your code in “Application code” section and upload the zip file.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*h4YjkA9p4EAm_FzW5SbYTw.png" /></figure><p>Set the version label to 1 and choose Single instance in “Presets” section and click Next.</p><p><strong>Note:</strong></p><p>Prefer High availability for production environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/0*zPtA8rrVbcp-Yk7q.png" /></figure><h3>Step 2: Configure service access</h3><p>In this section, we have to configure IAM roles.</p><ul><li>We need to create two IAM roles, one for Elastic Beanstalk and one for EC2</li><li>For service role, select Create and use new service role. It&#39;ll automatically create and provide required permissions</li><li>If you want to ssh into your EC2 instance via terminal, create a key-value pair and select it. Ignore this step if you don’t want to login into EC2.</li><li>Create an IAM role with the following permissions and add the role to “EC2 instance profile” and proceed Next</li><li>AWSElasticBeanstalkWebTier</li><li>AWSElasticBeanstalkWorkerTier</li><li>AWSElasticBeanstalkMulticontainerDocker</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P1hViq7-V2KJ_GMK.png" /></figure><h3>Step 3: Set up networking, database, and tags</h3><ul><li>Turn on the Enable database toggle and choose mysql Engine</li><li>Fill up the other fields based on your needs</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/0*Zmt7WpGWxwRxt-aM.png" /></figure><ul><li>Be super careful while selecting the “Database deletion policy”. As I’m creating the sample app I selected Delete option which will delete the database when the Elastic Beanstalk application is deleted. If you’re working on a production database, it’s always a best practice to choose Create Snapshot or Retain option.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*SstmWq-gakpTR-wEjENuvQ.png" /></figure><h3>Step 4: Configure instance traffic and scaling</h3><p>You don’t need to change anything here unless you exclusively need it. If you’re building this sample app leave the fields with default value. By default Elastic Beanstalk will create Amazon Linux machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/0*JPFveiKcenCPhk_m.png" /></figure><h3>Step 5: Configure updates, monitoring and logging</h3><p>Choose Basic in “Health reporting” and uncheck Managed updates activation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*2Ty78X4Oq_fvg_Xc.png" /></figure><ul><li>Add your environment variables and click Next</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*k6boGxz2pYn5d8ay.png" /></figure><p>Finally, review all your configurations and proceed with next. It takes time to provision RDS, so set back and have your coffee</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iG7FBtFoaxn6_j10.png" /></figure><p>By now you could’ve understand why I spent hours on it 😂. Every time I made a mistake I have to wait for about 10 to 15 minutes to check the result and redo all the above steps if something goes wrong. Elastic Beanstalk will definitely test your patience, so be calm and relax.</p><p>Once everything is done you could see health becomes green 🎉 and a domain URL will be generated 🥳</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zAz3AJgdNWeM3L6w.png" /></figure><p>If you used my example <a href="https://github.com/5minslearn/eb-nodejs-rds">repo</a> you’ll see the following page on opening the URL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/0*xVzJF0OQY2xGJNSz.png" /></figure><p>When you hit domain-url/hikes you can see the below page. Type some data and hit Record Hike button, the data will be stored in hikes table in RDS MySQL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/0*i8HNWhwIvYsU-WzC.png" /></figure><h3>Conclusion</h3><p>In this article, we’ve successfully deployed a NodeJS app with an RDS connection using AWS Elastic Beanstalk. This powerful service simplifies the deployment and management process, allowing us to focus on developing and scaling our applications.</p><p>If you are stuck at any point feel free to drop your queries to me at my <a href="https://www.gogosoon.com/cdn-cgi/l/email-protection#721300071c32151d151d011d1d1c5c111d1f">email</a>. I’ll be happy to help you.</p><p>Hope you enjoyed reading this article!</p><p>If you wish to learn more about AWS, subscribe to my newsletter by entering your email address in the below box.</p><p>Have a look at my <a href="https://5minslearn.gogosoon.com/?ref=medium_com_aws_ebs">site</a> which has a consolidated list of all my blogs.</p><p><em>Originally published at </em><a href="https://www.gogosoon.com/blog/how-to-use-elastic-beanstalk-to-deploy-nodejs-app"><em>https://www.gogosoon.com</em></a><em> on May 15, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef87ecbbaccb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker Extensions to Help You Improve Your Workflow — GoGoSoon]]></title>
            <link>https://5minslearn.medium.com/docker-extensions-to-help-you-improve-your-workflow-gogosoon-86365dcd7a3d?source=rss-36827e865e1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/86365dcd7a3d</guid>
            <dc:creator><![CDATA[5MinsLearn]]></dc:creator>
            <pubDate>Sun, 07 May 2023 15:54:56 GMT</pubDate>
            <atom:updated>2023-07-03T05:20:19.078Z</atom:updated>
            <content:encoded><![CDATA[<h3>Docker Extensions to Help You Improve Your Workflow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zb6bbwj2ZkjnJLUYItrRpA.png" /><figcaption>Poster</figcaption></figure><p>We all know that docker is getting popular day by day. A Lot of organizations also started using docker in their development lifecycle. So it is very important to update ourselves in terms of software development. ie, Docker itself is an automation tool in software development.</p><p>If you are new to docker please read our previous blogs related to docker, Then you can easily understand the workflow in docker.</p><p>In this blog, we can see about the top 5 simple and powerful docker extensions,</p><h3>Drone CI</h3><p>Before getting into this extension we should know about CI. CI — Continous Integration. Whenever we start with DevOps the first thing we need to learn is continuous integration. Nowadays, developers expect the code changes should immediately reflect the production or testing server. So to automate this we should enable the CI / CD Pipelines in the development lifecycle.</p><p>DroneCI is an open-source application that helps us to deploy our app continuously into our desired server. So DronCI is simple to set up and use. Let’s see how to deploy our NodeJS Application using DroneCI.</p><p>We can install it from the Docker extensions marketplace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/0*Ykq8WpJAIA_Km7W0.png" /><figcaption>JFrog installation in docker marketplace</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/0*N9_Cec2KlDkbELhg.png" /><figcaption>Import new pipelines</figcaption></figure><p>.drone.yml configuration. Put this file into the root of your Node project.</p><pre>kind: pipeline<br>type: docker<br>name: default<br><br>platform:<br> os: linux<br> arch: arm64<br><br>steps:<br>- name: message<br>  image: busybox<br><br>- name: test<br>  image: node<br>  commands:<br>  - npm install<br>  - npm test</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/0*LJf4PdJC-4lkv0Xe.png" /><figcaption>Imported pipelines</figcaption></figure><p>After importing the pipeline, you can run the pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*hB_TnpRf2zW6W5NDtqYJAA.png" /></figure><p>Here we are running only for testing the nodejs application, We can follow the same step to achieve the deployment also</p><h3>JFrog Scan</h3><p>We all know about docker images, and sometimes we need to work on some open-source docker images. This extension will be useful for the people who are all using open-source docker images.</p><p>Using the JFrog docker extension, We can scan any type of docker image, Moslty our internal docker images do not have any harmful configurations, So this is only useful for open-source or third-party docker images.</p><p>We can install it from the docker marketplace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/0*XjDomofsLq2Ogv0A.png" /><figcaption>JFrog installation in docker marketplace</figcaption></figure><p>Before using the JFrog, We need an active account from JFrog, So we create an account for free.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/0*JHk75uFKh1QeJAut.png" /><figcaption>JFrog Sign in console</figcaption></figure><p>After a successful sign in we can choose an Image to scan for vulnerabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/0*4c16enPXWAoBuDnm.png" /><figcaption>Choose an Image to scan for vulnerabilities</figcaption></figure><p>We can see that, The image is being scanned for vulnerabilities. It took some time</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/0*g80G5Mm1HfqZ2cHz.png" /><figcaption>JFrog Scanning the images</figcaption></figure><p>Oops, our docker image has 25 critical vulnerabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/0*cb6JecatghhiS89F.png" /><figcaption>Vulnerabilities found in the docker image</figcaption></figure><h3>Portainer</h3><p>Portainer provides a web-based interface for managing containers, images, volumes, networks, and other Docker-related resources.</p><p>This extension is used to manage container hosts, Docker Swarm clusters, and Kubernetes clusters in a much simpler way.</p><p>Using portainer we can manage the running containers, Images, and Environments in a uniform UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/0*qxfwlZSX1Buw1B6z.png" /><figcaption>Managing containers using portainer dashboard</figcaption></figure><p>We can quickly take any type of action on the containers and Images.</p><h3>Disk Usage</h3><p>Disk Usage is an official Docker extension that provides developers with insights into their Docker disk usage. Once installed, this extension thoroughly examines and categorizes the disk space occupied by various entities, such as images, containers, local volumes, and build cache. By utilizing this extension, users can efficiently manage their disk space by removing unnecessary objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/0*Vdub1a5FJ7atWy8B.png" /><figcaption>Disk space usage by docker</figcaption></figure><p>This optimization process is crucial to free up disk space for critical resources. The Disk Usage extension is readily accessible on the Docker extensions tab and can be easily enabled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/0*bSB3aThqSKtqGnRb.png" /><figcaption>Details of disk usage by docker images, containers and local volumes</figcaption></figure><p>We can reclaim the space by removing unused images, dangling images and build caches. So this disk image extension itself gives some suggestions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/0*DCk99zQXUHY-bmNs.png" /><figcaption>Reclaim disk space usage by docker</figcaption></figure><h3>Okteto</h3><p>Okteto is a useful tool that enhances your productivity and satisfaction by providing you with pre-configured environments. This helps free up your time from manually setting up environments.</p><p>This accelerates the software development process and release cycles when combined with a proper CI/CD platform. It also enables you to create preview environments resembling test and development environments, allowing you to test changes before deploying them to production. With Okteto, cloud-native development becomes much easier.</p><p>The Okteto extension is readily available in the Docker desktop extension marketplace and you can install it with a simple click.</p><p>To leverage the benefits of Okteto, you’ll need to configure the Okteto manifest for your application. After installing the extension, it prompts you to launch a remote environment. Choose the application folder with the Okteto manifest file and start exploring.</p><p>In simple words, you can connect to a remote environment using Okteto cloud. For more information on how to set up and use Okteto, refer to their <a href="https://www.okteto.com/docs/">official documentation</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/0*WoUkZgbzUQm4oxF_.png" /><figcaption>Octeto connect to remote environment</figcaption></figure><p>In order to sign in to Okteto, you need a business email.</p><p>After successful login, you have to choose the docker-compose.yml file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/0*Bui7hx2NNIA8s9cz.png" /><figcaption>Okteto connect to remote environment</figcaption></figure><h3>Conclusion</h3><p>Docker is a powerful tool that simplifies the development process and enables developers to build, test, and deploy applications quickly and efficiently.</p><p>By using these Docker extensions, you can take advantage of additional features and functionality to streamline your workflow and optimize your Docker environment.</p><p>If you wish to learn more about Docker, subscribe to my article by visiting my <a href="https://5minslearn.gogosoon.com/?ref=medium_docker_extensions">site</a>.</p><p>Have a look at my <a href="https://5minslearn.gogosoon.com/?ref=medium_docker_extensions">site</a> which has a consolidated list of all my blogs.</p><p><em>Originally published at </em><a href="https://www.gogosoon.com/blog/docker-extensions-to-help-you-improve-your-workflow"><em>https://www.gogosoon.com</em></a><em> on May 7, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86365dcd7a3d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Types of Navigation in Flutter — GoGoSoon]]></title>
            <link>https://5minslearn.medium.com/types-of-navigation-in-flutter-gogosoon-dc2a80c749ea?source=rss-36827e865e1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc2a80c749ea</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[5minslearn]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[flutter-navigation-drawer]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[5MinsLearn]]></dc:creator>
            <pubDate>Mon, 24 Apr 2023 12:58:11 GMT</pubDate>
            <atom:updated>2023-06-03T06:22:37.234Z</atom:updated>
            <content:encoded><![CDATA[<h3>Types of Navigation in Flutter — GoGoSoon</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wtyJIgd2i-hIut9Nc3fkJg.png" /></figure><p>Almost all the apps designed and developed will have either one of the 3 or all 3 types of navigation. These 3 types of navigation has been common to all apps. Flutter is no exemption to that convention. Flutter also supports all these 3 types of navigation. Navigation in flutter is almost exactly similar to other apps. But I felt it was super smooth when I built it on Flutter.</p><p>In this article, let’s try to build a Flutter app implementing all the 3 types of navigation in a single app.</p><h3>Types of Navigation</h3><p>As I have been saying 3 types of navigation from the beginning, you may wonder what are the 3?</p><p>Here it is,</p><ol><li>Stack Navigation</li><li>Tab Navigation</li><li>Drawer Navigation</li></ol><p>Let’s understand quickly about each of them.</p><h4>Stack Navigation</h4><p>Picture a deck of cards, where you can add or remove cards from the top of the stack. Stack Navigation in Flutter works in a similar fashion. It helps you navigate between pages or screens by stacking new pages on top of existing ones. When you move to a new screen, the current screen is pushed onto the navigation stack, and when you return, the top screen is popped off the stack. This navigation type is commonly used for hierarchical and linear flows within an app.</p><h4>Tab Navigation</h4><p>Tabs are a staple of mobile app navigation, allowing users to quickly switch between different sections or views without losing their current context. Flutter makes it easy to implement tabbed navigation with its built-in widgets, such as TabBar and TabBarView. By using these widgets, you can create a beautiful and functional tab navigation experience, perfect for organizing content into logical sections. With Flutter, you have the freedom to customize the appearance of your tabs, making it simple to create a unique look and feel for your app.</p><h4>Drawer Navigation</h4><p>The Drawer Navigation pattern, also known as the “hamburger menu” or “side menu,” is a popular navigation style in mobile apps. It consists of a hidden panel that slides out from the side of the screen, revealing a menu with various navigation options. This space-saving technique keeps your app’s main content visible while providing easy access to additional features or sections.</p><p>Let’s start building the app</p><h3>Create the Project</h3><p>Instead of creating a new project everytime from the scratch, I’ve created a boilerplate app and uploaded in <a href="https://github.com/5minslearn/Flutter-Boilerplate">Github</a>. You can pull the code and run. Hope that make project creation simple.</p><p>Navigate to the folder where you want to create your project in Terminal and run the following command.</p><pre>git clone https://github.com/5minslearn/Flutter-Boilerplate.git</pre><p>Navigate to the Flutter-Boilerplate folder and run flutter pub get command to install the dependencies.</p><pre>cd Flutter-Boilerplate/ flutter pub get</pre><p>That’s it. We got our dependencies installed.</p><p>Open the project in Visual Studio Code by running code ./ command in Terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4jVUWjerACQdVDE_.png" /><figcaption>Clone repo and install dependencies</figcaption></figure><p>Start your emulator/connect your device and press F5 in VS Code to run our app.</p><p>Our app will just contain an empty screen as shown in the below screenshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/0*B7FYDtMWLti3Cakv.png" /><figcaption>Flutter app with empty screen</figcaption></figure><p>Let’s build all 3 types of navigation into our app.</p><p>This is how our final app will look.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/0*I99eCCp2gUAiMJ0P.png" /><figcaption>Look of our final app</figcaption></figure><p>We’ll have a Drawer &amp; Tab Navigator at the top. Pressing on the button in the first tab will take us to the next page via Stack Navigator.</p><h3>Tab Navigation</h3><p>Let’s begin with building the tab navigator. Let’s assume the tab will be on the home page (ideally it’ll be).</p><p>Create a new filed named tab.dart in the lib/ directory. Add the following code.</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;./tabs/tab1.dart&#39;;<br>import &#39;./tabs/tab2.dart&#39;;<br>import &#39;./tabs/tab3.dart&#39;;<br>class HomePage extends StatelessWidget {<br>  const HomePage({super.key});<br>  @override<br>  Widget build(BuildContext context) {<br>    return DefaultTabController(<br>      length: 3,<br>      child: Scaffold(<br>          appBar: AppBar(<br>            title: const Text(&quot;Home&quot;),<br>            bottom: const TabBar(<br>              tabs: [<br>                Tab(icon: Icon(Icons.phone_android)),<br>                Tab(icon: Icon(Icons.tablet_android)),<br>                Tab(icon: Icon(Icons.laptop_windows)),<br>              ],<br>            ),<br>          ),<br>          body: const TabBarView(<br>            children: [<br>              Tab1(),<br>              Tab2(),<br>              Tab3(),<br>            ],<br>          )),<br>    );<br>  }<br>}</pre><p>In the above code, we’re creating a class named HomePage. In the build method, we return DefaultTabController widget, which is basically a tab view. We define that we need 3 tabs in the length property. At the bottom of the appBar property we have defined icons for each tab (Phone, Tablet, and Computer icons). Below that we define the body property with a TabBarView rendering all the tabs inside it.</p><p>Immediately you paste the above code, you’ll notice lot of errors being highlighted in your VS Code editor. The reason is, if you look at the top 4 lines, the 1st line is the import of Flutter’s Material UI package whereas the rest 3 are import from the user defined files. We haven’t created them yet. So, your code editor will throw an error in those lines and at the last 3 lines where we call Tab1(), Tab2(), and Tab3(). Because, these classes are imported from those files. Let&#39;s resolve this issue now.</p><p>Create a new folder named tabs inside lib/ directory and create 3 files naming them as tab1.dart, tab2.dart, and tab3.dart.</p><p>Copy the below content into tab1.dart file.</p><pre>import &#39;package:flutter/material.dart&#39;;<br>class Tab1 extends StatelessWidget {<br>  const Tab1({super.key});<br>  @override<br>  Widget build(BuildContext context) {<br>    return SizedBox(<br>      width: double.infinity,<br>      child: Column(<br>        mainAxisAlignment: MainAxisAlignment.center,<br>        children: [<br>          const Text(&quot;Mobiles&quot;),<br>          Padding(<br>            padding: const EdgeInsets.only(top: 16.0),<br>            child: ElevatedButton(<br>              onPressed: () {<br>                Navigator.of(context).pushNamed(&quot;/secret&quot;);<br>              },<br>              child: const Text(&#39;Disclose Secret&#39;),<br>            ),<br>          ),<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><p>Copy the below content into tab2.dart file.</p><pre>import &#39;package:flutter/material.dart&#39;;<br>class Tab2 extends StatelessWidget {<br>  const Tab2({super.key});<br>  @override<br>  Widget build(BuildContext context) {<br>    return SizedBox(<br>      width: double.infinity,<br>      child: Column(<br>        mainAxisAlignment: MainAxisAlignment.center,<br>        children: const [<br>          Text(&quot;Tablets&quot;),<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><p>Copy the below code into tab3.dart file.</p><pre>import &#39;package:flutter/material.dart&#39;;<br>class Tab3 extends StatelessWidget {<br>  const Tab3({super.key});<br>  @override<br>  Widget build(BuildContext context) {<br>    return SizedBox(<br>      width: double.infinity,<br>      child: Column(<br>        mainAxisAlignment: MainAxisAlignment.center,<br>        children: const [<br>          Text(&quot;Laptops&quot;),<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><p>If you look at the code for all the 3 files, you’ll notice everything is common except that the first tab file ( tab1.dart) has an additional button called &quot;Disclose Secret&quot; and pressing that will navigate to the /secret route. It&#39;ll not throw any error as this route has not been defined yet. The other 2 files ( tab2.dart and tab3.dart) will show only the text.</p><p>All the errors you saw in tab.dart file will be resolved now. But, if you run your app, you will not notice any changes in the output. This is because, we have just created the tab layout and we haven&#39;t mapped it to our main.dart file.</p><p>Add the following line at the top of the main.dart file.</p><pre>import &#39;./tab.dart&#39;;</pre><p>Replace home: const MyHomePage(title: &#39;Home&#39;), with home: const HomePage(), in the build method of the MyApp class.</p><p>Save the file and run your app. You should be able to see the tab layout on your screen now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/0*geHMM3PtMJEGAvFK.png" /><figcaption>Tab Layout in Flutter App</figcaption></figure><p>Don’t press the “Disclose Secret” button. If you press it, it will throw an error. Because, remember I mentioned earlier, we setup a route navigation in the onPress property of this button, while the route is not yet defined.</p><p>“Let’s click that and see what happens”,</p><p>Hopefully, this thought would have hit your mind by now. It’s not your mistake, but it’s human mentality. We’ll be curious to explore the things which the other (experienced person) do not recommend to do. You’ll see the following error (Exception in programming terminology) if you click on the button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*Fic5R0FTA0Oxb8UG.png" /><figcaption>Flutter Router Exception</figcaption></figure><p>In a nutshell, this error screenshot describes that the provided route does not exist.</p><h3>Drawer Navigation</h3><p>Own next target is to add a drawer navigation. But before that, we have to create 2 files. They are,</p><ol><li>drawer.dart - To show the Navigation Drawer</li><li>about.dart - An option will be provided on Drawer Navigator to navigate here</li></ol><p>Create drawer.dart file inside lib/ directory and not inside tab/ directory. tab/ directory is only for tabs and we don&#39;t need to touch that further as we&#39;re done with the tabs. Copy the below code into the drawer.dart file.</p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>class MyDrawer extends StatelessWidget {<br>  const MyDrawer({super.key});<br><br>  navigateTo(String route, BuildContext context) {<br>    Navigator.of(context).pushReplacementNamed(route);<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Drawer(<br>      child: ListView(<br>        padding: const EdgeInsets.all(16.0),<br>        children: &lt;Widget&gt;[<br>          ListTile(<br>            leading: const Icon(Icons.home),<br>            title: const Text(&#39;Home&#39;),<br>            onTap: () {<br>              navigateTo(&quot;/home&quot;, context);<br>            },<br>          ),<br>          ListTile(<br>            leading: const Icon(Icons.info),<br>            title: const Text(&#39;About&#39;),<br>            onTap: () {<br>              navigateTo(&quot;/about&quot;, context);<br>            },<br>          ),<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><p>In this file, we define the class named MyDrawer. In the build method we render the Drawer widget with Home and About options in list. Click on those options will navigate us to the appropriate routes.</p><p>Create about.dart file in the same directory and copy the below code.</p><pre>import &#39;./drawer.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br><br>class About extends StatelessWidget {<br>  const About({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      drawer: const MyDrawer(),<br>      appBar: AppBar(title: const Text(&quot;About&quot;)),<br>      body: const Center(child: Text(&quot;About&quot;)),<br>    );<br>  }<br>}</pre><p>In this file, we create a class named About which returns a Scaffold widget containing the drawer which we defined right before this file. The appBar and the body will show the text &quot;About&quot;.</p><p>Again, you’ll not be able to see these changes immediately in the app. Because, we haven’t linked it into the main.dart file.</p><p>Before we linking them, we have one item in our backlog. Let’s finish it and come back to linking them altogether.</p><p>Create a file named secret.dart in the lib/ directory and copy the below code.</p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>class SecretPage extends StatelessWidget {<br>  const SecretPage({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>        appBar: AppBar(<br>          // backgroundColor: Colors.red,<br>          title: const Text(&quot;Secret&quot;),<br>        ),<br>        body: SizedBox(<br>          width: double.infinity,<br>          child: Column(<br>            mainAxisAlignment: MainAxisAlignment.center,<br>            children: const &lt;Widget&gt;[<br>              Text(&quot;Nothing to show&quot;),<br>            ],<br>          ),<br>        ));<br>  }<br>}</pre><p>In this file, we have created a class named SecretPage and return just a Text in the `body`. Nothing fancy here. It&#39;s a super simple Flutter widget.</p><p>Our backlog item is also done. This is the most awaited time. We’re going to define our routes now.</p><p>Open main.dart file and add the following imports at the top of the file.</p><pre>import &#39;./about.dart&#39;;<br>import &#39;./secret.dart&#39;;</pre><p>Replace the build method of MyApp class with the below code.</p><pre>@override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      routes: &lt;String, WidgetBuilder&gt;{<br>        &quot;/about&quot;: (BuildContext context) =&gt; const About(),<br>        &quot;/home&quot;: (BuildContext context) =&gt; const HomePage(),<br>        &quot;/secret&quot;: (BuildContext context) =&gt; const SecretPage(),<br>      },<br>      initialRoute: &quot;/home&quot;,<br>      title: &#39;Flutter Navigation&#39;,<br>      theme: ThemeData(<br>        primarySwatch: Colors.blue,<br>      ),<br>      home: const HomePage(),<br>    );<br>  }</pre><p>In the above code, you can see we’re defining the MaterialApp to contain routes. They’re defined as key-value pairs, mapping a route with a Widget. We have defined 3 routes.</p><ul><li>/about - Route for drawer navigator</li><li>/home - Route for tab navigator</li><li>/secret - Route for stack navigator</li></ul><p>We have set the initial route to be /home, which has the tab navigator.</p><p>Run the app and you should be able to see the following output on your device.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/0*a6WuN45BlPQQWQCO.png" /><figcaption>Merged Tab and Drawer View</figcaption></figure><p>On pressing the “Disclose Secret” button you’ll be taken to the Secret page which we created (ideally it does not have any secret). You should also be scroll through the tabs smoothly.</p><p>By now, I hope you would have noticed an error here. If not, I’m revealing here for you. The back button is shown on the 1st screen of our app.</p><p>“What is the need to show the back button on the 1st screen?”</p><p>That’s an error and we have to resolve it. Press the back button and let’s see what happens. Hopefully, you saw the same I saw. The back button was hidden and we see just the “Home” title in the appBar (similar to the below screenshot).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/0*nD8rls8h0jatN8Fo.png" /><figcaption>Back button issue</figcaption></figure><p>But there’s an another issue available in the same screen. Hopefully you got that too. If not, don’t worry, I’m revealing it right here.</p><p>“Can you access the drawer navigator by any means?”</p><p>No. Right?</p><p>But, do you know the fix for above two issues is the same. If we fix the 2nd issue, the 1st issue will automatically be fixed.</p><p>That’s great. But, How to fix the 2nd issue?</p><p>You have to show the drawer navigator button (Hamburger icon) on the top left. This will eventually hide the back button.</p><p>Open tab.dart file and import the drawer file at the top of this file.</p><pre>import &#39;./drawer.dart&#39;;</pre><p>Add the following line inside the Scaffold widget of the build method.</p><pre>drawer: const MyDrawer(),</pre><p>That’s it.</p><p>Here’s the output you can see when you run your app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/0*htXRFFHhJtlt6EvZ.png" /><figcaption>App look after the issues are fixed</figcaption></figure><h3>Conclusion</h3><p>n this article, you’ve learnt about navigation in Flutter. We’ve implemented all 3 types of navigation in a single app. Ideally, this will not be the case with any real app you build. Most apps will be built on either 1 or 2 types of navigation.</p><p>This <a href="https://github.com/5minslearn/Flutter-Navigation-Types">repo</a> has my code. You can use it for your reference.</p><p>If you wish to learn more about Flutter, subscribe to my article by entering your email address in the below box.</p><p>Have a look at my <a href="https://5minslearn.gogosoon.com/?ref=medium_flutter_navigation_types">site</a> which has a consolidated list of all my blogs.</p><p><em>Originally published at </em><a href="https://www.gogosoon.com/blog/types-of-navigation-in-flutter"><em>https://www.gogosoon.com</em></a><em> on April 24, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc2a80c749ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is CloudFormation & How to use it to deploy NodeJS]]></title>
            <link>https://5minslearn.medium.com/what-is-cloudformation-how-to-use-it-to-deploy-nodejs-b262658e47ff?source=rss-36827e865e1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b262658e47ff</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[nodejs-deployment]]></category>
            <category><![CDATA[aws-cloudformation]]></category>
            <dc:creator><![CDATA[5MinsLearn]]></dc:creator>
            <pubDate>Wed, 19 Apr 2023 12:49:28 GMT</pubDate>
            <atom:updated>2023-06-02T11:51:15.231Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bjhyLbNJLK_LZ8R-EfGPxQ.png" /><figcaption>Deploy Node.Js app using AWS CloudFormation</figcaption></figure><p>Imagine you have built a great product. The user base of your product has been increasing rapidly. You want to scale your product to the people around the world. To achieve that you should have a good cloud infrastructure.</p><p>But you’ll definitely be exhausted if you manage your cloud infrastructure manually? You would be wondering, “Well. How are the enterprise companies managing now?”.</p><p>They automate their cloud infrastructure management via code. Well, that’s exactly AWS CloudFormation offers — a way to manage your cloud infrastructure as code!</p><p>In this blog, we’ll explore the basics of AWS CloudFormation and how it can help you automate your infrastructure management. Let’s dive into the world of infrastructure as code!</p><h3>What is CloudFormation</h3><p>AWS CloudFormation is a service that helps you automate creating and managing your cloud resources. Imagine you’re building a house, and you want to ensure everything is in the right place — the walls, the roof, the doors, and the windows. With CloudFormation, you can create a blueprint for your house, and specify exactly what you want and where you want it.</p><p>Similarly, CloudFormation allows you to create a blueprint for your cloud infrastructure. You can specify what resources you want to create, (Eg. EC2 servers, databases, storage, etc.) and how they should be configured. CloudFormation takes care of creating and managing those resources for you automatically.</p><p>CloudFormation will be extremely helpful in few cases. Listing few of them below,</p><ol><li>Managing the infrastructure changes in multiple environments (Development, Staging, Production)</li><li>Re-create the same infrastructure in a different region / account</li><li>Unfortunate accidental deletion of a resource can be re-created with the exact configuration in seconds (not manually, as you have all configurations in your code)</li></ol><p>The best part is that CloudFormation makes updating your infrastructure super simple and automatic. If you want to add a new resource, change a configuration, or delete a resource, you can update your blueprint, and CloudFormation will handle the changes for you.</p><h3>How CloudFormation works</h3><p>You may wonder how CloudFormation works? It’s simple, we’ll upload our CloudFormation templates in Amazon S3 behind the scenes and then CloudFormation will pull our template from the S3. One important point to note is we cannot edit the template once uploaded. We need to re-upload the updated template to AWS and then CloudFormation will compare and figure out what needs to be updated</p><p>One awesome feature is you can delete all resources created by CloudFormation in one click by deleting the stack. CloudFormation stack is nothing but a collection of AWS resources that you can manage as a single unit. You define a stack by creating a CloudFormation template that describes the resources you want to create, and then you create the stack by running the template</p><h3>Deploying CloudFormation Templates</h3><p>We can deploy the CloudFormation template in two ways. One is using CloudFormation Designer and the other is writing the code in a YAML file. If you’re not familiar with YAML then you can go for CloudFormation Designer. It’s also recommended for those who don’t know to code. It allows you to create and edit templates graphically, making it easier to visualize your infrastructure and simplify the template creation process. However, in this blog we’ll be writing YAML code to deploy our app.</p><h3>How to create CloudFormation Template to deploy NodeJS</h3><p>CloudFormation Template can be created using YAML or JSON file but we’re going to use YAML file. In this template, we’ll be creating an EC2 instance, security group and add a script to deploy a simple NodeJS app.</p><h3>CloudFormation Template to create EC2 instance</h3><p>There are over 224 types of resources but now we need to create EC2 resource. <strong>Resources</strong> represent the different AWS Components that will be created and configured. The <strong>Resource</strong> types identifiers are in below form.</p><pre>AWS::aws-product-name::data-type-name</pre><p>So for the EC2 instance, the resource is Aws::EC2::Instance. To learn more about AWS resources and syntax check out the AWS official <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html">documentation</a> and play with it. If you look at <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html">EC2 documentation</a> and scroll down you can see how to declare EC2 instance. Both JSON and YAML syntax is available but we&#39;ll stick with YAML for this blog. There will be lot of properties available to customize the creation of EC2 instances. But for now, we&#39;ll be configuring AvailabilityZone, ImageId and InstanceType which are very basic properties to create an EC2 instance.</p><pre><br>Resources:<br>  SampleNodejsDeploy:<br>    Type: AWS::EC2::Instance<br>    Properties:<br>      AvailabilityZone: us-east-1a<br>      ImageId: ami-a4c7edb2<br>      InstanceType: t2.micro</pre><p>Here SampleNodejsDeploy refers to the name of the block. You can name your resource as your wish.</p><p>Let’s see the process to deploy the NodeJS app.</p><h3>How to deploy NodeJS App using CloudFormation template</h3><p>We’re going to deploy the NodeJS app using the UserData property in the EC2 resource. For people who don&#39;t know about EC2 user data, it is a feature of AWS EC2 which allows us to pass information during the launch of the EC2 instance. It can be used to perform custom actions, such as installing software and executing the script. Let&#39;s write the bash script to deploy NodeJS app and attach it to the user data.</p><p>Here is the simple script to deploy the NodeJS app</p><pre>#!/bin/bash<br>set -e<br>curl -sL https://deb.nodesource.com/setup_16.x | bash -<br>sudo apt install nodejs<br>node -v<br>npm -v<br>curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -<br>echo &quot;deb https://dl.yarnpkg.com/debian/ stable main&quot; | sudo tee /etc/apt/sources.list.d/yarn.list<br>sudo apt update &amp;amp;&amp;amp; sudo apt install yarn<br>yarn --version<br>sudo -i -u ubuntu bash &amp;lt;&amp;lt; EOF<br>set -e<br>cd /home/ubuntu<br>sudo npm install -g pm2<br>git clone https://github.com/5minslearn/node_with_docker.git<br>cd node_with_docker<br>yarn install<br>pm2 start yarn --time --interpreter bash --name sample_node -- start -p 8000<br>EOF</pre><p>The above script installs the nodejs, yarn and pm2. Clones the NodeJS project from <a href="https://github.com/5minslearn/node_with_docker.git">git</a>, installs the dependencies and starts the app with PM2.</p><p>Having this script, let’s attach it to the CloudFormation template.</p><h3>Attaching UserData into CloudFormation Template</h3><pre>Resources:<br>  SampleNodejsDeploy:<br>    Type: AWS::EC2::Instance<br>    Properties:<br>      InstanceType: t2.micro<br>      ImageId: ami-014d05e6b24240371<br>      UserData:<br>        Fn::Base64:<br>          |<br>          #!/bin/bash<br>          set -e<br>          curl -sL https://deb.nodesource.com/setup_16.x | bash -<br>          sudo apt install nodejs<br>          node -v<br>          npm -v<br>          curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -<br>          echo &quot;deb https://dl.yarnpkg.com/debian/ stable main&quot; | sudo tee /etc/apt/sources.list.d/yarn.list<br>          sudo apt update &amp;amp;&amp;amp; sudo apt install yarn<br>          yarn --version<br>          sudo -i -u ubuntu bash &amp;lt;&amp;lt; EOF<br>          set -e<br>          cd /home/ubuntu<br>          sudo npm install -g pm2<br>          git clone https://github.com/5minslearn/node_with_docker.git<br>          cd node_with_docker<br>          yarn install<br>          pm2 start yarn --time --interpreter bash --name sample_node -- start -p 8000<br>          EOF</pre><p>You can notice the UserData property is added to the EC2 block. Fn::Base64 is a function in AWS CloudFormation that allows users to encode a string to base64 format. This function can be used to pass sensitive information, such as credentials, to AWS resources in a secure manner. Since EC2 user data is not encrypted it&#39;s always best practice to encode it. Right below the line, you can notice a small vertical bar (|). It is used for multi-line string support as our script is more than 1 line.</p><p>Alright. Now we have a script to deploy the NodeJS. But, we have to remember one super important item. By default NodeJS applications run on port 8000. We should expose the port 8000 from EC2. Here comes the need to create a security group configuration for our EC2 instance.</p><h3>How to create a security group using CloudFormation Template</h3><p>It’s exactly similar to creating an EC2 instance, except replacing the type from Instance to SecurityGroup.</p><pre>SampleNodejsDeploySG:<br>    Type: AWS::EC2::SecurityGroup<br>    Properties:<br>      GroupDescription: for the app nodes that allow ssh, http, 8000<br>      SecurityGroupIngress:<br>      - IpProtocol: tcp<br>        FromPort: &#39;80&#39;<br>        ToPort: &#39;80&#39;<br>        CidrIp: 0.0.0.0/0<br>      - IpProtocol: tcp<br>        FromPort: &#39;22&#39;<br>        ToPort: &#39;22&#39;<br>        CidrIp: 0.0.0.0/0<br>      - IpProtocol: tcp<br>        FromPort: &#39;8000&#39;<br>        ToPort: &#39;8000&#39;<br>        CidrIp: 0.0.0.0/0</pre><p>The above code is self explanatory that we defined a Security group, allowing ports 22(SSH port), 80(HTTP port), 8000 (for NodeJS). We named the Resource as SampleNodejsDeploySG.</p><h3>Link Security Group to EC2</h3><p>You may encounter an obvious question, “We’ve created a template for creating Security group but how will this be linked to EC2 instance?”.</p><p>The solution is simple, CloudFormation provides an intrinsic function called !Ref that allows us to reference a resource or parameter within a CloudFormation template.</p><pre>Resources:<br>  SampleNodejsDeploy:<br>    Type: AWS::EC2::Instance<br>    Properties:<br>      InstanceType: t2.micro<br>      ImageId: ami-014d05e6b24240371<br>      SecurityGroups:<br>        - !Ref SampleNodejsDeploySG<br>      UserData:<br>        Fn::Base64:<br>          |<br>          #!/bin/bash<br>          set -e<br>          curl -sL https://deb.nodesource.com/setup_16.x | bash -<br>          sudo apt install nodejs<br>          node -v<br>          npm -v<br>          curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -<br>          echo &quot;deb https://dl.yarnpkg.com/debian/ stable main&quot; | sudo tee /etc/apt/sources.list.d/yarn.list<br>          sudo apt update &amp;amp;&amp;amp; sudo apt install yarn<br>          yarn --version<br>          sudo -i -u ubuntu bash &amp;lt;&amp;lt; EOF<br>          set -e<br>          cd /home/ubuntu<br>          sudo npm install -g pm2<br>          git clone https://github.com/5minslearn/node_with_docker.git<br>          cd node_with_docker<br>          yarn install<br>          pm2 start yarn --time --interpreter bash --name sample_node -- start -p 8000<br>          EOF<br>  SampleNodejsDeploySG:<br>    Type: AWS::EC2::SecurityGroup<br>    Properties:<br>      GroupDescription: for the app nodes that allow ssh, http<br>      SecurityGroupIngress:<br>      - IpProtocol: tcp<br>        FromPort: &#39;80&#39;<br>        ToPort: &#39;80&#39;<br>        CidrIp: 0.0.0.0/0<br>      - IpProtocol: tcp<br>        FromPort: &#39;22&#39;<br>        ToPort: &#39;22&#39;<br>        CidrIp: 0.0.0.0/0<br>      - IpProtocol: tcp<br>        FromPort: &#39;8000&#39;<br>        ToPort: &#39;8000&#39;<br>        CidrIp: 0.0.0.0/</pre><p>You can notice the SecurityGroups property is added to the EC2 instance and the created Security Group configuration is linked to the EC2 instance by using the !Ref parameter. Now we have the CloudFormation template. But we&#39;re not yet complete. We still miss one more thing. Can you figure it out? We created an EC2 instance, and we allowed an SSH port but to log in using SSH we need to attach a key-value pair right? Let&#39;s do that.</p><p>We can attach Key-value pair name directly into the template. For example, let’s say your key-value pair name is 5minslearn you can attach the property KeyName directly to the EC2 resource block like this or we can use parameters.</p><pre>Resources:<br>  SampleNodejsDeploy:<br>    Type: AWS::EC2::Instance<br>    Properties:<br>      InstanceType: t2.micro<br>      ImageId: ami-014d05e6b24240371<br>      KeyName: 5minslearn<br>      SecurityGroups:<br>        - !Ref SampleNodejsDeployS</pre><h3>How to use parameters in the CloudFormation template</h3><p>We can use parameters to get the name of the key-value pair from the user while creating the stack. Basically, parameters allow us to pass input values into CloudFormation templates at runtime. Let’s see how to do that</p><pre>Parameters:<br>  SSHKey:<br>    Type: AWS::EC2::KeyPair::KeyName<br>    Description: name of the key pair to ssh into the instance<br>Resources:<br>  SampleNodejsDeploy:<br>    Type: AWS::EC2::Instance<br>    Properties:<br>      InstanceType: t2.micro<br>      ImageId: ami-014d05e6b24240371<br>      KeyName: !Ref SSHKey<br>      SecurityGroups:<br>        - !Ref SampleNodejsDeploySG<br>      UserData:<br>        Fn::Base64:<br>          |<br>          #!/bin/bash<br>          set -e<br>          curl -sL https://deb.nodesource.com/setup_16.x | bash -<br>          sudo apt install nodejs<br>          node -v<br>          npm -v<br>          curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -<br>          echo &quot;deb https://dl.yarnpkg.com/debian/ stable main&quot; | sudo tee /etc/apt/sources.list.d/yarn.list<br>          sudo apt update &amp;amp;&amp;amp; sudo apt install yarn<br>          yarn --version<br>          sudo -i -u ubuntu bash &amp;lt;&amp;lt; EOF<br>          set -e<br>          cd /home/ubuntu<br>          sudo npm install -g pm2<br>          git clone https://github.com/5minslearn/node_with_docker.git<br>          cd node_with_docker<br>          yarn install<br>          pm2 start yarn --time --interpreter bash --name sample_node -- start -p 8000<br>          EOF<br>  SampleNodejsDeploySG:<br>    Type: AWS::EC2::SecurityGroup<br>    Properties:<br>      GroupDescription: for the app nodes that allow ssh, http<br>      SecurityGroupIngress:<br>      - IpProtocol: tcp<br>        FromPort: &#39;80&#39;<br>        ToPort: &#39;80&#39;<br>        CidrIp: 0.0.0.0/0<br>      - IpProtocol: tcp<br>        FromPort: &#39;22&#39;<br>        ToPort: &#39;22&#39;<br>        CidrIp: 0.0.0.0/0<br>      - IpProtocol: tcp<br>        FromPort: &#39;8000&#39;<br>        ToPort: &#39;8000&#39;<br>        CidrIp: 0.0.0.0/0</pre><p>In the above template, we added a parameter to get the key-pair name and referenced it to KeyName property.</p><p>Great! We successfully created a CloudFormation template to create an EC2 instance and security group. In addition to that, we also added a script to deploy the NodeJS app. Now it’s time to create a CloudFormation stack.</p><h3>How to create CloudFormation stack</h3><p>The first step is to log in to the AWS console and search for CloudFormation in the search bar. You can see the below page. Click on stacks in the left sidebar to get started with CloudFormation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Y1DZv43Dksj7ec3e.png" /></figure><p>Click on create stack button to create the CloudFormation stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZDTpmS5rSvjAc8Bd.png" /></figure><p>As we have our template ready, select “Template is ready” and choose “Upload a template file” in the Template source and upload the template file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/0*JV9SQ5gAqcp1YQAX.png" /></figure><p>Once you upload the file, “View in Designer” button will be enabled. Click on it to view our template design.</p><h3>How to validate the CloudFormation template</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ARTLDC12apadoDna.png" /></figure><p>To validate our template click on the “Tick” icon on top left in the designer. It will validate and show us errors if any. Once the validation is done, click on the “Cloud” icon to the left of “Tick” icon. It will take you to create stack page.</p><p>In the stack details page, enter the stack name and select your key-value pair. If you don’t have key-value pair create one and select it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/0*SSJA130GoyOQB-jD" /></figure><p>Leave the Configure stack options section as it is and click continue since we don’t need any IAM permissions or advanced options.</p><p>Then review the page and submit the template. The template will start creating the resources</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zXWPZS79lrCbJQh1" /></figure><p>Once creation is done click on resources tab, you’ll be able to see the resources we created (EC2 and Security group resources).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FJQDGCbXIt9oFcqq.png" /></figure><p>Click on the EC2 instance, you can see our instance will be up and running. Copy the public IPv4 address</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hsbD1PLPmZDhrMMa.png" /></figure><p>Now go to browser and type <a href="http://:8000">http:&lt;ip-address&gt;//:8000</a> (In my case it is <a href="http://54.176.19.18:8000/),">http://54.176.19.18:8000/),</a> you can see the below page</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/0*RvjLxSxFdjz3YdSX.png" /></figure><p>This means our NodeJS app successfully got deployed!</p><p><strong>Note:</strong></p><p>EC2 user data will take some time to install dependencies. So for the first time, the page will take long time to load. Please be patient till the site is loaded.</p><h3>Deleting CloudFormation Stack</h3><p>If you no longer need the stack, you can delete it from the CloudFormation console. Select the stack you want to delete, click “Delete Stack,” and confirm the action. This action will delete all resources created using this stack. In our case, it’ll delete both EC2 and Security Group. You don’t need to delete the EC2 instance and Security Group individually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JBUZk6nfeaYcx_do" /></figure><h3>Conclusion</h3><p>In this article, we learned what is CloudFormation, it’s working, creating and deleting a template stack.</p><p>Hope you enjoyed reading this article! If you are stuck at any point feel free to drop your queries to me at my <a href="https://www.gogosoon.com/cdn-cgi/l/email-protection#3f5e4d4a517f585058504c505051115c5052">email</a>. I’ll be happy to help you!</p><p>If you wish to learn more about AWS, subscribe to my <a href="https://5minslearn.gogosoon.com/?ref=medium_aws_CF">newsletter</a></p><p><em>Originally published at </em><a href="https://www.gogosoon.com/blog/what-is-cloudformation-how-to-use-it-to-deploy-nodejs"><em>https://www.gogosoon.com</em></a><em> on April 19, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b262658e47ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Docker Compose? When and How to use it? — GoGoSoon]]></title>
            <link>https://5minslearn.medium.com/what-is-docker-compose-when-and-how-to-use-it-gogosoon-76cc521e4ce0?source=rss-36827e865e1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/76cc521e4ce0</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[compose]]></category>
            <category><![CDATA[5minslearn]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[mongodb]]></category>
            <dc:creator><![CDATA[5MinsLearn]]></dc:creator>
            <pubDate>Mon, 10 Apr 2023 12:56:30 GMT</pubDate>
            <atom:updated>2023-05-24T05:44:55.034Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is Docker Compose? When and How to use it? — GoGoSoon</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gt6AsDGGAq69FTKefl5kLA.png" /><figcaption>Docker compose with an example</figcaption></figure><p>Docker helps you to setup development environment on your machine quickly. It hardly takes a couple of minutes for the entire process to complete. But let’s assume you were assigned on a project which requires at least 10 different services in running state to run your project. Assuming your project requires Java 8, Node 14, MySQL, MongoDB, Ruby on rails, RabbitMQ, etc. Ideally this may not be the case, but it’s just an assumption. In such case, you have to pull all those images individually from Docker and start all of them in their containers. At some point, one process may depend on another to run. So, you have to order them. It would be good if it’s a one time process. But, not just once, every day, every time you start working on your project, you have to start all these services.</p><p>That’s a tedious process right?</p><p>To overcome this Docker introduced a concept called Multi Containers (Docker Compose). Before learning about docker compose, let’s quickly learn how to start a database host in docker. In the example part of this tutorial, we’ll spin up a NodeJS container and MongoDB container together. Learning about MongoDB at the beginning will give you a good understanding when we move to docker compose.</p><p>Let’s split this tutorial into 2 sections.</p><ol><li>How to use docker as a Database host (MongoDB)</li><li>Docker compose with an example (NodeJS &amp; MongoDB)</li></ol><h3>How to use docker as a Database host</h3><p>If you had experience on backend development, you might have a chance to handle multiple database. Databases like MySQL/Postres to handle relational data and Cassandra/MongoDB to handle unstructured data.</p><p>Do you know a secret, We can work on Back-end development without installing the database on your machine locally. Yes, we can use the docker as a database host. It has all the dependencies by default in the particular image file.</p><h3>Why do we need to use Database in Docker instead of Local?</h3><p>As I’ve already mentioned in my old blog, Docker helps us maintain consistent versions across platforms &amp; environments. Let’s consider there are a group of people working in your team on MongoDB version 5.0. If a new techie joins your team, he/she needs to set up the same version with the exact configuration manually. What if they install the latest version of MongoDB (6.0) which will lead to some conflict. This will be nightmare if it spreads to everyone’s device.</p><p>To overcome this, We can use the MongoDB in docker with a custom configuration and push the MongoDB Image to the docker hub internally. If a new person comes in they can pull the image and start the implementation without any manual configuration.</p><p>Let’s quickly get into the advantages of using a database in docker.</p><ol><li>By using this implementation we can ensure that everyone in a team uses the exact runtimes and configuration without any external resources.</li><li>It’s very easy to set up and we can start/stop the server quickly using the docker desktop</li></ol><h3>How to setup MongoDB using Docker</h3><p>Hope you’re aware of Docker Hub. If not, here’s a short intro. Docker hub is a platform where we can find, and share docker images in public or private. It is more similar to GitHub / GitLab. In a nutshell, it’s a repository for docker images.</p><p>The first step is to pull the official docker image from the docker hub.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kgKNEmA-lVUXO5cf.png" /><figcaption>MongoDB image in Docker Hub</figcaption></figure><pre>docker pull mongo:latest</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/0*J9ePcfQt4WnRpkcb" /><figcaption>Pull MongoDB image from Docker</figcaption></figure><p>Once you’re done pulling the MongoDB image, open your Docker Desktop and you’ll be able to see it there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/0*1Q_JhZTRR8BULWZb" /><figcaption>Docker Desktop Dashboard</figcaption></figure><p>Let’s run our MongoDB image using the docker run command.</p><pre>docker run -d -p 27017:27017 --name mongo-server-local mongo: latest</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/0*ulO6nUScOTVfvAo7" /><figcaption>Run the docker image</figcaption></figure><p>We successfully run the docker image. Now we can see the container running on the docker desktop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/0*9gQIAt95NTKv59AN" /><figcaption>Docker Desktop Container Dashboard</figcaption></figure><p>So, the MongoDB server is running on your machine. Let’s ensure this in the browser. Hit <a href="http://localhost:27017/">http://localhost:27017</a> on your browser and you should be able to see the message as shown in the screenshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/0*8pPd49C5w_v6eJPk" /><figcaption>Output from MongoDB when accessing via HTTP</figcaption></figure><p>Interesting right?</p><p>We can stop/start the MongoDB server using docker whenever we need.</p><h3>Important Note</h3><ol><li>It is not recommended to use the docker as a database for production</li><li>Do not use docker database for large scale applications</li></ol><h3>What is docker-compose</h3><p>Let’s come back to docker-compose.</p><p>Docker Compose is a tool used to define and share multi-container applications. This means we can run a project with multiple containers using a single source.</p><p>For example, assume you’re building a project with NodeJS and MongoDB together. We can create a single image that starts both containers as a service, you don’t need to start each separately.</p><p>Interesting right? And this solves the problem which I called out at the very beginning of this article.</p><p>To achieve this we need to define a docker-compose.yml.</p><p><strong>docker-compose.yml</strong></p><p>The compose file is a YML file defining services, networks, and volumes for a docker container. There are several versions of the Compose file format available — 1, 2, 2.x, and 3.x.</p><p>Before proceeding further, here’s a important note to us from the <a href="https://docs.docker.com/compose/">Docker Compose team</a>.</p><blockquote><em>From the end of June 2023 Compose V1 won’t be supported anymore and will be removed from all Docker Desktop versions.</em></blockquote><blockquote><em>Docker</em></blockquote><p>We are using version 3 in this article.</p><pre>version: &#39;3&#39;<br>services:<br>  app:<br>    image: node:latest<br>    container_name: app_main<br>    restart: always<br>    command: sh -c &quot;yarn install &amp;&amp; yarn start&quot;<br>    ports:<br>      - 8000:8000<br>    working_dir: /app<br>    volumes:<br>      - ./:/app<br>    environment:<br>      MYSQL_HOST: localhost<br>      MYSQL_USER: root<br>      MYSQL_PASSWORD: <br>      MYSQL_DB: test<br>  mongo:<br>    image: mongo<br>    container_name: app_mongo<br>    restart: always<br>    ports:<br>      - 27017:27017<br>    volumes:<br>      - ~/mongo:/data/db<br>volumes:<br>  mongodb:</pre><p>Let’s dismantle the above code and understand one by one.</p><p>version - Refers to the docker-compose version (Latest 3)</p><p>services - Define the services that we need to run</p><p>app - Custom name for one of your containers</p><p>image - Image which we have to pull. Here we are using node:latest and mongo.</p><p>container_name - Name for each container</p><p>restart - Start/Restart a service container</p><p>port - Define the custom port to run the container</p><p>working_dir - The current working directory for the service container</p><p>environment - Define the environment variables, such as DB credentials, etc.</p><p>command - Command to run the service</p><h3>How to run the multi-container?</h3><p>We need to build it using docker build.</p><pre>docker compose build</pre><p>After successfully building, We can run the containers using up Command.</p><pre>docker compose up</pre><p>If you want to run the container in detached mode just use -d flag.</p><pre>docker compose up -d</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/0*w0waf5MrY7st_s-1.png" /><figcaption>Run all images in a single compose command</figcaption></figure><p>Fine, We are good to go. The containers are up and running. Let’s check the container list.</p><pre>docker compose ps</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*23u4dGYH8sOWkQRH.png" /><figcaption>Status of running docker containers</figcaption></figure><p>Hurray, We can see that there are two containers running at the same time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/0*VudgiPaGYSluXbqW.png" /><figcaption>Testing NodeJS</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/0*eXNGbThIlQZe47r5" /><figcaption>Testing MongoDB</figcaption></figure><p>To have a look at the data in your MongoDB, you have to install MongoDB Compass.</p><p>Here’s the screenshot of it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*31WfCc34WiRdHcoE.png" /><figcaption>MongoDB Compass</figcaption></figure><h3>Conclusion</h3><p>In this article, you have learnt about Docker Compose with an example. Using this multiple containers you can spin up any type of service such as RabbitMQ, Apache Kafka and run in a single source of service. Hope you enjoyed reading this article.</p><p>Give a clap 👏 if you like the article and learnt something from it. I’m happy to listen to your comments and suggestions.</p><p>Subscribe to my email newsletter at my <a href="https://5minslearn.gogosoon.com/?ref=medium_docker_compose">site</a> (<a href="https://5minslearn.gogosoon.com/?ref=medium_docker_compose">https://5minslearn.gogosoon.com</a>) which also has a consolidated list of all my blogs.</p><p>Cheers!!!</p><p><em>Originally published at </em><a href="https://www.gogosoon.com/blog/what-is-docker-compose-when-and-how-to-use-it"><em>https://www.gogosoon.com</em></a><em> on April 10, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76cc521e4ce0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn state management in Flutter by building a simple todo app]]></title>
            <link>https://5minslearn.medium.com/learn-state-management-in-flutter-by-building-a-simple-todo-app-bbc1543f897a?source=rss-36827e865e1f------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbc1543f897a</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[to-do-list-app]]></category>
            <dc:creator><![CDATA[5MinsLearn]]></dc:creator>
            <pubDate>Tue, 04 Apr 2023 12:29:08 GMT</pubDate>
            <atom:updated>2023-05-15T15:19:09.894Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b8E7NDWwo8M7YNI7sQN7kw.png" /></figure><p>State management is a complex topic and is also a necessary topic in mobile application development. It plays a major role in building dynamic mobile apps. You’ll be able to build any kind of dynamic application if you master state management. This is because the UI that’s being rendered on the mobile will be determined by the state of the data that your app holds at that time. Hence, it becomes inevitable to master state management in front-end application development.</p><p>In this article, we’ll learn state management by building a Todo app in Flutter.</p><p>A quick little theory on state management.</p><h3>What is State</h3><p>State defines the user interface of your app. In other words, the user interface is built by the current state of the app. When a state of the Flutter app changes, it’ll trigger the re-draw of the user interface. This is called Declarative UI and Flutter follows the same, whereas the native mobile apps (Android &amp; iOS) are built with Imperative UI, where the user interface is defined earlier.</p><h3>Types of State</h3><p>There are 2 types of state. They are,</p><h4>Ephemeral State</h4><p>Ephemeral state is the state that is contained in a single widget or a screen/page of an app.</p><h4>App State</h4><p>It is the state that is shared between user sessions and is used across many parts of the app.</p><h3>How to choose the state for my app</h3><p>There is no single rule to choose either state. It’s depends on your use case. It’s advised to prefer Ephemeral state at first and refactor your code in future if you face any need to use App state.</p><h3>What will we build</h3><p>We’ll be building a Todo app. This app will have the functionality to create a todo item, list all the added items, update an item and delete an item. Here’s the sneak peak (screenshot) for you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/0*7cSV-l9bxLmwvyi5.png" /><figcaption>Todo App</figcaption></figure><h3>App Development</h3><p>Let’s put on our development shoes and start building our app.</p><h4>Create a project</h4><p>Here are the super simple steps to create our Flutter project. If you want a detailed explanation, please read the <a href="https://www.freecodecamp.org/news/how-to-build-a-simple-login-app-with-flutter/">“How to Create the Project” section in the blog</a> and come back here.</p><ol><li>Open your VS Code</li><li>Hit “CTRL+SHIFT+P” (Mac user replace CTRL with CMD key)</li><li>Type “Flutter”</li><li>Select “Flutter: New Project” option</li><li>Select “Application” from the next list</li><li>Select the folder to create your project in the next prompt</li><li>On the final prompt, enter your app name and press “Enter”</li></ol><p>That’s it!!! Our boilerplate app is ready.</p><p>Select the preferred device to run your app on the bottom right and hit “F5”. Your app will run on your selected device. You should see the following screen in next few seconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/0*9wuvlR7y7315h_1Q.png" /><figcaption>Flutter Boilerplate App</figcaption></figure><h3>Refactor</h3><p>We have a Flutter boilerplate app. By default, it’ll have a lot of items, let’s refactor our code. We’ll be working on main.dart file in lib/ folder to build this entire app.</p><h4>Initialize Git</h4><p>Initialize Git by running git init in the root folder of your repo.</p><h4>Remove comments</h4><p>I’ve removed all the comments in the main.dart file and added a commit.</p><h4>Rename Classes</h4><p>Rename MyApp to TodoApp in the main method by pressing F2 key in VS Code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/0*0VPsMVY3ja4Zzk9P.png" /></figure><p>On the first page, we’ll be listing the created to-do items. Let’s rename it from MyHomePage to TodoList.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/0*grflMKkG6jR2pY_c.png" /></figure><p>In the above screenshot, the title of the MaterialApp is set to “Flutter Demo” and title passed in TodoList is set to “Flutter Demo Home Page”. Let’s change both of that to “Todo Manager”.</p><h3>Build Todo App</h3><p>Let’s build the core functionality of our app.</p><p>We need a Todo class. This class will define the properties of a todo. In our case, we&#39;ll having the following items.</p><ol><li>Name of todo</li><li>Status of todo (Backlog / Completed)</li></ol><p>Let’s define a Todo class with the above properties.</p><pre>class Todo { <br>Todo({required this.name, required this.completed}); <br>String name; <br>bool completed; <br>}</pre><p>Add the above code at the bottom of the main.dart file.</p><h4>Add a Todo</h4><p>Look at your code for a class named _TodoListState. In the body of the build method, set the children property to empty array. Refer the below screenshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*79z5nWHLPQ6wAl5x.jpg" /><figcaption>Before and After of removing the Text widgets</figcaption></figure><p>Remove the 2 Text widget inside that children property.</p><p>Replace the counter variable with a todo list.</p><pre>int _counter = 0;</pre><p>Replace the above line with the following lines. The first line is the todo list and the second line defines the controller to get the name of the todo from the user.</p><pre>final List _todos = []; <br>final TextEditingController _textFieldController = TextEditingController();</pre><p>Remove the _incrementCounter method and add the method to add a todo.</p><pre>void _addTodoItem(String name) { <br>setState(() { _todos.add(Todo(name: name, completed: false)); }); <br>_textFieldController.clear(); <br>}</pre><p>So far we have defined our todo list, a input controller and created a method that accepts an input text and add that to the todo list with completed status set to false and clear the input field. The reason we have used the setState method is to refresh the UI after we update the todo list. As our component is a stateful widget, whenever a change in state is detected, the UI will render again with the updated state.</p><p>We have built the functionality code to add a todo. Let’s build the UI code. Let’s ask the user the name of todo on pressing the Floating action button at the bottom right. When the user try to save the todo, we’ll call the _addTodoItem method defined above.</p><pre>floatingActionButton: FloatingActionButton( <br>onPressed: () =&gt; _displayDialog(), <br>tooltip: &#39;Add a Todo&#39;, <br>child: const Icon(Icons.add), ),</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/0*zoyUKBKLfHt6qIbB.jpg" /><figcaption>Before and After of Floating Action Button code</figcaption></figure><p>In the above method, we have changed the onPressed property to call _displayDialog method. As it’s not defined yet, it’ll shown an error. We’ll define the method next. We have also changed the tooltip property to “Add a Todo”.</p><p>Here’s the code (_displayDialog method) to show a dialog box with a input field, add, and cancel button. Add this method inside the _TodoListState class.</p><pre>Future _displayDialog() async { <br>return showDialog( <br>context: context, <br>T: false, <br>builder: (BuildContext context) { <br>return AlertDialog( <br>title: const Text(&#39;Add a todo&#39;), <br>content: TextField( <br>controller: _textFieldController, <br>decoration: const InputDecoration(hintText: &#39;Type your todo&#39;), <br>autofocus: true, ), <br>actions: [ <br>OutlinedButton( <br>style: OutlinedButton.styleFrom( <br>shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(12),<br> ), ), <br>onPressed: () { <br>Navigator.of(context).pop(); <br>}, child: const Text(&#39;Cancel&#39;), ), <br>ElevatedButton( <br>style: ElevatedButton.styleFrom( <br>shape: RoundedRectangleBorder( <br>borderRadius: <br>BorderRadius.circular(12), ), ), <br>onPressed: () { <br>Navigator.of(context).pop(); <br>_addTodoItem(_textFieldController.text); }, <br>child: const Text(&#39;Add&#39;), <br>), <br>], <br>); <br>}, ); }</pre><p>Let’s understand this huge piece of code.</p><p>The Future class is used for asynchronous computation.</p><p>Quoting from the <a href="https://api.flutter.dev/flutter/dart-async/Future-class.html">documentation</a>,</p><p>“An asynchronous computation may need to wait for something external to the program (reading a file, querying a database, fetching a web page) which takes time. Instead of blocking all computation until the result is available, the asynchronous computation immediately returns a Future which will <strong><em>eventually</em></strong> &#39;complete&#39; with the result. &quot;</p><p>In our case, it’ll wait for the user to tap the Add or Cancel button.</p><p>The _displayDialog method will return the showDialog method by building the UI.</p><p>The barrierDismissible property is used to define if the pop up has to be closed if the user taps outside of the alert dialog. We have set that to false which means the alert dialog will not be closed on taping outside.</p><p>The builder of this showDialog method, returns an AlertDialog consisting of title, content, and actions property. The title is set to display a text &quot;Add a todo&quot;. The content property will render an text input field with automatic focus enabled and the hint &quot;Type your todo&quot;. The actions property will render 2 buttons. They&#39;re Cancel and Add buttons. The Cancel button is an outlined button, pressing it will close the dialog. The Add button adds the text to the todo list and closes the dialog.</p><p>Let’s test our app. Click on the floating action button and you should see the UI similar to the one below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/0*juHClEjOJCUXx776.png" /></figure><p>If you try to add a todo, it’ll be added to our todo list. But, you’ll not be able to see any change on UI.</p><h4>List the Todos</h4><p>We have added the code to add todos to the list. But Wait. How can we verify that? We have to find if the todo is actually added to the list.</p><p>Let’s verify that by rendering the list of todo items in the UI. To do so, we have to design the UI for a single todo. Let’s do that.</p><p>Add the following code at the end of main.dart file.</p><pre>class TodoItem extends StatelessWidget { <br>TodoItem({required this.todo}) : super(key: ObjectKey(todo)); <br>final Todo todo; <br>TextStyle? _getTextStyle(bool checked) { <br>if (!checked) return null; <br>return const TextStyle( <br>color: Colors.black54, <br>decoration: TextDecoration.lineThrough, ); } <br>@override <br>Widget build(BuildContext context) { <br>return ListTile( onTap: () {}, <br>leading: Checkbox( checkColor: <br>Colors.greenAccent, <br>activeColor: Colors.red, <br>value: todo.completed, <br>onChanged: (value) {}, ), <br>title: Row(children: [ <br>Expanded( child: Text(todo.name, <br>style: _getTextStyle(todo.completed)), ), <br>IconButton( <br>iconSize: 30, <br>icon: const Icon( Icons.delete, color: Colors.red, ), <br>alignment: Alignment.centerRight, <br>onPressed: () {}, ), ]), ); } }</pre><p>Here’s the brief explanation of the above code.</p><p>We created a class with the TodoItem and we extend it from StatelessWidget class as we don&#39;t need to maintain state for this class. We accept a Todo, which is passed via constructor to our class. The code in the build method determines the UI. It renders the ListTile widget with the Checkbox widget passed to the leading property. The title property renders a row of Text and IconButton widgets. The Text widget shows the name of the todo and the IconButton widget displays the delete icon. Notice the _getTextStyle method passed to the style property of the Text widget. This method strikes the text if the todo is marked as complete. Nothing changes on tapping any of these widgets as the corresponding properties are left empty (onTap, onChanged, and onPressed).</p><pre>ListView( <br>padding: const EdgeInsets.symmetric(vertical: 8.0), <br>children: _todos.map((Todo todo) { <br>return TodoItem( <br>todo: todo, ); }).toList(), ),</pre><p>Here’s the highlighted screenshot showing the changes on the build method of _TodoListState class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/0*0Eo2q1xylxXFDZ7U.jpg" /></figure><p>The above code defines a ListView widget iterating over the created todos and passing each todo to the TodoItem widget.</p><p>We’re done with listing the todos. Let’s verify if both creating and viewing a todo works fine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/0*zNci2m2y9AqBd51L.png" /></figure><p>Cool!!! Here are our todos.</p><p>Tapping on either Checkbox or Delete button will have no effect.</p><p>Hope you’ll got a clue on what we’ll be doing next. Yes, we’ll be adding the code to mark the todo as completed and delete a todo item.</p><h4>Update a Todo</h4><p>Let’s mark the todo as complete on pressing the checkbox near each todo.</p><p>We have 2 fields in our Todo class. They’re name and completed status. Whenever a Todo is created, the default value of completed field is set to false. This means the todo is in progress. We can change that to true, whenever we complete the task.</p><p>Define a method called _handleTodoChange in the _TodoListState class. Add this method below the _addTodoItem method which we defined to add a todo to the list.</p><pre>void _handleTodoChange(Todo todo) { <br>setState(() { <br>todo.completed = !todo.completed; }); }</pre><p>In the above code, we accept a todo and change the completed status of the todo. So, whenever this method is called with a todo, it’s completed status will change from true to false or vice versa. Remember we have wrapped this inside a setState method to render the UI after making the change.</p><p>We have to trigger this method when a user taps on a todo or taps on a checkbox. We should pass this method to the TodoItem class. While calling the TodoItem in the build method of the _TodoListState class, pass the _handleTodoChange method as shown below.</p><pre>return TodoItem( todo: todo, onTodoChanged: _handleTodoChange, );</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fJoPDD-UPVl6983O.jpg" /></figure><p>As we’re passing the method to TodoItem class, we should receive the same method in TodoItem class. To do so, we have to define this method in the constructor of TodoItem class. Go to TodoItem and change the constructor to include onTodoChanged method.</p><pre>TodoItem({required this.todo, required this.onTodoChanged}) : super(key: ObjectKey(todo));</pre><p>You could notice in the above code that we use <strong>this.</strong>onTodoChanged, which means we&#39;re binding the method passed to a method in this TodoItem class.</p><p>Let’s define a method with the same name and set the return type to void (as we don&#39;t expect anything from that method).</p><pre>final void Function(Todo todo) onTodoChanged;</pre><p>So, wherever we call this method in our code, the status of our todo will be changed to the opposite. Let’s call this method in the onTap property of ListTile widget and onChanged property of Checkbox widget.</p><pre>onTap: () { onTodoChanged(todo); },</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/0*0CCj0piy3I25cmRQ.jpg" /></figure><p>That’s it. We’re done. Let’s run our app and verify if we’re able to complete the todo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/0*TU5Bh4N4EWe64XWZ.png" /></figure><p>That’s Awesome right? We’re able to mark the todo as complete and revert back.</p><h4>Delete a Todo</h4><p>We have only one item left to complete this app. We should be able to delete a todo which we may create by mistake or you may feel that it’s no longer applicable.</p><p>Steps to delete a todo is almost similar to updating a todo. We’ll doing the exact 4 steps as we did for updating a todo.</p><ol><li>Define the _deleteTodo method</li><li>Pass the method on TodoItem render</li><li>Receive the method on TodoItem constructor</li><li>Bind the method</li><li>Call the method on button tap</li></ol><p>I would recommend you to try this by yourself as we’ll be repeating the steps we did earlier. After you’re done, you can verify your implementation by cross checking with my steps.</p><p>Here’s the method to delete the todo. Add this in the _TodoListState class below the _handleTodoChange method.</p><pre>void _deleteTodo(Todo todo) { setState(() { _todos.removeWhere((element) =&gt; element.name == todo.name); }); }</pre><p>This method accepts a todo. Compares it with the todo list and identifies the todo which matches with this name and deletes it from the list and finally updates the state.</p><p>Let’s pass the method reference to TodoItem in the build method of _TodoListState class.</p><pre>return TodoItem( todo: todo, onTodoChanged: _handleTodoChange, removeTodo: _deleteTodo);</pre><p>Change the constructor to accept removeTodo method.</p><pre>TodoItem( {required this.todo, required this.onTodoChanged, required this.removeTodo}) : super(key: ObjectKey(todo));</pre><p>Define a method with the same name and set the return type to void (as we don&#39;t expect anything from this method).</p><p>Our final step is to call this method on pressing the delete button.</p><pre>IconButton( iconSize: 30, icon: const Icon( Icons.delete, color: Colors.red, ), alignment: Alignment.centerRight, onPressed: () { removeTodo(todo); }, ),</pre><p>That’s it. I hope it’s super simple. Let’s test our app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*TRPaftZGzir8Yhb-.jpg" /></figure><p>Wow!!! That works.</p><p>In the above screenshot, you can see I created a todo with the name “Call SC service men” which should be created as “Call AC service men”. So, that was a mistake. I don’t want that todo now as it’ll confuse me. I would rather create a new todo with right spelling. So, I pressed the delete button which almost instantly deleted my todo.</p><p>Cool! We have built our own todo app.</p><h3>Conclusion</h3><p>In this article, you’ve learnt about state management in Flutter. Along with that, we’ve built a simple todo app in Flutter implementing CRUD functionality. CRUD stands for Create, Read, Update, and Delete. We created a todo, listed that on UI, updated it’s status, and finally deleted it.</p><p>This <a href="https://github.com/5minslearn/Flutter-Todo-App">repo</a> has my code. You can use it for your reference.</p><p>Here are few exercise to challenge yourself. Try to extend this app by adding the following functionalities.</p><ol><li>Show a message saying “No todo exist. Please create one and track your work”, if no todo was created</li><li>I know a bug in this app. I hope you don’t know. I’m revealing it here. But you have to fix it. Create two todos with same name and try to delete one. You’ll be amazed to see both of them deleted together. Here’s a tip for you to fix. Assign a random id for each todo and while deleting filter the todo by id.</li><li>Add functionality to edit the name of a todo</li><li>This app was completely built on Ephemeral state. So, if you close and open the app again, your old todo items will not be there. Add a functionality to store the todo in the device storage. Show the todos to the user when they reopen the app by reading them from your device storage.</li></ol><p>If you wish to learn more about Flutter, subscribe to my <a href="https://5minslearn.gogosoon.com/?ref=medium_flutter_getting_started">newsletter</a></p><p>Have a look at my <a href="https://5minslearn.gogosoon.com/?ref=medium_flutter_getting_started">site</a> which has a consolidated list of all my blogs.</p><p><em>Originally published at </em><a href="https://www.gogosoon.com/blog/learn-state-management-in-flutter-by-building-a-simple-todo-app"><em>https://www.gogosoon.com</em></a><em> on April 4, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbc1543f897a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>