<?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 Mahesh Jamdade on Medium]]></title>
        <description><![CDATA[Stories by Mahesh Jamdade on Medium]]></description>
        <link>https://medium.com/@maheshjamdade?source=rss-a565d616dfb4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*phK5I3cjCO1dKUyKWvybUg.jpeg</url>
            <title>Stories by Mahesh Jamdade on Medium</title>
            <link>https://medium.com/@maheshjamdade?source=rss-a565d616dfb4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 17:48:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@maheshjamdade/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[Inside the Agentic Code Editors a deep dive]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://levelup.gitconnected.com/inside-the-agentic-code-editors-a-deep-dive-a4abfee40119?source=rss-a565d616dfb4------2"><img src="https://cdn-images-1.medium.com/max/2126/1*UcgTs_ONYJ7mjGOQ3wcu6g.png" width="2126"></a></p><p class="medium-feed-snippet">If you&#x2019;re someone who has been experimenting with vibe coding or you&#x2019;re just getting started, this guide will walk you through everything&#x2026;</p><p class="medium-feed-link"><a href="https://levelup.gitconnected.com/inside-the-agentic-code-editors-a-deep-dive-a4abfee40119?source=rss-a565d616dfb4------2">Continue reading on Level Up Coding »</a></p></div>]]></description>
            <link>https://levelup.gitconnected.com/inside-the-agentic-code-editors-a-deep-dive-a4abfee40119?source=rss-a565d616dfb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4abfee40119</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[cursor]]></category>
            <category><![CDATA[mcps]]></category>
            <category><![CDATA[google-antigravity]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Mahesh Jamdade]]></dc:creator>
            <pubDate>Fri, 03 Apr 2026 21:12:30 GMT</pubDate>
            <atom:updated>2026-05-27T18:42:33.971Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Shorebird: Deliver Real-Time Updates to Your Flutter app]]></title>
            <link>https://medium.com/flutter-community/shorebird-deliver-real-time-updates-to-your-flutter-app-9be2adb4215a?source=rss-a565d616dfb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/9be2adb4215a</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[shorebirdflutter]]></category>
            <dc:creator><![CDATA[Mahesh Jamdade]]></dc:creator>
            <pubDate>Sun, 06 Jul 2025 01:29:47 GMT</pubDate>
            <atom:updated>2025-08-26T15:28:22.407Z</atom:updated>
            <content:encoded><![CDATA[<p>You have a wild idea for your next mobile app, You’re all too excited and hyped up for this next big release. After weeks of development and testing you decide to release the app and hit <strong>Publish</strong>. The Playstore and App store folks at work review and evaluate your app with all their policies in place measure your app icon size with all scales and rulers and decide to approve your app. You are happy the app hit the stores and your app starts getting traction. <br>Users downloading your app, Everything looks great… except <strong>one thing</strong>.<br>One of Your novice developer forgot to handle a null check and one of the functionality broke, And Users are seeing blank screens in production no helpful message/error to deal with this issue. The fix is just a couple of lines of code, But it will take a few days for the app to get approved to stores. You have to notify users to update the app, few might many won’t. Even worse Its a weekend the app store reviewers work with limited capacity, meaning long waiting times for a fix that should only take a few minutes. Your business’s stuck and yours users get a bad experience with your product. And You have no choice but wait for the app to get approved.</p><p><strong>Sounds familiar?</strong></p><p>Hi, I am Mahesh a Software Engineer with a passion for delivering exceptional mobile experiences. In this blog post, I’ll share how I use Shorebird and deliver updates to flutter app on the fly cutting down app update delivery time and reducing turn around time to handle production issues.</p><p>By the end of this blog post I will share how to deliver app updates on the fly with shorebird.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zH7MkIsQyBt0oHBCwjdxFw.png" /><figcaption>Screenshot of the epoch app downloading the patch</figcaption></figure><h4>Back Story</h4><p>If you already know what Shorebird is and would like to know how to integrate Shorebird into your existing app headover to <strong>Setting up Shorebird.</strong></p><p>And now back to the story, The need for Code push/hot update or Over the air updates started with this issue thread by <a href="https://github.com/eseidel">Eric Seidel</a>, The Founder of <a href="https://flutter.dev/">Flutter</a> &amp; former Director of Engineering for Flutter/Dart at Google. The twist is He is the same person who opened that issue and came up with a solution <a href="https://shorebird.dev/">Shorebird.dev</a> to help the flutter ecosystem deliver realtime updates to their Flutter apps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3hMykDgmW8I1Ty1H1rFFqg.png" /></figure><p>This issue is one of the top most feature request in the flutter ecosystem till date and is open since 2018. There’s a great discussion on that thread on this topic, where people have shared their insights and solutions surrounding this topic I’ll leave the link here <a href="https://github.com/flutter/flutter/issues/14330"><strong>Code Push / Hot Update / out of band updates · Issue #14330 · flutter/flutter</strong></a> for you to explore.</p><h3>Setting up Shorebird</h3><h4>Installing Shorebird</h4><p>Setting up shorebird is extremely easy and should only take few minutes<br>1. Signup by visiting the <a href="https://console.shorebird.dev/">shorebird console</a> <br>2. Download and install the Shorebird CLI</p><p><strong>MacOS/Linux</strong></p><pre>curl --proto &#39;=https&#39; --tlsv1.2 https://raw.githubusercontent.com/shorebirdtech/install/main/install.sh -sSf | bash</pre><p><strong>Windows</strong></p><pre>Set-ExecutionPolicy RemoteSigned -scope CurrentUser # Needed to execute remote scripts<br>iwr -UseBasicParsing &#39;https://raw.githubusercontent.com/shorebirdtech/install/main/install.ps1&#39;|iex</pre><p>Once shorebird cli is installed, run shorebird doctor to verify the installation is complete.</p><pre>maheshjamdade@Maheshs-MacBook-Pro epoch % shorebird doctor<br>Shorebird 1.6.44 • git@github.com:shorebirdtech/shorebird.git<br>Flutter 3.32.3 • revision 7ac05a80729f189ff1bfd971a512b259638f7f8a<br>Engine • revision b5245dd80cae75a83b4d464fde2cdf941fc3e1d2<br><br>URL Reachability<br>✓ https://api.shorebird.dev OK (0.3s)<br>✓ https://console.shorebird.dev OK (0.3s)<br>✓ https://oauth2.googleapis.com OK (0.2s)<br>✓ https://storage.googleapis.com OK (0.2s)<br>✓ https://cdn.shorebird.cloud OK (0.3s)<br><br>✓ Shorebird is up-to-date (0.7s)<br>✓ AndroidManifest.xml files contain INTERNET permission (24ms)<br>✗ shorebird.yaml found in pubspec.yaml assets (8ms)<br>  [✗] No shorebird.yaml found in pubspec.yaml assets<br>✓ Lock files are tracked in source control (59ms)<br>1 issue detected.<br>1 issue can be fixed automatically with shorebird doctor --fix.<br>maheshjamdade@Maheshs-MacBook-Pro epoch %</pre><p>3. Login to the account from the shorebird cli by running</p><pre>shorebird login</pre><p>Once you are logged in you are ready to integrate shorebird into your existing flutter project.</p><h4>Integrating Shorebird into your flutter app</h4><p>Initialize Shorebird inside your existing flutter project</p><blockquote>Note: If you are starting a new flutter project shorebird now supports the create command, similar to flutter create shorebird create my_flutter_project and thats the only command you will need to create and setup a flutter project with shorebird initialized and you can skip all the instructions in this section.</blockquote><pre>cd my_flutter_project<br>shorebird init</pre><p>This initialization will ask you the app name to identify your app in list of shorebird projects for your account. This will also create a shorebird.yaml file in the root of your project. This file contains a unique Shorebird app_idand any shorebird related configuration for your app (if needed) will be done here. More on that later.</p><p>From the <a href="https://docs.shorebird.dev/getting-started/">Shorebird docs</a></p><blockquote>Your app_id is not a secret and can be checked into source control and freely shared.</blockquote><p>And that is all you need to setup shorebird. <strong>Quick and easy!</strong></p><h3>How shorebird works?</h3><p>Hereafter when you are ready to publish your app to stores, You need to use the shorebird cli to create a release or publish the patch. Before we go any further it is important to understand the terms <strong>release</strong> and <strong>patch </strong>in the context of shorebird to ensure we are aligned</p><p>A<strong> “release”</strong> refers to a new version of the app that is being submitted to the stores generally a apk/appbundle for android or <em>ipa/archive</em> for ios</p><p>A<strong> “patch” </strong>refers to a binary that is being applied to a release. This patch is basically a diff between the release and your current local code.</p><p>The idea of patch and release is fairly simple. I will try to explain this in three simple steps</p><p>1. You create a new “release” using shorebird CLI. This release is tagged with the version and build number you specify in <strong>pubspec.yaml</strong> to uniquely identify the release. This is also shown in the <a href="https://console.shorebird.dev/">shorebird console</a>.</p><p>2. Once the app is approved in stores. You can use the shorebird cli to patch the updates using just a single command `<strong>shorebird patch android</strong>` and `<strong>shorebird patch ios</strong>` commands.</p><p>3. Once the patch is published. This patch gets downloaded in the app in the background when the users reopen the app next time. Users see the updated changes on the next app launch.</p><blockquote>Also note that patch sizes correlate with the total amount of Dart changed from the original released app. Each patch is a diff against the released dart code, not a diff to the previous patch.</blockquote><h4>Creating a release</h4><h4>Android</h4><p>To build for Android runshorebird release android This command generates the appbundle.</p><blockquote>Running <em>shorebird release android --artifact=apk</em>will produce <em>both</em> .apk and .aab files. You can distribute either or both as needed.</blockquote><h4>IOS</h4><p>To build for IOS runshorebird release ios This command generates the ipa file.</p><p>Shorebird by default uses the latest stable version of the flutter sdk. If you need to create a release with a different version of Flutter, you should use --flutter-version option with the shorebird release command.<br>e.g</p><pre>shorebird release android --flutter-version=3.22.3 --dart-define=HIDE_MENU=true</pre><blockquote>Note: Shorebird supports all flutter related flags such as <em>--flavour</em>, <em>--dart-define etc</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yQUnpQLmfPhTDLQ_iySwgg.png" /><figcaption>Shorebird console showing list of releases</figcaption></figure><h4>Creating a Patch</h4><p>Patches are published corresponding to a particular release and are generally in few hundred kbs. At any given time only one patch is active corresponding to a particular release.</p><h4>Android</h4><pre>shorebird patch android</pre><h4>IOS</h4><pre>shorebird patch ios</pre><p>By default a patch is applied to the latest release, If you would like to submit a patch to a different release use the — <strong>release-version </strong>flag</p><pre>shorebird patch android --release-version 0.1.0+1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uPLneYUZLrTcxYMhYWY6Aw.png" /></figure><p>few things to note here before submitting a patch</p><ul><li><em>Each Patch is published to a particular release, You can submit any number of patches to a release.</em></li><li><em>Publishing a patch deactivates the previous obsolete patch.</em></li><li><em>The latest patch contains all the dart changes made since the last release was made.</em></li><li><em>You should not change the version code or version name in the pubspec.yaml when publishing a patch.</em></li><li><em>You should not patch if you update any native code, assets, or any other files that are not part of the dart code.</em></li><li><em>You should only patch when there is any change in the dart code including pure dart packages.</em></li><li><em>A good rule of thumb is if you have published a patch its good to submit a new release too, this ensures your old and new users get the latest app.</em></li></ul><p>But you don’t have to keep track of what has changed and whether its safe to publish a patch. The Shorebird cli is smart enough to give you a headsup about the files that won’t be included in the patch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vBt_mxKbiBzFxHtoQVHFFQ.png" /></figure><h4>Rollback and Rollforward</h4><p>No matter how many processes and best practices you add to your release cycle, mistakes are inevitable and you may find your self in a situation where something broke in the production release and this is why we have a patch, <strong>but what if you publish a buggy patch?</strong></p><p>Heres a small instance, despite the above warnings that the assets won’t be included in the patch, I went rogue and published the patch to one of my app. Result? A blank screen because of missing assets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*3RXvTAAC7iJgCbHNvslMmw.gif" /><figcaption>Demo showcasing a buggy patch being rolled back with a click</figcaption></figure><p>But shorebird has this amazing feature of rollback. You go to the shorebird console and rollback the patch and boom your users will come back to the previous state of the app without any additional hassle to update/redownload the app. And if you change your mind you also have an option to rollforward to reactivate a patch. All of this with a single click.</p><p>Consider the above example of one of my app <a href="https://play.google.com/store/apps/details?id=com.wml.epoch">epoch</a>.</p><ol><li>The App in store has a version 0.1.4 build 9</li><li>You make a change to the dart code and create a patch #1</li><li>Then you create a patch #2, this means patch #1 is no longer active.</li></ol><p>- Users who download release 0.1.4 will receive patch #2 on the next app launch.</p><p>- Users who already have patch #1 (existing users) or downloaded the app from store (new users) will receive patch #2</p><p>- Patch #2 contains all the changes you made since the 0.1.4+9 was released. “<em>Again a Patch is just a diff between your current local code and the release”</em></p><p>4. Patches will get deleted if users clear the app data. And redownloaded on the next app launch if they are using the same release for which the patch was created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qx6lAALJbtlKbyAN9ybFXQ.png" /><figcaption>Shorebird console showing list of patch corresponding to a release</figcaption></figure><h4>Manually download the patch</h4><p>As of now whenever a new patch is published, shorebird silently downloads it in the background on app launch. If you would like to give users the control and manually download a patch. You will need to use a package from shorebird called <a href="https://pub.dev/packages/shorebird_code_push">shorebird_codepush</a>. This is just a programmatic way of notifying users of a new patch and helping you build amazing patch delivery experience while giving your users a greater sense of control.</p><p>Heres a short demo of how a patch update can be manually downloaded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*JUlzvhDGfaeeC50DypNBqg.gif" /></figure><p>And the bare bone starter code to help you implement this feature.</p><blockquote>Note that Shorebird_codepush does not currently notify when a patch download is complete. This code sample runs a safe progress of 15 seconds assuming the patch will be downloaded within this time frame.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3cb0c543aee8a97d37c39d9bdff24105/href">https://medium.com/media/3cb0c543aee8a97d37c39d9bdff24105/href</a></iframe><p>And that is all from this blog post, I hope this guide will help you deliver bold releases swiftly and confidently on the fly with <strong>Shorebird</strong>.</p><p>Heres a fun idea to make this even more better</p><p>Shorebird also integrates well with <a href="https://docs.shorebird.dev/code-push/ci/github/">github actions</a>. That means you could configure it in a way that would allow sending firebase notifications to your app when a patch is published with a single commit. I will leave that challenge for you to explore.</p><p>Until next time 👋🏻</p><blockquote>If this post helped you with some new info, Don’t forget to give claps and do you know you can clap multiple times to appreciate the work?</blockquote><blockquote>Don’t forget to follow so that you get notified on my new blog posts.</blockquote><p>Thanks for Reading and Happy Fluttering 💙</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9be2adb4215a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutter-community/shorebird-deliver-real-time-updates-to-your-flutter-app-9be2adb4215a">Shorebird: Deliver Real-Time Updates to Your Flutter app</a> was originally published in <a href="https://medium.com/flutter-community">Flutter Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rendering Long lists in React: A Pragmatic Guide]]></title>
            <link>https://javascript.plainenglish.io/rendering-long-lists-in-react-a-pragmatic-guide-eef13d11d883?source=rss-a565d616dfb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/eef13d11d883</guid>
            <category><![CDATA[lazy-loading]]></category>
            <category><![CDATA[lists]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[grid]]></category>
            <dc:creator><![CDATA[Mahesh Jamdade]]></dc:creator>
            <pubDate>Fri, 03 Jan 2025 19:13:42 GMT</pubDate>
            <atom:updated>2025-01-06T06:33:43.233Z</atom:updated>
            <content:encoded><![CDATA[<p>A pragmatic guide to rendering lazy list components using IntersectionObserver.</p><p>Lists are a common UI components for displaying content that exceeds the screen size. Many applications feature scenarios where long lists need to be rendered, such as product catalogs, social media feeds, video libraries, Image galleries and so on. Rendering lists is Challenging especially when the client needs to render a large amount of scrollable content, In such cases we generally implement a concept of <strong>Pagination </strong>on the server side.If you are familiar with Pagination and if you would like to jump right into the React implementation of lazy loading, then Switch to the <strong>The Implementation Section.</strong></p><h3>What is Pagination?</h3><p><strong>Pagination</strong> involves designing the system so that each server request fetches a limited number of items, typically by specifying parameters such as <strong>page number</strong> and <strong>number of objects</strong> to retrieve in that request. For a seamless user experience, the frontend must implement a similar strategy to process and display this paginated data efficiently.</p><h4>Pagination from a UX Perspective</h4><p>From a UX perspective, there are two primary ways to handle paginated data retrieval:</p><ol><li><strong>Manual Pagination</strong>: The user explicitly requests data for a specific page, usually by clicking on a page number or a &quot;Next&quot; button.</li><li><strong>Dynamic Pagination</strong>: Data is fetched automatically on the fly as the user interacts with the interface, without any explicit action from the user.</li></ol><p>The second approach often provides a superior user experience since the content is seamlessly loaded, enhancing the overall flow of interaction.</p><p>We subconsciously use pagination in our day to day life, We may not know it, take google search for example Which is an example of <strong>Manual Pagination</strong>, At the end of each search results you see this page numbers UI, where clicking a particular page fetches a set of results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dLgAmfvfNRriXSGY7IukaA.png" /></figure><p>On the other hand, platforms like social media feeds implement <strong>Dynamic pagination</strong>. As you scroll through your feed, new content loads automatically, allowing for endless scrolling. Dynamic pagination feels more natural and intuitive, because users don’t have to interrupt their flow to click buttons or select pages. I’m sure there must be some engineering challenges that might explain why Google Search, don’t implement dynamic pagination. The sheer scale and complexity of fetching search results from massive data stores with blazing fast response and accuracy likely poses significant technical hurdle.</p><h4>From UX to Engineering: Why Optimization Matters</h4><p>This was about Pagination in terms of UX, Lets take a look at the Engineering Side specifically in React. You might have heard terms analogous to pagination such as <strong>lazy-loading</strong>, <strong>infinite scrolling</strong>, <strong>Virtualized or Non-Virtualized lists</strong>. They all relate to pagination with slight nuances of how list items are rendered and destroyed. In this blog post, I will walk you through practical techniques for rendering long lists in React, addressing both performance concerns and the User experience.</p><h4>The Optimization reward</h4><p>It is Often tempting to naively just iterate and render a list. While this may work for a small list, But when it comes to rendering the app in a Constrained environment such as on mobile devices, where memory and network requests are crucial, Optimization becomes inevitable.</p><p>To give you a brief idea why optimization is vital. Imagine a list containing 100 image thumbnails, each approximately<strong> a </strong>Megabyte<strong> </strong>in size. If you were to fetch and load all 100 items in a single request, it would cost the user a staggering <strong>100 MB of data</strong> — and most of that content might never even be viewed if the user doesn’t scroll to the end of the list.<br>On the other hand, lets say you implement a infinite scrolling approach, where more data is fetched as the user scrolls. Lets say you fetch 15 items on a single request. So technically this approach would cost 1/6 th less of data than the previous approach. Thats a massive Optimization when you are dealing with Large Data. You can further optimize this by lazy loading the images by simply passing a lazy attribute to image tag.</p><pre>&lt;img src=&quot;image.png&quot; loading=&quot;lazy&quot; ... /&gt;</pre><p>Images that are out of the viewport (visible area) won’t be downloaded. until they appear on screen. More on that further.</p><h4>Key Design Principle</h4><p>From my point of View, A good rule of thumb when rendering lists is to “<em>Always design as if you’ll be rendering a million items, even if your current dataset contains fewer than 100</em>.” Adopting this mindset ensures that your application remains performant and scalable as your data grows. Here’s a Visual demonstration of lazy loading created using <a href="https://jitter.video/">Jitter</a>. The content is loaded dynamically on the fly as they appear in Viewport.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*VVr1EehrYgAJItrxrnl-6Q.gif" /><figcaption>Lazy loading demonstrating the content is rendered as it enters the viewport</figcaption></figure><h3>The Implementation</h3><p>I believe that was enough to set the background. By the end of this blog post we will implement this <a href="https://unsplash-lib.vercel.app/">Gallery app</a> similar to Unsplash. This app dynamically fetches data from the <a href="https://unsplash.com/documentation#pagination-headers">unsplash api</a> as you scroll using pagination and renders them in a <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_grid_layout/Masonry_layout">Masonry Layout</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qFSUbezpYNKdAKCbo4wZxA.png" /><figcaption>The image shows the snapshot of the final app</figcaption></figure><h4>Setting up a new project</h4><p>Let’s start by creating a new React application. We’ll use the following tools:</p><ul><li><a href="https://ui.shadcn.com/">ShadCN</a> a UI component library</li><li><a href="https://tailwindcss.com/">Tailwind CSS</a> for styling, and</li><li><a href="https://redux.js.org/">Redux</a> for state management.</li></ul><p>If you would prefer you can use this <a href="https://github.com/maheshj01/react-apps/blob/master/create-react-app.sh">shell script</a> to create a new react app and automate the setup with a single command (Instructions in readme.md).</p><p>Once you run the sample app you should see a Counter App (Inspired from flutter)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4qfPs4ofhhtBGAy6oSnKpQ.png" /></figure><p>Now Go to <a href="https://unsplash.com/developers">Unsplash Developers</a> and grab a unsplash api key inorder to fetch the data using the Api. We will store these keys in the <strong>dot env</strong> file located in the root of this project.</p><pre>REACT_APP_APPLICATION_ID=<br>REACT_APP_ACCESS_KEY=<br>REACT_APP_SECRET_KEY=<br>REACT_APP_UNSPLASH_BASE_URL=https://api.unsplash.com/</pre><h4>Creating the ImageModel Class</h4><p>Then we will need a <strong>ImageModel</strong> class inorder to conform to the Json Object received from the API along with the nested URLs class</p><pre>// src/models/ImageModel.ts<br>class ImageModel {<br>    id: string;<br>    urls: URLS;<br>    description: string;<br>    alt_description: string;<br>    likes: number;<br>    width: number;<br>    height: number;<br><br>    constructor(id: string, urls: URLS, description: string, alt_description: string,<br>        width: number, height: number,<br>        likes: number) {<br>        this.id = id;<br>        this.width = width;<br>        this.height = height;<br>        this.urls = urls;<br>        this.description = description;<br>        this.alt_description = alt_description;<br>        this.likes = likes;<br>    }<br>}<br><br>class URLS {<br>    raw: string;<br>    full: string;<br>    regular: string;<br>    small: string;<br>    thumb: string;<br>    small_s3: string;<br><br>    constructor(raw: string, full: string, regular: string, small: string, thumb: string, small_s3: string) {<br>        this.raw = raw;<br>        this.full = full;<br>        this.regular = regular;<br>        this.small = small;<br>        this.thumb = thumb;<br>        this.small_s3 = small_s3;<br>    }<br>}<br><br>export default ImageModel;</pre><h3>Setting Up Redux</h3><p>Now, let’s configure Redux to manage the Unsplash data. If you are unfamiliar with Redux, I would highly recommend the <a href="https://redux.js.org/tutorials/quick-start">official quick start guide</a> which gives a very good overview for beginners.</p><h4>1. Install redux dependencies</h4><p>Install if not already installed using script by running</p><pre>npm install @reduxjs/toolkit redux</pre><h4>2. Configure the Redux Store</h4><pre>// src/store.ts<br>import { configureStore } from &quot;@reduxjs/toolkit&quot;;<br>import imageSlice from &quot;./redux/images/imageSlice&quot;;<br><br>const store = configureStore({<br>  reducer: imageSlice,<br>});<br><br>export type RootState = ReturnType&lt;typeof store.getState&gt;;<br>export default store;<br><br></pre><h4>Step 3: Create the Images Slice</h4><p>Define a slice to handle fetching and storing images.</p><pre><br>import ImageModel from &#39;@/src/models/ImageModel&#39;;<br>import { createSlice, PayloadAction } from &#39;@reduxjs/toolkit&#39;;<br><br><br>const initialState: { images: ImageModel[], loading: boolean, error: any, page: number, endOfList: boolean } = {<br>    images: [],<br>    loading: false,<br>    error: null,<br>    page: 1,<br>    endOfList: false<br>}<br><br>const imageSlice = createSlice({<br>    name: &#39;images&#39;,<br>    initialState,<br>    reducers: {<br>        setEndOfList: (state, action: PayloadAction&lt;boolean&gt;) =&gt; {<br>            state.endOfList = action.payload;<br>        },<br>        addImage: (state, action: PayloadAction&lt;ImageModel&gt;) =&gt; {<br>            const image = action.payload;<br>            state.images.push(image);<br>        },<br>        addImages: (state, action: PayloadAction&lt;ImageModel[]&gt;) =&gt; {<br>            const images = action.payload;<br>            state.images.push(...images);<br>        },<br>        setImages: (state, action: PayloadAction&lt;ImageModel[]&gt;) =&gt; {<br>            state.images = action.payload;<br>        },<br>        setLoading: (state, action: PayloadAction&lt;boolean&gt;) =&gt; {<br>            state.loading = action.payload;<br>        },<br>        setPage: (state, action: PayloadAction&lt;number&gt;) =&gt; {<br>            state.page = action.payload;<br>        },<br>        setError: (state, action: PayloadAction&lt;string&gt;) =&gt; {<br>            state.error = action.payload;<br>        }<br>    }<br>});<br><br><br>export const { addImage, setImages, setLoading, setError, addImages, setEndOfList } = imageSlice.actions;<br><br>export default imageSlice.reducer;</pre><h4>Step 4: Provide the Store</h4><p>Wrap your application with the Redux Provider in the index.tsx file.</p><pre>import React from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom/client&#39;;<br>import &#39;./index.css&#39;;<br>import App from &#39;./App&#39;;<br>import { Provider } from &#39;react-redux&#39;;<br>import store from &#39;./store&#39;;<br><br>const root = ReactDOM.createRoot(<br>  document.getElementById(&#39;root&#39;) as HTMLElement<br>);<br>root.render(<br>  &lt;React.StrictMode&gt;<br>    &lt;Provider store={store}&gt;<br>      &lt;App /&gt;<br>    &lt;/Provider&gt;<br>  &lt;/React.StrictMode&gt;<br>);</pre><p>And now we will make an API Request to Unsplash by specifying <strong>page_number</strong> and <strong>per_page</strong> parameter to fetch the images for page 1 and you should see a Grid Loading.</p><pre>import React, { useRef } from &quot;react&quot;;<br>import SearchBar from &quot;./components/SearchBar&quot;;<br>import ImagesGrid from &quot;./components/Grid&quot;;<br>import { useDispatch, useSelector } from &quot;react-redux&quot;;<br>import { setImages, setLoading } from &quot;./redux/images/imageSlice&quot;;<br>import useDebounce from &quot;./hooks/useDebounce&quot;;<br>import { RootState } from &quot;./store&quot;;<br><br>const App: React.FC = () =&gt; {<br>  const [value, setValue] = React.useState&lt;string&gt;(&quot;&quot;);<br>  const clientId = process.env.REACT_APP_ACCESS_KEY;<br>  const path = &#39;/photos&#39;<br>  const per_page = 20;<br>  const page_number = useRef&lt;number&gt;(1);<br>  const dispatch = useDispatch();<br>  const debouncedValue = useDebounce(value, 15000);<br>  const loading = useSelector((state: RootState) =&gt; state.loading);<br><br>  const fetchImages = async (query: string, append?: boolean) =&gt; {<br>    try {<br>      dispatch(setLoading(true));<br>      const response = await fetch(`${process.env.REACT_APP_UNSPLASH_BASE_URL}${path}?client_id=${clientId}&amp;query=${query}&amp;per_page=${per_page}&amp;page=${page_number.current}`);<br>      const data = await response.json();<br>      if (!data) {<br>        dispatch(setLoading(false));<br>        return;<br>      }<br>      dispatch(setImages(data));<br>      dispatch(setLoading(false));<br>    } catch (error) {<br>      dispatch(setLoading(false));<br>      console.error(error);<br>    };<br>  };<br><br>  const LoadingComponent = () =&gt; {<br>    return (&lt;div className=&quot;flex justify-center items-center h-96&quot;&gt;<br>      &lt;div className=&quot;loader&quot;&gt;Loading...&lt;/div&gt;<br>    &lt;/div&gt;)<br>  }<br><br>  React.useEffect(() =&gt; {<br>    fetchImages(debouncedValue, false);<br>  }, [debouncedValue]);<br><br>  return (<br>    &lt;&gt;<br>      &lt;div className=&quot;relative&quot;&gt;<br>        &lt;SearchBar<br>          onChange={(query) =&gt; setValue(query)}<br>          placeholder=&quot;Search for Images&quot;<br>          value={value}<br>          onSubmit={() =&gt; fetchImages(debouncedValue, false)}<br>        /&gt;<br>        &lt;div className=&quot;h-4&quot; /&gt;<br>        &lt;ImagesGrid className=&quot;px-2&quot; /&gt;<br>        {loading &amp;&amp; (<br>          &lt;LoadingComponent /&gt;<br>        )}<br>      &lt;/div&gt;<br>    &lt;/&gt;<br>  );<br>}<br><br>export default App;<br><br><br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-pKyA60foLPDvO7-nhZlaw.png" /></figure><p>Nothing fancy yet, Just a normal API request to fetch 20 elements for page 1 and render them in a simple Grid.</p><pre>import React, { memo } from &#39;react&#39;;<br>import { useSelector } from &#39;react-redux&#39;;<br>import ImageModel from &#39;../models/ImageModel&#39;;<br>import { RootState } from &#39;../store&#39;;<br>import GridImage from &#39;./GridImage&#39;;<br><br>interface ImagesGridProps {<br>    className?: string;<br>    imageRef?: (element: HTMLDivElement | null) =&gt; void;<br>}<br><br>const ImagesGrid: React.FC&lt;ImagesGridProps&gt; = memo(({ className, imageRef }) =&gt; {<br>    const images = useSelector((state: RootState) =&gt; state.images as ImageModel[]);<br>    const loading = useSelector((state: RootState) =&gt; state.loading);<br>    if (!images.length) {<br>        return (<br>            &lt;div className=&quot;flex justify-center items-center h-96&quot;&gt;<br>                &lt;p className=&quot;text-gray-500&quot;&gt;No images found&lt;/p&gt;<br>            &lt;/div&gt;<br>        );<br>    }<br><br>    const LoadingComponent = () =&gt; {<br>        return (&lt;div className=&quot;flex justify-center items-center h-96&quot;&gt;<br>            &lt;div className=&quot;loader&quot;&gt;Loading...&lt;/div&gt;<br>        &lt;/div&gt;)<br>    }<br><br>    return (<br>        &lt;div<br>            key={images.length}<br>            className={`grid grid-cols-1 gap-2 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 ${className}`}&gt;<br>            {images.map((image: ImageModel, index: number) =&gt; {<br>                return (<br>                    &lt;GridImage<br>                        key={index}<br>                        image={image}<br>                        className={`bg-white rounded-lg shadow-lg overflow-hidden`}<br>                        ref={images.length === index + 1 ? imageRef : undefined}<br>                    /&gt;<br>                );<br>            })}<br>            {loading &amp;&amp; &lt;LoadingComponent /&gt;}<br>        &lt;/div&gt;<br>    );<br>});<br><br>ImagesGrid.displayName = &#39;ImagesGrid&#39;;<br><br>export default ImagesGrid;</pre><p>Now comes the Secret Sauce, that will help implement Lazy Loading. There are several approaches to rendering lazy lists. You can either use community libraries like <a href="https://github.com/bvaughn/react-window">react-window </a>, <a href="https://github.com/bvaughn/react-virtualized">React Virtualized</a> or implement your own solution. While libraries can save time and effort, I generally prefer custom implementations for greater control and autonomy unless the task becomes overly complex. To implement Lazy lists we will be using, the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API"><strong>IntersectionObserver</strong></a><strong> </strong>Api<strong>.</strong> Before we go ahead and directly use it. It is important to understand What it is and How it works and its use cases.</p><h3>Understanding IntersectionObserver</h3><p>The <strong>IntersectionObserver</strong> is an API provided by browsers to observe if a Certain DOM element is intersecting with the boundaries of the Viewport or the root element. This API allows you to implement use cases such as Ads revenue calculation based on how long the ads was displayed or lazy-loading techniques, enabling you to trigger data fetching or component rendering as elements come into view.</p><p>Here’s a simple explanation taken straight <a href="https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API#intersection_observer_concepts_and_usage">from the docs</a></p><p>The Intersection Observer API allows you to configure a callback that is called when either of these circumstances occur:</p><ul><li>A target element intersects either the device’s viewport or a specified element. That specified element is called the <strong>root element</strong> or <strong>root</strong> for the purposes of the Intersection Observer API.</li><li>The first time the observer is initially asked to watch a target element.</li></ul><h4>How Intersection Observer Works</h4><ol><li>You define a target element to observe.</li><li>The IntersectionObserver monitors that element’s visibility relative to the parent element, if not specified it will be the top level document’s viewport</li><li>When the element intersects (or leaves) the viewport, a callback function is triggered, allowing you to perform actions like loading new content or rendering components dynammically.</li></ol><h4>Api Usage</h4><pre>function handleIntersection(entries: IntersectionObserverEntry[]) {<br>     const entry = entries[0];<br>     ...<br>}<br><br>const options = {<br>  root: document.querySelector(&quot;#parentdiv&quot;),<br>  rootMargin: &quot;0px&quot;,<br>  threshold: 1.0,<br>};<br><br>const observer = new IntersectionObserver(handleIntersection, options);</pre><p>We create an instance of a IntersectionObserver and pass in a callback and an options. The Options take the following arguments</p><h4><a href="https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver#instance_properties">Instance properties</a></h4><ul><li><strong>root:</strong> The <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element">Element</a> or <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document">Document</a> whose bounds are used as the bounding box when testing for intersection. If no root value was passed to the constructor or its value is null, the top-level document&#39;s viewport is used.</li><li><strong>rootMargin:</strong> An offset rectangle applied to the root’s <a href="https://developer.mozilla.org/en-US/docs/Glossary/Bounding_box">bounding box</a> when calculating intersections, effectively shrinking or growing the root for calculation purposes. The value returned by this property may not be the same as the one specified when calling the constructor as it may be changed to match internal requirements. Each offset can be expressed in pixels (px) or as a percentage (%). The default is &quot;0px 0px 0px 0px&quot;.</li><li><strong>thresholds:</strong> A list of thresholds, sorted in increasing numeric order, where each threshold is a ratio of intersection area to bounding box area of an observed target. Notifications for a target are generated when any of the thresholds are crossed for that target. If no value was passed to the constructor, 0 is used.</li></ul><p>The callback function is executed when it detects that a target element’s visibility has crossed one or more thresholds.</p><p>Heres a <a href="https://pastelog.vercel.app/logs/publish/vMPo1upUeG6kqlWc4zBz/">sample demo app</a> created to demonstrate how we can target a 10th list item in a list and observe it coming into and going out of the specified root.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v3q33T76ynO_HHzPYLeXzg.gif" /></figure><h4>The Approach</h4><p>We will use this similar approach in the gallery app to lazy load the data. We will attach a ref to last element in the list, Once the scroll reaches the end of the list we will stop observing the old last element and start observing the new last element.</p><pre>  ...<br><br>  const loading = useSelector((state: RootState) =&gt; state.loading);<br>  const endOfList = useSelector((state: RootState) =&gt; state.endOfList);<br>  const observerRef = React.useRef&lt;IntersectionObserver | null&gt;(null);<br><br>  const fetchImages = async (query: string, append?: boolean) =&gt; {<br>    try {<br>      if (endOfList) return;<br>      dispatch(setLoading(true));<br>      page_number.current += 1;<br>      const response = await fetch(`${process.env.REACT_APP_UNSPLASH_BASE_URL}${path}?client_id=${clientId}&amp;query=${query}&amp;per_page=${per_page}&amp;page=${page_number.current}`);<br>      const data = await response.json();<br>      // stop observing if the api returned an empty response<br>      if (!data) {<br>        observerRef.current?.disconnect();<br>        dispatch(setEndOfList(true));<br>        dispatch(setLoading(false));<br>        return;<br>      }<br>      if (append) {<br>        dispatch(addImages(data));<br>      } else {<br>        dispatch(setImages(data));<br>      }<br>      dispatch(setLoading(false));<br>    } catch (error) {<br>      console.error(error);<br>    };<br>  };<br><br>...<br><br>  const lastImage = useCallback((element: HTMLDivElement | null) =&gt; {<br>    if (!element || loading) return;<br>    if (observerRef.current) {<br>      observerRef.current.disconnect();<br>    }<br>    // check if the last element is intersecting then set new observerRef.current<br>    observerRef.current = new IntersectionObserver((entries) =&gt; {<br>      if (entries[0].isIntersecting) {<br>        fetchImages(debouncedValue, true);<br>      }<br>    }, { threshold: 0.1 });<br>    observerRef.current.observe(element);<br>  }, [loading, debouncedValue]);<br><br> ...<br><br>  return (<br>    &lt;&gt;<br>      &lt;div className=&quot;relative&quot;&gt;<br>       ...<br>        &lt;ImagesGrid imageRef={lastImage} className=&quot;px-2&quot; /&gt;<br>        {loading &amp;&amp; (<br>          &lt;LoadingComponent /&gt;<br>        )}<br>      &lt;/div&gt;<br>    &lt;/&gt;<br>  );<br>}<br><br>export default App;</pre><p>Attach the forwarded ref to last element in the list</p><pre>const ImagesGrid: React.FC&lt;ImagesGridProps&gt; = memo(({ className, imageRef }) =&gt; {<br>    const images = useSelector((state: RootState) =&gt; state.images as ImageModel[]);<br>    const loading = useSelector((state: RootState) =&gt; state.loading);<br><br>    return (<br>      ...<br>      &lt;GridImage<br>        key={index}<br>        image={image}<br>        className={`bg-white rounded-lg shadow-lg overflow-hidden ${spanClass}`}<br>        ref={images.length === index + 1 ? imageRef : undefined}<br>      /&gt;<br>  {loading &amp;&amp; &lt;LoadingComponent /&gt;}<br>)</pre><p>The result is a seamless user experience where new images are loaded as the user scrolls, without overloading the browser or server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Sdy0-S9T5zcYeyEe7Q9cAg.gif" /></figure><h3>Summary</h3><p>Final thoughts using IntersectionObserver allows</p><ul><li><strong>Better User Experience:</strong> Improves perceived performance by rendering only visible items.</li><li><strong>Reduced Network Requests and Memory Consumption:</strong> Loads data on demand, avoiding unnecessary fetches and memory usage.</li></ul><p>That was all from this Long blog post you can find the necessary links below</p><p>source code: <a href="https://github.com/maheshj01/react-apps/">https://github.com/maheshj01/react-apps/</a><br>deployed app: <a href="https://unsplash-lib.vercel.app/">https://unsplash-lib.vercel.app/</a><br>Intersection Observer: <a href="https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver">https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver</a></p><blockquote>If this post helped you with some new info, Don’t forget to give claps and do you know you can clap multiple times to appreciate the work?</blockquote><blockquote>Don’t forget to follow so that you get notified on my new blog posts.</blockquote><p>Until Next time 👋🏻</p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://cofeed.app/"><strong>Check out CoFeed, the smart way to stay up-to-date with the latest in tech</strong></a> <strong>🧪</strong></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eef13d11d883" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/rendering-long-lists-in-react-a-pragmatic-guide-eef13d11d883">Rendering Long lists in React: A Pragmatic Guide</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Add Keyboard Shortcuts to your React App like a Pro]]></title>
            <link>https://javascript.plainenglish.io/add-keyboard-shortcuts-to-your-react-app-like-a-pro-94e712a163c5?source=rss-a565d616dfb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/94e712a163c5</guid>
            <category><![CDATA[product]]></category>
            <category><![CDATA[keyboard-shortcuts]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-app-development]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Mahesh Jamdade]]></dc:creator>
            <pubDate>Tue, 08 Oct 2024 02:45:28 GMT</pubDate>
            <atom:updated>2024-11-10T15:49:11.456Z</atom:updated>
            <content:encoded><![CDATA[<p>Give your users the shortcuts they need to boost their productivity and provide a great User Experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xgVNPVSSJ01Jj3UX.jpg" /><figcaption>Image source <a href="https://hidraupianobenches.com/8-most-popular-piano-songs-to-learn/">hidraupianobenches.com</a></figcaption></figure><p>Just as each piano key corresponds to a unique sound, the keys on a keyboard can be mapped to trigger specific UI components. When developing desktop or web applications, we often need to capture keyboard events to perform certain actions. Keyboard shortcuts provide quick access to features that would otherwise require multiple keystrokes and mouse clicks. I encountered a similar need while building <a href="https://pastelog.vercel.app/">Pastelog</a>, an AI-powered note-taking app.</p><p>In the world of great product experiences, if you are not adding a keyboard shortcut at appropriate places you are hurting the user experience. Wonder how?</p><p>Take Google Search as an example. It has a ‘Google Search’ button, but I bet 90% of people will press ‘Enter’ instead of clicking the button. Why? Because it’s a product standard — it’s ingrained in our subconscious to hit ‘Enter’ to submit input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u9q4PfTQ0bkg5LsOegDMyQ.png" /></figure><p>Similarly, when aiming to build a great user experience, it’s important to follow established standards and implement relevant keyboard shortcuts wherever necessary. For this note-taking app, I developed a custom editor that supports GitHub Flavored Markdown, allowing users to create rich text using keyboard shortcuts. A rich text editor relies on a variety of shortcuts to make writing a smooth and enjoyable experience.</p><p>In this blog post I give a high level implementation of how to:</p><ol><li>Capture keyboard shortcuts on any React component.</li><li>Implement shortcuts in a text input for custom formatting.</li></ol><p>Before we dive in, check out Demo 1 of the Pastelog app, which showcases keyboard shortcuts in action throughout the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cIfzEStdDe1Ek9s60Am7ow.gif" /><figcaption>Demo of Keyboard shortcuts in Action on the Pastelog app</figcaption></figure><p>If you look closely the demo shows 4 shortcuts</p><ol><li><strong>Cmd + S: </strong>Hide/Unhide the Sidebar</li><li><strong>Cmd + P: </strong>Toggle between editor and preview</li><li><strong>Cmd + N: </strong>Switch to new Editor</li><li><strong>Cmd + D: </strong>Switch to Dark mode</li></ol><p>Now, lets take a look at how we can add this feature in our existing app. Pastelog is built using NextJS but the approach and code we will discuss should work just fine in a React/Vite app.</p><p>This is the simple <strong>Logslayout </strong>Component of the app with a sidebar and the main content placed in a row.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b01wpEowm75QgBpSa5MMzQ.png" /></figure><blockquote>Few tailwind CSS classes and some unnecessary methods have been redacted to make the code readable.</blockquote><p>To listen for keyboard events, web browsers provide an API that JavaScript can use to handle the keydown and keyup events. <br>From the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/keydown_event">MDN documentation</a>, the keydown event is triggered for all keys, regardless of whether they produce a character. Both keydown and keyup events includes several properties such as code (ascii) and key (character) that indicates which key is pressed.</p><p>To leverage this API we create a <strong>ShortcutWrapper</strong> component that can be wrapped around Other Components to listen to keyboard events generated from those components. It also exposes a onShortCutClick callback to capture the keypress event.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9dtsMk-uwKG1_oqcimfSow.png" /></figure><p>Here are two important things to know from this component</p><p>1. pressing ‘A’ or ‘a’ (whether uppercase or lowercase) will still work becauseevent.key property is providing the key&#39;s value as a string and its value will be<strong> ‘a’.</strong></p><p>2. When capturing keyboard events, We shoud add <strong>event.preventDefault </strong>only if we want to override the default system behavior, For instance pressing ctrl/cmd + p will trigger printing of the web page, But This shortcut won’t work in our app since we are overriding that behavior using `<strong>event.preventDefault`</strong></p><p>Now we Wrap the ShortcutsWrapper component around the <strong>LogsLayout </strong>inorder to capture any key stroke and handle it in <strong>handleShortCut</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_KUDVHHzXwSw4NcH-bpDuQ.png" /></figure><p>Now, Lets take a look at adding shortcuts to our editor to perfom some custom editing, The Pastelog Editor Supports <a href="https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax">Github flavoured markdown</a> syntax. Since its an editor built to write long Rich notes, It is not uncommon to expect keyboard shortcuts built into the editor. Heres a look at short demo showcasing few among the many shortcuts supported by the Pastelog editor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Au_S9PuZujekkZQAcr6YA.gif" /><figcaption>textinput showcasing formatting text with keyboard shortcut</figcaption></figure><p>A texteditor at its core is a <strong>textArea, </strong>All beautiful editors out there were built after customizing this basic input. Our text editor has a markdown Support embedded any text format written in the editor will be fed to the Markdown Preview and the editor toggles between preview and the textinput using the preview property</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nndte2bJDLpcszLZqoRljg.png" /></figure><p>The core functionality of this editor lies in the <strong>TextCompletionInput</strong> component. It includes various formatting options and keyboard shortcuts. However, here&#39;s a simplified version of the code for the purposes of this blog post. If you would like to go nuts, Heres the <a href="https://github.com/maheshj01/pastelog/blob/main/src/app/(main)/_components/completion.tsx">complete code</a> 😅</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ol7twXM81N2D2VdWO8eWgg.png" /><figcaption>Customized TextInput area</figcaption></figure><p>Unlike ShortCutWrapper we don’t need to have a keydown listener, textinput provides a <strong>onKeyDown</strong> property to listen to key events and do all the magic.</p><p>On a Text selection we plan to apply following formattings in the text editor</p><pre>    text              Shortcut               Markdown Syntax<br><br>- Bold Text            Ctrl + b              **selected text**<br>- Italic               Ctrl + i.             *&lt;selected text&gt;*<br>- Embed text in a Link Ctrl + k              [](selected text)</pre><p>So we take a particular piece of text trigger a shortcut and convert it to Markdown Syntax<br>- e.g Pressing <strong>Ctrl + b</strong> should bold the text by adding <strong>** </strong>around the selected text.</p><p>for a complete list of markdown syntax supported by Pastelog refer the <a href="https://pastelog.vercel.app/logs/publish/shortcuts">keyboard shortcuts guide</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I3jEN8SlDQMj--KLpAocKw.png" /></figure><p>And, This is just a helper function to append the special characters around the selected text denoted by start index and end index and returns the markdown text with the position of the cursor at the end of the text.</p><pre>public applyFormatting(start: number, end: number, syntax: string): { value: string, newCursorPos: number } {<br>    let selectedText = this.value.substring(start, end);<br><br>    const trimmedText = selectedText.trim();<br><br>    if (trimmedText === &#39;&#39;) {<br>        return { value: this.value, newCursorPos: end };<br>    }<br><br>    const trimStart = selectedText.indexOf(trimmedText);<br>    const trimEnd = trimStart + trimmedText.length;<br><br>    const formattedText =<br>        selectedText.substring(0, trimStart) +<br>        `${syntax}${trimmedText}${syntax}` +<br>        selectedText.substring(trimEnd);<br><br>    const newValue =<br>        this.value.substring(0, start) +<br>        formattedText +<br>        this.value.substring(end);<br><br>    const newCursorPos = start + formattedText.length;<br><br>    return { value: newValue, newCursorPos };<br>}</pre><p>For embedding a link We will need another helper function and so on,</p><pre>const applyLinkFormatting = () =&gt; {<br>    const textarea = inputRef.current;<br>    if (!textarea) return;<br><br>    const { value, newCursorPos } = markdownFormatter.current.applyLinkFormatting(<br>        textarea.selectionStart,<br>        textarea.selectionEnd<br>    );<br>    updateValue(value, newCursorPos);<br>};</pre><p>Overall, it’s all about capturing keystrokes and implementing custom logic to handle the formatting. I highly recommend taking a look at the complete code, If you plan to implement something similar. As of this writing, the editor includes the following features:</p><ul><li>Keyboard shortcuts for different markdown syntax</li><li>Tab/Shift+Tab functionality to add or remove tabs across selected lines (including multiple lines).</li><li>Custom undo/redo functionality that tracks the editor’s state with each character change.</li><li>When in a List ordered/unordered Pressing enter Continues the list</li></ul><p>Moving forward, I plan to add more shortcuts, As you’d expect from any standard text editor, Heres a list of <a href="https://github.com/maheshj01/pastelog/issues/35">shortcuts to add</a> on the roadmap.</p><p>And that is all from this blog post, Hope this gave a indication of how these shortcuts are added in a web app.</p><blockquote>If this post helped you with some new info, Don’t forget to give claps and do you know you can clap multiple times to appreciate the work?</blockquote><blockquote>Don’t forget to follow so that you get notified on my new blog posts.</blockquote><p>Until next time 👋🏻 Keep building great User experiences🚀</p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94e712a163c5" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/add-keyboard-shortcuts-to-your-react-app-like-a-pro-94e712a163c5">Add Keyboard Shortcuts to your React App like a Pro</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Google’s Secret Hiring Challenge-II]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://blog.stackademic.com/demystifying-googles-secret-hiring-challenge-ii-4544bdac8ed8?source=rss-a565d616dfb4------2"><img src="https://cdn-images-1.medium.com/max/1024/0*K9wZ_uM8rvHNzgAo.jpeg" width="1024"></a></p><p class="medium-feed-snippet">This blog post is the continuation of my previous blog Demystifying Google&#x2019;s Secret Hiring Challenge-I, where I shared How I got invited&#x2026;</p><p class="medium-feed-link"><a href="https://blog.stackademic.com/demystifying-googles-secret-hiring-challenge-ii-4544bdac8ed8?source=rss-a565d616dfb4------2">Continue reading on Stackademic »</a></p></div>]]></description>
            <link>https://blog.stackademic.com/demystifying-googles-secret-hiring-challenge-ii-4544bdac8ed8?source=rss-a565d616dfb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/4544bdac8ed8</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[challenge]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[foobar]]></category>
            <dc:creator><![CDATA[Mahesh Jamdade]]></dc:creator>
            <pubDate>Thu, 02 Nov 2023 01:26:02 GMT</pubDate>
            <atom:updated>2024-09-10T23:35:52.567Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Demystifying Google’s Secret Hiring Challenge-I]]></title>
            <link>https://itnext.io/demystifying-googles-secret-hiring-challenge-i-1513c30033b4?source=rss-a565d616dfb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/1513c30033b4</guid>
            <category><![CDATA[google]]></category>
            <category><![CDATA[hiring-process]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Mahesh Jamdade]]></dc:creator>
            <pubDate>Fri, 13 Oct 2023 20:59:16 GMT</pubDate>
            <atom:updated>2023-11-02T12:36:16.347Z</atom:updated>
            <content:encoded><![CDATA[<p>This blog post is mainly about my experience with Google’s secret hiring challenge</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-lZ0iCHmGrSRdrd0iKDQKQ.jpeg" /></figure><p>If you have ever applied to tech jobs you must be familiar that the process is fairly common, You visit the company’s website look for a job that best fits your interests and skills, and apply there. If the employer finds your profile is a match they will most likely reach out to you with a coding assessment. This is also true for the tech giant Google. But they also have a “<strong>secret</strong>” way of hiring developers around the world, It is called the <a href="https://foobar.withgoogle.com/#"><strong>Foobar Hiring Challenge</strong></a>. I heard about this challenge for the first time sometime back during my undergrad(at least 3 years ago). But never really researched about it, until I experienced it myself last week. There is no official info from Google regarding this but only from folks who have shared their experiences on the internet.</p><p>So for those who are hearing about this challenge for the first time, this is what I could collect from the internet and based on my experience regarding this challenge as of Oct 2023.</p><blockquote>Google Foobar is a secret hiring process that Google uses to hire developers from around the world. The challenge is designed to evaluate and recruit potential engineers for Google. This challenge is invite only and unlocked to folks who have been searching some specific coding related terms on Google for quite a while.</blockquote><p>This happened last week, on a bright Sunday morning when I was studying a topic for school and I did a regular Google search. The term was “<strong>Genetic Algorithm</strong>” and as the search executed, My Google Search results Page collapsed flat backward, and I was taken to this black screen with a shell-like interface and I couldn’t believe it for a minute.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rbDuy4_BmUT4VbKGDRNP5Q.png" /></figure><p>The web URL looked genuine and to confirm again I did another Google search just to see what exactly is the foobar challenge and the search results convinced me that I actually landed on the <strong>Foobar challenge</strong>. I didn’t waste a lot of time and I signed in with Google to ensure the invite doesn’t get lost.</p><p>Now it was about giving my best, I had tried Google’s coding challenges like <a href="https://codingcompetitionsonair.withgoogle.com/#code-jam">Codejam</a> before, sometime during my undergrad, and I gave up because they were too tough for me to solve, and I was convinced I was not there yet to even compete. But now since the challenge showed up itself, I tried to give it a shot and I was prepared to give up again because I still have that notion that the Google coding challenges are extremely difficult to solve.</p><p>So now I have this unix-like shell on my screen, so seeing this black screen I know what needs to be done, ask for “<strong>help</strong>”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TToqqHHwfwOdIJfrrrclbQ.png" /></figure><p>and with this information, we exactly know what needs to be done to request a new problem using the command <strong>request, </strong>running this command a new directory was mounted at the root changing into that directory I was presented with the first coding challenge. As I said even at this point, I was prepared that this question would be extremely difficult and I would give up again. But to my surprise, the question was pretty easy, and I think I was able to solve it in less than half an hour.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mVwirlTLKau8ib5JkwRS0g.png" /></figure><p>Solving the first challenge would present you with a bunny jumping across the screen.</p><p><strong>So to summarize this challenge</strong></p><ul><li>Google Foobar is an <strong>invite-only</strong> challenge.</li><li>The challenge consists of five levels of algorithms <strong>9 problems</strong> in total that can be completed in either Python or Java. <strong>Level 1 &amp; 5</strong> has <strong>one</strong> problem each, <strong>Level 2 &amp; 4</strong> has <strong>two</strong> problems each, and <strong>Level 3</strong> has <strong>three</strong> problems</li><li>The first two levels are relatively easy, but the difficulty increases as the levels progress.</li><li>Each challenge needs to be completed within 168 hours (7 days)</li><li>After completing level 3, players are asked if they’re interested in hearing from a Google recruiter. Those who clear the challenge are offered direct interviews for positions that match their qualifications.</li></ul><p>After hearing some experiences from folks on the internet it seems completing these challenges does not guarantee an interview with Google, But regardless the challenges are definitely fun to solve per se.<br>So, next time if your Google search results page ever collapses and you see this black screen you exactly know what you have fallen into and what exactly you need to do.</p><p>I am currently in the midst of these challenges, If you would like to read more about what were the exact problems? And How I solved them stay tuned for my upcoming blog post.</p><blockquote>If this post helped you with some new info, Don’t forget to give claps and do you know you can clap multiple times to appreciate the effort?</blockquote><blockquote>Don’t forget to follow so that you get notified on my new blog posts.</blockquote><p>Edit: I have published a <a href="https://itnext.io/demystifying-googles-secret-hiring-challenge-ii-4544bdac8ed8">continuation of this blog post</a> where I shared the challenges from foobar and the approach I used to solve them.</p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1513c30033b4" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/demystifying-googles-secret-hiring-challenge-i-1513c30033b4">Demystifying Google’s Secret Hiring Challenge-I</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Genetic Algorithm and The Travelling Salesman Problem(TSP)]]></title>
            <link>https://itnext.io/the-genetic-algorithm-and-the-travelling-salesman-problem-tsp-31dfa57f3b62?source=rss-a565d616dfb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/31dfa57f3b62</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[genetic-algorithm]]></category>
            <dc:creator><![CDATA[Mahesh Jamdade]]></dc:creator>
            <pubDate>Fri, 06 Oct 2023 23:12:27 GMT</pubDate>
            <atom:updated>2024-03-15T23:28:23.892Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TJrwjDHxmqncaeIkCOTIBA.jpeg" /></figure><p>So far all of my blog posts have revolved around widgets, flutter, Open Source, and software development. But this time I am taking a different direction, it&#39;s about an algorithm I studied as part of my master&#39;s course work Artificial Intelligence. I have had the privilege to study many different algorithms throughout my academics and work and have used them day in and day out, But I find this algorithm fascinating, and interesting for its nature, It is inspired by the phenomenon of Natural selection. The same phenomenon on which evolution is based. Brace yourself because this will be a lengthy blog post and probably difficult to understand, But I will try my best to keep things simple.</p><h4>Introduction</h4><p><strong>Genetic Algorithm</strong> is a problem-solving strategy inspired by the way living things evolve and adapt over time. It’s a computer-based method used to find good solutions to <strong>HARD</strong> problems, especially when finding the very best answer is really hard. Going forward I will clarify what exactly I meant by <strong>HARD problems</strong>.</p><p>We have all heard the popular phrase “<em>Survival of the Fittest “</em></p><blockquote>species of animals and plants that are best adapted to their environment survive and reproduce, while those that are less well adapted die out.</blockquote><p>We understand this fittest theory in terms of evolution and you will see this behavior being perfectly applied in the genetic algorithm for the Travelling Salesman problem. <em>The concept will evolve as you read along and everything will start to make sense, This is not Philosophy this is Evolution.</em></p><h3>The Problem</h3><blockquote>So what exactly is <a href="https://en.wikipedia.org/wiki/Travelling_salesman_problem"><strong>The Traveling Salesman Problem</strong></a><strong> (TSP)</strong></blockquote><p>The problem states</p><blockquote>Given a list of cities and the distances between each pair of cities, what is the shortest possible route that visits each city exactly once and returns to the origin city?</blockquote><p>This problem is not as straightforward as it sounds, This is an <strong>NP-hard </strong>problem meaning there is no standard polynomial time algorithm that would solve every instance of this problem. In simple terms, as the number of cities increases it gets exponentially difficult and time-consuming to find a solution to this problem. Hence the Genetic Algorithm (A solution to this Optimization Problem).</p><h3>The Algorithm</h3><p>The above problem described can be solved using the genetic algorithm, This algorithm guarantees a solution that is close to the optimal but not necessarily optimal. It uses a stochastic approach (meaning the next state is not determined since it uses randomization) to reach the near-optimal solution. I found a simple yet easy-to-understand analogy to understand this algorithm. I confess this analogy is not mine but it helps explain genetic algorithms in simple words.</p><p>“<strong>Finding the Best Recipe</strong> <em>Imagine you’re trying to find the best recipe to make a delicious sandwich. You have lots of ingredients (like bread, cheese, meat, veggies), but you’re not sure which combination is the tastiest.</em> <br>Here’s how a genetic algorithm could help:</p><ol><li><strong>Create Recipes</strong>: First, you make a bunch of different sandwich recipes by randomly mixing ingredients. These recipes are like solutions to your sandwich problem.</li><li><strong>Taste Test</strong>: You taste each sandwich and give them a score based on how yummy they are. Higher scores mean better-tasting sandwiches.</li><li><strong>Mix Recipes</strong>: Now, you take the recipes (sandwiches) with the best scores and mix them together. You combine the recipes to create new ones.</li><li><strong>Add a Twist</strong>: Sometimes, you make tiny changes in the new recipes to keep things interesting. This is like adding a pinch of creativity or randomness.</li><li><strong>Repeat</strong>: You repeat these steps many times, keeping the best recipes and making new ones. Over time, the sandwiches get tastier and tastier because you’re always choosing the best ones and mixing them.</li><li><strong>Yummiest Sandwich</strong>: After doing this for a while, you end up with a super yummy sandwich recipe because the genetic algorithm keeps improving the recipes based on what tastes best.”</li></ol><p>Similarly, we apply the GA to the Travelling Salesman problem. Let&#39;s understand the algorithm steps before we dive into solving the problem. Before that, it is important to clarify some of the terms that might be confusing.</p><p><strong>‘Population</strong>’ denotes the collection of paths (with a size of <strong>populationSize</strong>), and terms such as ‘<strong>parent</strong>’ and ‘<strong>offspring</strong>’ refer to individual elements within this population, specifically referring to a path of cities, And <strong>genes</strong> refer to each individual city within this path.</p><ol><li><strong>Initialization</strong><br>Create an initial set of population(paths) of possible solutions. Each population(path) represents a possible route that visits all cities exactly once with the start and end city being the same.</li><li><strong>Fitness Calculation</strong><br>Evaluate the fitness of each path. The fitness is determined by the total distance of the route. Shorter routes have higher fitness.</li><li><strong>Selection</strong><br>Select parents from the current population based on their fitness. The higher-fitness population should have a higher chance of being selected.</li><li><strong>Crossover</strong><br>Apply crossover (recombination) to the selected parents to create offspring. This can be done using various crossover techniques such as order crossover, partially mapped crossover, or cycle crossover.</li><li><strong>Mutation<br></strong>Apply mutation to the offspring. This involves making small random changes to some of the genes (cities) in the population.</li><li><strong>Replacement<br></strong>Replace the old population with the combined population of parents and offspring.</li><li><strong>Termination<br></strong>We repeat steps 2–6 for a certain number of generations or until a stopping criterion is met (e.g. a sufficiently good solution is found or if we have iterated the number of generations).</li></ol><h3>Implementation</h3><p>Now that we have these steps to solve this problem in place, Let&#39;s take a problem instance to understand this better. Do not worry if the above steps do not make any sense. The problem instance we will discuss will help us go through each step in detail and make things clear. This problem instance is from my coursework assignment. (I swear this blog is being posted after the assignment&#39;s due date 🙂.)</p><p><em>Our Goal here is to find the shortest path among these 10 cities such that we start from City A, visit every city exactly once, and return back to </em><strong><em>City A </em></strong><em>with the shortest path.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0blxf_JknvYnRmG-kYw_dw.png" /><figcaption>A graph of 10 Cities along with their coordinates</figcaption></figure><p>We are given with coordinates of these 10 cities as shown on the above scale<br>e.g. A (X: 100, Y: 300) B (X: 200, Y: 130) C (X: 300, Y: 500), and so on.</p><p>We will start by implementing a Graph data structure to store this data and some helper functions that will help us along the way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MZQySkYH-HgUZzvNGYKraA.png" /></figure><p>In the above Graph class following are the <em>class members </em><br>- <strong>nodes_len</strong> is the number of nodes that will be stored in a graph<br>- <strong>roots </strong>is a dictionary that acts as an adjacency matrix to store the connections of nodes in a graph.<br>- <strong>nodes </strong>is a dictionary that stores the coordinates of the node<br>- <strong>start_city </strong>a configurable field to choose the start city in our TSP<br>- <strong>directed </strong>decides whether the graph is directed or not.</p><p><em>and the member functions</em></p><p>- <strong>addEdge: </strong>is a function that takes two nodes and a weight (distance) between two nodes<br>- <strong>addNode: </strong>is a function that takes a node and the coordinates of the node (x,y)<br>- <strong>distance: </strong>A helper function to calculate the distance between two nodes<br>- <strong>vertices</strong>: A helper function to return the list of nodes in the graph</p><p>Note that <strong>addEdge</strong> and <strong>addNode </strong>both are only added for convenience if we have distance between each pair of cities we can directly use <strong>addEdge.</strong></p><p>Now let&#39;s implement the Genetic Algorithm Class</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DX17DHxt5mCICGoc7hNwrg.png" /></figure><p>I will try to explain these class members in short here, if you find difficulty understanding the below terms that&#39;s totally fine. It is not uncommon to not understand them at this point, it will only get clearer when we look at each step of the algorithm in detail.</p><p><strong>population_size: </strong>Determines the possible number of solutions to the problem in each generation which will be optimized further to obtain a near-optimal solution.</p><p><strong>generations: </strong>The number of generations/iterations the algorithm should go through. Each generation involves the evaluation of the fitness of individuals in the population, the selection of parents for reproduction, crossover, mutation, and the creation of a new population.</p><p><strong>tournamentSize</strong>: The tournament size is the number of individuals participating in each tournament during tournament selection during the crossover.</p><p><strong>mutationRate: </strong>The mutation rate is a parameter that determines the likelihood of mutation occurring for each gene.</p><p><strong>fit_selection_rate: </strong>This parameter represents the rate or proportion of the fittest individuals(shortest path is fittest) in the population that will be directly carried over to the next generation without undergoing crossover or mutation. It’s a form of elitism, preserving some of the best solutions.</p><p>The program begins here in <strong>find_fittest_path </strong>we will leave this method here for our reference and go through this method one step at a time to get a clear picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lOrCP7W18R4NA9UVHoY8Ig.png" /></figure><p>we start by first generating a list of random cities (The list of <strong>possible</strong> solutions) for our TSP. Note that I am calling it a <strong>possible</strong> solution, As I mentioned above this is an optimization problem, generation 1 may/may not have the <strong>near-optimal solution. </strong>If it does, then it will be carried forward (<em>Survival of the fittest</em>) to <strong>newPopulation </strong>and if it doesn’t then the new offspring generated from the fittest parents will give rise to the near-optimal solution.</p><p>Let&#39;s go through the steps of the algorithm we defined above</p><h4>Initialization</h4><p>The <strong>randomizeCities</strong> method is responsible for generating a list of initial populations. It works in a way that it randomizes all the vertices except the <strong>start_city</strong> and then appends the start_city at the beginning and end of the generated population. <strong>Remember</strong><em> in TSP the salesman must return to the original city (start city).</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9QV5Q9_ygbkPEji3VnXibA.png" /><figcaption>The output at the end of the code shows the output generated by this function</figcaption></figure><p>Once we have generated the initial population, Our next work would be to select the fittest population and retain them as part of <strong>Generation 1</strong>. Each generation must have a population of <strong>population_size</strong></p><p>But the question is</p><blockquote>How many fits to select from the population and What exactly do we mean by fit?</blockquote><p>In the context of the Travelling Salesman problem, fitness is basically the distance of the path (in other problems it would mean different e.g. in the Sandwich recipe the <strong>taste score</strong> given to each sandwich was the fitness value). We intend to achieve the shortest path in TSP. So, the population with the shortest path would be deemed fit. And to select the number of fits we have already defined a fit factor called <strong>fit_selection_rate (</strong>in the range 0-1) to avoid overflow).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vWtO4LCFHtQWTWCCq5ge0g.png" /></figure><h4><strong>Fitness Calculation</strong></h4><p>So we calculate the fitness of our entire population using <strong>computeFitness and </strong>add the <strong>number_of_fits_to_carryover</strong> number of population from the current generation to <strong>newPopulation.</strong></p><p>But the <strong>newPopulation </strong>we generate in each generation must have a population of size <strong>population_size. </strong>So the remaining population (<strong>population_size - number_of_fits_to_carryover</strong>) will be generated in our next step of the algorithm using crossover and mutation.</p><h4>Selection</h4><p><strong>CrossOver </strong>is a process to produce offspring by combining the traits of parents. But,</p><blockquote>How do we decide which parents to select for crossover?</blockquote><p>We do this with the help of <strong>Tournament selection, </strong>This is the selection step in GA that determines which parents to select from the existing population for reproduction, This is an important step since selecting the right parent ensures the fit traits/genes are passed on to the next generation. Tournament Selection is a commonly used method for selecting the parents who will participate in the tournament.</p><p>This step is pretty much simple, we run a tournament among a subset of the population (of <strong>tournamentSize</strong>). This subset is randomly selected and the tournament selection is executed multiple times until the number of parents participating in the crossover are selected. <em>The selection criteria is basically to select the most fit individual among the subset of the population.</em></p><h4>Crossover</h4><p>Now Once we have two parents participating in crossover we need to decide how the crossover takes place to produce the offspring that is as fit as its parents. The idea of crossover is to select genes from both parents and add them to the offspring ensuring the genes in the offspring are unique. The goal is to generate diverse offspring with a combination of genetic material from both parents, potentially leading to improved solutions in the search space.</p><p>There are multiple methods of crossover such as <strong>partially mapped crossover</strong>, <strong>order crossover,</strong> etc with one-point and multiple-point crossovers.</p><ol><li><a href="https://en.wikipedia.org/wiki/Crossover_(genetic_algorithm)#Partially_mapped_crossover_(PMX)"><strong>Partially Mapped CrossOver (PMX)</strong></a></li></ol><p>Let&#39;s say we have these two parents from the Tournament selection</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3VC7Mo8RFIsiNjX8x8_CPw.png" /><figcaption>Parents participating in Crossover</figcaption></figure><p>and we want them to cross over to produce offspring. The steps for this cross-over are</p><ol><li>Select the points to cross over we can choose a single point or two points to divide the array into halves, let&#39;s select two points for our case the choice of selection is random (computed using <strong>computeTwoPointIndexes </strong>method<strong> </strong>in the source code)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bdfCY_JXcqvpo1aUSJS8eg.png" /><figcaption>Two-point indexes to copy the genes to offspring</figcaption></figure><p>2. Copy the genes between the two points from parent 1 to the offspring at the same location as the parent</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Xjk-26FPRES4qMUrOy6Lw.png" /><figcaption>genes copied from parent 1 to Offspring</figcaption></figure><p>3. Look for genes that have not been copied in the corresponding segment of parent 2, starting at the first position in the crossover point.<br>Gene <strong>I</strong> is the first uncopied Gene from parent 2( …, I, B, F, …) Copy I to Offspring at the location where E appears in Parent 2.</p><p>The next gene in (… I, B, F … ) is <strong>B</strong>, but since it is already present in Offspring we will skip it,</p><p>The next gene is <strong>F, </strong>It should be copied to the position occupied by B in parent 2, But that position is already occupied by C in the Offspring, so F will be copied to the position occupied by C in parent 2.</p><p>With this change, our Offspring will be</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ELcVpZbu3FVWWuhBDb8Kg.png" /></figure><p>4. The remaining elements of offspring are copied from parent 2 in the same order as they appear in parent 2.</p><p>The final Offspring generated after crossover is ‘IGHECBFDJ’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OR1LYdhnpiMChVrzUDLgpw.png" /></figure><p>2.<strong> </strong><a href="https://en.wikipedia.org/wiki/Crossover_(genetic_algorithm)#Order_crossover_(OX1)"><strong>Order Crossover(OX1)</strong></a><strong>:</strong> The order crossover is simpler than partially mapped crossover we choose multipoint crossover indexes generally more than two. We will choose two cross-over indexes for simplicity and choose the same example as the previous</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3VC7Mo8RFIsiNjX8x8_CPw.png" /><figcaption>Parents Participating in Order Crossover</figcaption></figure><ol><li>Select the points to cross over we must choose two or more points to divide the array into multiple halves. We will select the same indexes for simplicity, the choice of selection is random.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bdfCY_JXcqvpo1aUSJS8eg.png" /><figcaption>Two-point indexes to copy the genes to offspring</figcaption></figure><p>2. Copy the genes within the crossover indexes to Offspring in the same position as they appear in parent 1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tvn-XLWlmY4IFRV1khFZyw.png" /></figure><p>3. Now for each element in <strong>Parent 2</strong> copy the missing genes to Offspring in the same order as they appear. e.g. The first element not present in Offspring from parent 2 is G so G appears in the first position of Offspring, the second missing element is H so it appears next, and so on. So the newly generated Offspring is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fG4RtS8gtOFRl5wmxkJsYw.png" /><figcaption>Generated Offspring after Order Crossover</figcaption></figure><p>coming back to our implementation we will use Order Crossover to keep things simple.</p><blockquote>Notice the crossover implementation we are keeping the Offspring_length short by 2 to eliminate <strong>start_city</strong> from the start and end of the path. And adding it back once the offspring is generated (before return).</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aIoDyLI0mitbtuNYsSZVsA.png" /></figure><h4>Mutation</h4><p>The last step of the Genetic Algorithm for the current generation is Mutation, The idea of mutation is to make some random changes in the genes of the new Offspring. The primary purpose of mutation is to maintain diversity in the population. Without mutation, the genetic algorithm might get stuck with a local optimum where all individuals are quite similar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UntG8N72AKEbUzPWYBw3Sg.png" /></figure><p>And then for each iteration, we replace our old population with <strong>newPopulation</strong> obtained to achieve a better solution with every iteration. But there will be a point where the algorithm will converge even after introducing randomness in mutation, meaning Further iterations/generations cannot give a better solution so we stop the generations with the converged solution.</p><h4>Output</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ip5EBa9Uh3-BPYnmwfGxww.png" /><figcaption>The smaller values of population size and generations are only used to keep the output short</figcaption></figure><p>If you have made it to the end thank you so much for reading, hope this algorithm helped you understand the genetic algorithm and more importantly it gave you an idea of how it can be used to solve hard problems.</p><blockquote>Follow for updates on my new posts — Comment if you have any suggestions or critiques to help improve this post.</blockquote><p>You can find the complete source code for this problem <a href="https://github.com/maheshmnj/POPULAR_CODING_Questions_Solution/blob/master/algorithms/advanced/genetic.py">here</a>. I occasionally write on various topics, You can find all my blogs filtered based on topics in one place on my <a href="https://blog.maheshjamdade.com/">personal blog</a>.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31dfa57f3b62" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/the-genetic-algorithm-and-the-travelling-salesman-problem-tsp-31dfa57f3b62">The Genetic Algorithm and The Travelling Salesman Problem(TSP)</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Ultra gradients in flutter]]></title>
            <link>https://medium.com/flutter-community/creating-ultra-gradients-with-flutter-d4e87003358e?source=rss-a565d616dfb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4e87003358e</guid>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[gradient]]></category>
            <category><![CDATA[ui-design]]></category>
            <dc:creator><![CDATA[Mahesh Jamdade]]></dc:creator>
            <pubDate>Wed, 16 Aug 2023 02:31:33 GMT</pubDate>
            <atom:updated>2023-11-05T17:24:44.390Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gTJB0n7CN5pUqoPTjRxGxg.png" /></figure><p>Choosing the right background and surface colors in your app is always challenging and <strong>plain backgrounds are boring</strong>, especially when you are building apps with Flutter. Flutter was built to create beautiful experiences so why spend time building boring apps?</p><p>I have been working on a mobile app that supports different color schemes along with dark mode (thanks to <a href="https://docs.flutter.dev/ui/design/material">Material 3 support for Flutter</a>) to cater to the needs of the user and adapt to user preferences. But one thing that really makes the experience bland is the plain backgrounds and surfaces. We could have used Linear, Radial Gradients but choosing the right color to support multiple color themes and the dark mode is tedious and limited, Ultra gradient opens up a wide spectrum of colors and makes the content visible well, even in the dark mode.</p><p>By the end of this blog post, you will learn to create this animating ultra gradient in Flutter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*oY2buOGBCp1-nsRZPw2D4w.gif" /></figure><p>I came across this tweet the other day, which shows how to add ultra gradients in Figma I took that approach to flutter and the result turned out to be beautiful.</p><h3>Fons Mans on Twitter: &quot;New tutorial! ✨Learn how to create an &#39;ultra gradient&#39; with @figma, without using any plugins! Let&#39;s get started 👇 pic.twitter.com/5eMYoPJc3z / Twitter&quot;</h3><p>New tutorial! ✨Learn how to create an &#39;ultra gradient&#39; with @figma, without using any plugins! Let&#39;s get started 👇 pic.twitter.com/5eMYoPJc3z</p><p>At first glance it might seem challenging to implement this type of gradient without any third-party asset, However, if we follow the breakdown of intricacies provided by Mans in his tweets, achieving it becomes much more feasible.</p><p>So let&#39;s dive into the code and bring it into practice. We first start with a new flutter project with the usual counter app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iskQ9Twt1SI2vg1CtMzsGQ.png" /></figure><p>Now Since we are trying to create a background for our app we Should make the code reusable so we will create a Background Widget let&#39;s name it <strong>UltraBackground</strong> that takes a widget as input. An <strong>UltraBackground</strong> may need access to the default material colors so we will use Material Widget on top.</p><p>Since the ultra gradient is basically a layer beneath our widgets we will use a <strong>Stack</strong> to layout widgets on top of each other. With this change, your code should look something like this (Although no change in the output so far)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UdzGPzGHMmXzo5qaK6jRKg.png" /></figure><p>To start we need some background color to be painted for the ultra gradient to show up when the blobs are painted. So We will paint a background with a “black” Color. We can do this with the help of <a href="https://api.flutter.dev/flutter/rendering/CustomPainter-class.html">CustomPainter class</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VJJadIX4ZVS3J2apOpm6oA.png" /></figure><p>This should make the entire screen black making the content invisible and that is fine for now</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*JhYFkaNHTZrQscacBjkgMw.png" /></figure><p>Now let’s draw Some Abstract Shapes that we want to paint in the background, We will draw one abstract shape using a bezier curve and a square.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ExRLHXPkxlk3OK-oM4KAvw.png" /></figure><p>Now Apply a blur to these shapes using</p><pre> paint.maskFilter = MaskFilter.blur(BlurStyle.normal, 100);</pre><p>Add the above line before we paint these two shapes for the blur effect to be applied to them. With the above implementation, we should see these two shapes drawn with a blur effect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*qfQxxZ1aJq8oOszBu5I48w.png" /></figure><p>Now let&#39;s add some Contrasting shapes to the canvas, For simplicity we will draw an ellipse, A circle, and a Triangle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5kwvvLNF9FYULBtOw0KM1w.png" /></figure><p>With the above change, you should see the below output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*XiBXh4V6Ig6WFmmzgYiuEw.png" /></figure><p>Now let&#39;s apply a blur effect to these shapes and set the blend mode to overlay for these three shapes and we should see the Ultra Gradient in effect. We can do this by just adding the two lines in `drawContrastingBlobs`</p><pre>  void drawContrastingBlobs(Canvas canvas, Size size, Paint paint) {<br>    paint.maskFilter = MaskFilter.blur(BlurStyle.normal, 30);<br>    paint.blendMode = BlendMode.overlay;<br>    drawCircle(canvas, size, paint);<br>    drawTriangle(canvas, size, paint);<br>    drawEllipse(canvas, size, paint);<br>  }</pre><p>And we should see the following gradient on the Screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*XJcZP550QQkUhagFzsWkRg.png" /></figure><p>The result of the effect is totally dependent on the choice of colors and the Opacity. Let&#39;s take this a bit further and pair it with animation to make the effect dynamic. If we move the shapes around we should see different colors blending together to produce a dynamic gradient.</p><p>For that, we first need to decide the path these shapes will travel around we will draw a bezier curve for these shapes to smoothly move around.</p><p>so let&#39;s paint some paths on the screen to get a clear picture of their trajectory. The purple path is for Ellipse, Orange is for Circle and Green is for Triangle, These three shapes will move to and fro along this path.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*CZ5i5CAm8qlzVkTRhI04Lg.png" /></figure><p>So the last part we need to do is we need to change the position of these shapes along the path, But How do we identify the position of these shapes at a particular instance? Fortunately, flutter provides us with <a href="https://api.flutter.dev/flutter/dart-ui/Path/computeMetrics.html">ComputeMetrics Api </a>which basically gives us the details about the path and we can use it to find the offset of a widget where it lies along the path at a particular instance and pair it with animation to smoothly move it along the trajectory. Putting it all together you should see the shapes moving this way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*onC8ic7pmGgDhjq-h_Xj5g.gif" /></figure><p>We will also apply a blur effect between the canvas and the child for the generating colors to smoothly blend well together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9O3LhKwmycuYF_KakXMckw.png" /></figure><p>And finally applying the mask and the blur effect we should see this output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*oY2buOGBCp1-nsRZPw2D4w.gif" /></figure><p>The complete code sample is available in a <a href="https://gist.github.com/maheshmnj/d5cb45a3d73ebb1299c1f1206ee84425">Github gist</a>. Don’t forget to explore the entire open-source project on <a href="https://github.com/maheshmnj/vocabhub/tree/v0.7.5">Github</a> for a deeper understanding. Additionally, you can experience the app firsthand on the <a href="https://play.google.com/store/apps/details?id=com.vocabhub.app">Playstore</a>.<br> <br>Thanks for taking the time to read hope this helps you create stunning backgrounds for your app.</p><p>Happy Fluttering!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4e87003358e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutter-community/creating-ultra-gradients-with-flutter-d4e87003358e">Creating Ultra gradients in flutter</a> was originally published in <a href="https://medium.com/flutter-community">Flutter Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying futter app to Netlify Continuous deployment]]></title>
            <link>https://maheshjamdade.medium.com/deploying-futter-app-to-netlify-continuous-deployment-26e888cd6e76?source=rss-a565d616dfb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/26e888cd6e76</guid>
            <category><![CDATA[netlify]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <dc:creator><![CDATA[Mahesh Jamdade]]></dc:creator>
            <pubDate>Sat, 03 Jun 2023 18:39:01 GMT</pubDate>
            <atom:updated>2025-04-24T18:25:31.173Z</atom:updated>
            <content:encoded><![CDATA[<p>Flutter to Netlify: Seamlessly Deploy Your App with Continuous Deployment Delight!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XkO4tftFG1JpqFf9G60mVA.png" /></figure><p>Developing apps can feel overwhelming and take up a lot of time. On top of that, deploying web applications can be an added challenge. As developers, our focus should be on creating and improving our products, not getting stuck in the complexities of deployment. In this blog post, I’ll walk you through a straightforward process of deploying your Flutter app on Netlify using GitHub actions. For those who are not aware</p><blockquote>GitHub Actions is a continuous integration and continuous delivery (CI/CD) platform that allows you to automate your build, test, and deployment pipeline</blockquote><p>Whether you’re using Flutter or any other web framework, this post will provide you with simple steps to effortlessly deploy your app without any hassle.</p><p>We will be using <a href="https://github.com/marketplace/actions/netlify-actions">Netlify actions</a> which will run the GitHub workflow for every commit and deploy our web app. We will be deploying this <a href="https://github.com/maheshmnj/flutter-palm">flutter-palm </a>project which is basically a chat app powered by the <a href="https://developers.generativeai.google/products/palm">Google Palm Api</a>.</p><p>The app is available for use here <a href="https://palmchat.netlify.app/">https://palmchat.netlify.app</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kT8OBsN2bJ4H-_yyROS66w.png" /><figcaption>Screenshot of the deployed app</figcaption></figure><p>To set up Continuous deployment in your project first you need to create a new site on Netlify <a href="https://app.netlify.com/start">https://app.netlify.com/start</a> or you may also use the <a href="https://docs.netlify.com/cli/get-started/">Netlify CLI</a>, if you feel comfortable with it. Go to your team’s <strong>Sites</strong> page, open the <strong>Add New Site</strong> menu, and create a new site it should be pretty straightforward if you feel stuck see <a href="https://docs.netlify.com/welcome/add-new-site/">https://docs.netlify.com/welcome/add-new-site/</a></p><p>There are multiple ways of creating a site</p><ul><li>Import an existing project from a Git repository</li><li>Select a prebuilt site from Netlify Templates</li><li>Deploy local project files manually using Netlify’s deploy Dropzone</li></ul><p>Once you have your site created we need two things</p><ol><li><strong>OAuth Token</strong> is required to authorize workflow (which we will create in a moment) to deploy your site. Visit the <a href="https://app.netlify.com/user/applications#personal-access-tokens">Oauth access token </a>and create a new token.</li><li><strong>Site Id</strong> to identify unique to your site you can find your site id under <strong>Site</strong> <strong>Settings</strong> -&gt; <strong>General</strong> -&gt; <strong>Site details</strong> -&gt; <strong>Site id</strong></li></ol><p>We will need to provide these tokens to our workflow site. Don’t worry we won’t directly hardcode them in the script rather we will make use of Github secrets to store them and use them as variables in our workflow script.</p><p>Go to your project repository under <strong>Settings</strong>-&gt;<strong>secrets and variables</strong>-&gt;<strong>actions -&gt; create a new Repository secret <br></strong>And we will store our Netlify Oauth token and SiteId here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o2olYFtw1slFVYI9vhE3FQ.png" /><figcaption>The screenshot shows three secrets added in my repository API_KEY, Token, Site id</figcaption></figure><p>Once you have your secrets added note down the names of your secret because we will use them in our workflow script.</p><p>Now it&#39;s time to set up the Github workflow.</p><ol><li>In the root of your project create a <strong>workflows</strong> directory under <strong>.github,</strong> for me the directory path will be <strong>palmchat/.github/workflows</strong></li><li>Create a file named <strong>workflow.yml </strong>(name it whatever you like)</li><li>Paste the below <a href="https://github.com/maheshmnj/flutter-palm/blob/main/.github/workflows/workflow-merge.yml">workflow script</a>, most part of it is self-explanatory, But I will still try to explain whats cooking</li></ol><pre>name: Deploy to netlify on merge<br>&quot;on&quot;:<br>  push:<br>    branches:<br>      - main<br>jobs:<br>  build_and_deploy:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v2<br>      - uses: subosito/flutter-action@v2<br>        with:<br>          # flutter-version: &#39;3.3.10&#39;<br>          channel: &quot;stable&quot;<br>      - run: flutter clean<br>      - run: flutter pub get<br>      - run: flutter pub run build_runner build --delete-conflicting-outputs<br>      - run: flutter build web --release --dart-define=API_KEY=${{secrets.API_KEY}}<br>      - name: Deploy to Netlify<br>        uses: nwtgck/actions-netlify@v1.1<br>        with:<br>          publish-dir: &quot;./build/web&quot;<br>          production-branch: main<br>          github-token: ${{ secrets.GITHUB_TOKEN }}<br>          deploy-message: &quot;Deploy from GitHub Actions&quot;<br>          enable-pull-request-comment: false<br>          enable-commit-comment: true<br>          overwrites-pull-request-comment: true<br>        env:<br>          NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}<br>          NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}<br>        timeout-minutes: 1</pre><ol><li>The above script (named “Deploy to Netlify on merge”) executes every time we make a commit on the <strong>main </strong>branch.</li><li>It gets a stable version of flutter SDK (since we are trying to build a flutter app) using this action <a href="https://github.com/subosito/flutter-action">subosito/flutter-action@v2</a>.</li><li>It runs the flutter commands required to clean and build the release.</li><li>We then run the actual part which this blog post is about <em>deploying to Netlify</em></li></ol><pre>- name: Deploy to Netlify<br>        uses: nwtgck/actions-netlify@v1.1<br>        with:<br>          publish-dir: &quot;./build/web&quot;<br>          production-branch: main<br>          github-token: ${{ secrets.GITHUB_TOKEN }}<br>          deploy-message: &quot;Deploy from GitHub Actions&quot;<br>          enable-pull-request-comment: false<br>          enable-commit-comment: true<br>          overwrites-pull-request-comment: true<br>        env:<br>          NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}<br>          NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}<br>        timeout-minutes: 1</pre><p>The important part here is to check your <strong>production-branch </strong>name and path to <strong>publish-dir </strong>where your release build will be, after running the build in the previous step (<strong>flutter build web</strong> … in this case)</p><p>And finally, we define the <strong>env</strong> environment variables basically the secrets we added to Github to be used in this script.</p><p>Once we have this setup try making a commit to your repository and you should see your Github actions workflow running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QLXvxCL8T_BaKC0pmfBspw.png" /><figcaption>Previous workflow runs and their status</figcaption></figure><p>But at this point even if the workflow succeeds you won’t see your app running, because netlify doesn’t know which file to load under the build directory, or how to handle redirects, We specify that configuration in a file called netlify.toml</p><blockquote>The netlify.toml is a configuration file that specifies how Netlify builds and deploys your site — including redirects, branch and context-specific settings, and more.</blockquote><p>So create a file namednetlify.tomlin the web directory with the following content</p><pre>[[redirects]]<br>  from = &quot;/*&quot;<br>  to = &quot;/index.html&quot;<br>  status = 200</pre><p>Now once you make a commit and the workflow succeeds you should see your website deployed to your domain specified in Netlify, (<a href="https://palmchat.netlify.app/">https://palmchat.netlify.app</a> in this case, If it ever fails you can always look at the logs to figure out the error.</p><p>Additionally, if you want to handle your web app urls see <a href="https://github.com/flutter/flutter/issues/89763#issuecomment-925040018">https://github.com/flutter/flutter/issues/89763#issuecomment-925040018</a></p><p>I hope this blog post will help you grab a coffee while this workflow is busy deploying your web app to Netlify, if you have any questions or have problems deploying your web app feel free to write your queries in the comments and I would be happy to help.</p><p>Thanks for reading and have a happy time deploying :)</p><p>Curious about How to deploy a flutter web app to Github Pages check out my other blog here <a href="https://medium.com/@maheshmnj/deploying-your-flutter-webapp-to-github-pages-111ff9e5cbc9">https://medium.com/@maheshmnj/deploying-your-flutter-webapp-to-github-pages-111ff9e5cbc9</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26e888cd6e76" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[VS Code for Flutter hacks that will blow your mind]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/flutter-community/vs-code-for-flutter-hacks-that-will-blow-your-mind-648acd15a13d?source=rss-a565d616dfb4------2"><img src="https://cdn-images-1.medium.com/max/1920/1*ldqkuW0Io9f1ej9Q2Ln6Mw.jpeg" width="1920"></a></p><p class="medium-feed-snippet">When building software Productivity depends on various factors, including typing speed and accuracy. However, there are also many&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/flutter-community/vs-code-for-flutter-hacks-that-will-blow-your-mind-648acd15a13d?source=rss-a565d616dfb4------2">Continue reading on Flutter Community »</a></p></div>]]></description>
            <link>https://medium.com/flutter-community/vs-code-for-flutter-hacks-that-will-blow-your-mind-648acd15a13d?source=rss-a565d616dfb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/648acd15a13d</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[hacks]]></category>
            <category><![CDATA[vscode]]></category>
            <dc:creator><![CDATA[Mahesh Jamdade]]></dc:creator>
            <pubDate>Sun, 08 Jan 2023 20:22:49 GMT</pubDate>
            <atom:updated>2025-06-30T18:08:12.169Z</atom:updated>
        </item>
    </channel>
</rss>