<?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 Markandey Pathak on Medium]]></title>
        <description><![CDATA[Stories by Markandey Pathak on Medium]]></description>
        <link>https://medium.com/@markandeyp?source=rss-cba7901bffb4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RxSAOPMe2FJAvAEGMMUP3A.jpeg</url>
            <title>Stories by Markandey Pathak on Medium</title>
            <link>https://medium.com/@markandeyp?source=rss-cba7901bffb4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 13:25:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@markandeyp/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[Securing Your React App with Atlas App Authentication]]></title>
            <link>https://markandeyp.medium.com/mastering-atlas-web-sdk-part-1-1d55ac964d06?source=rss-cba7901bffb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d55ac964d06</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[user-authentication]]></category>
            <category><![CDATA[mongodb-atlas]]></category>
            <category><![CDATA[atlas-app-services]]></category>
            <dc:creator><![CDATA[Markandey Pathak]]></dc:creator>
            <pubDate>Tue, 27 Feb 2024 04:42:45 GMT</pubDate>
            <atom:updated>2024-02-27T04:42:45.777Z</atom:updated>
            <content:encoded><![CDATA[<h4>Mastering MongoDB Atlas Web SDK — Part 1</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aIY-dJrDRISVewKmIki9pA.png" /><figcaption>Mastering MongoDB Atlas Web SDK</figcaption></figure><p><a href="https://www.mongodb.com/docs/atlas/">MongoDB Atlas</a> is a fully managed cloud database service provided by MongoDB. It allows users to deploy, operate, and scale MongoDB databases with ease, eliminating the need for users to manage infrastructure tasks such as hardware provisioning, setup, configuration, patching, and backups. MongoDB Atlas offers a range of features tailored for different use cases, including high availability, automated backups, security features, and performance optimisation tools.</p><p>One aspect of MongoDB Atlas is the Atlas App Services. This is a suite of services provided as part of the MongoDB Atlas platform to help developers build, manage, and deploy modern applications more efficiently. These services include <strong><em>User authentication and management</em></strong>, <strong><em>Schema management and access rules</em></strong><em>, </em><strong><em>Device sync</em></strong><em>, </em><strong><em>GraphQL</em></strong><em>, </em><strong><em>Serverless functions</em></strong><em>, </em><strong><em>HTTP Endpoints</em></strong><em> </em>and much more. Atlas Device SDKs are available for various platforms like <strong><em>Kotlin</em></strong>, <strong><em>Swift</em></strong>, <strong><em>.NET</em></strong>, <strong><em>Java</em></strong>, <strong><em>Node.js,</em></strong> <strong><em>Flutter</em></strong>, <strong><em>React Native</em></strong>, <strong><em>C++</em></strong> and <strong><em>Web</em></strong>.</p><p>Throughout this entire series, our focus will remain on the Web SDK, delving into how Atlas App Services can seamlessly integrate with Web Applications to construct modern, data-centric applications. By leveraging the power of MongoDB Atlas and the capabilities offered by the Web SDK, we’ll uncover innovative approaches to building robust and efficient web-based solutions.</p><h3>Setting up the development environment</h3><p>For this entire series, all you need is a web browser. We will be using</p><ul><li><a href="https://glitch.com/">Glitch</a> for our development</li><li><a href="http://cloud.mongodb.com/">MongoDB</a> cloud account to setup Atlas App Services</li></ul><h4>Creating a MongoDB cloud account</h4><p>Establishing a MongoDB cloud account is straightforward. Just navigate to <a href="https://cloud.mongodb.com/">https://cloud.mongodb.com</a> and sign in via your Google or Github credentials. Alternatively, you have the option to register using your email address if preferred.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HO4VW5kv_ftYqELFDU-Csg.png" /><figcaption>Creating a MongoDB Atlas account</figcaption></figure><p>Upon account creation, it’s advisable to acquaint yourself with the User Interface. Initially, the array of configurations might appear overwhelming. However, fret not, as we’ll delve into them extensively as we advance through the series. For now, feel free to create a project and deploy a database to get started.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p24O1EDqGNPMJ8KNI9hyIw.png" /><figcaption>Creating a cluster</figcaption></figure><blockquote>MongoDB Atlas provides a notably generous free tier that grants you 512 MB of storage, and it remains free indefinitely. This complimentary tier encompasses the majority of the services mentioned previously.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c7Y_3nS3p-A0OJhxBIMZvg.png" /></figure><p>Opt for the M0 cluster tier, select your preferred provider among AWS, Google Cloud, and Microsoft Azure, and then choose a region nearest to your location for optimal performance. Provide a name for your cluster and proceed to click on the “Create” button. Your cluster will be created and deployed within a matter of minutes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EB9Uo9VZ0o48qRo-R_JLbg.png" /></figure><p>Upon the successful creation of your cluster, you have the option to create a user for accessing the MongoDB database. However, for the context of this article, this step is irrelevant. Instead, navigate to the <strong><em>“App Services”</em></strong> tab located at the top of the page as indicated below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*_d7OmvtvIpDhDly-gxu6Og.png" /></figure><p>With our cluster now prepared, we can proceed to create our application. The application creation wizard provides boilerplate options to expedite the project setup. Choose the <strong><em>“Build your own App”</em></strong> option and then click on <strong><em>“Next”</em></strong> to proceed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E-IE4MZXdraee7EH-dlQpw.png" /></figure><p>Enter a name for your application, select a data source (which will be the cluster created earlier), and proceed to click on <strong><em>“Create App Service”</em></strong> when you are prepared.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*69zhsuRHrm09dBM6aaalxA.png" /></figure><p>Each application is allocated a unique application ID, which serves as the identifier utilized by Atlas SDKs to establish connections with your application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*i1ClUd-lp-5k_datbPNIYA.png" /></figure><blockquote>The App ID, being non-sensitive information, can be safely stored within your codebase. However, the actual security measures at the application level are configured through the App settings, which include specifications such as Allowed Origins or Allowed IP Addresses, along with Data Access Rules.</blockquote><blockquote>To regulate requests to our Atlas App Services App, we can define a list of permitted origins. This can be accomplished by accessing the App Settings section from the left-hand sidebar, where you’ll find the setting for Allowed Request Origins, as depicted in the screenshot below.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yMmN7gf6Y9PTrHr-PbFn1g.png" /></figure><h4>Creating a Glitch account</h4><p>With our application configured, it’s time to commence building our web application. To get started, you can create a free Glitch account by visiting <a href="https://glitch.com/">https://glitch.com</a>. After logging in, you can access my boilerplate project at <a href="https://atlas-auth-boilerplate.glitch.me/">https://atlas-auth-boilerplate.glitch.me</a> and simply click on <strong><em>“Remix” </em></strong>to begin working on it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ptT5TyjxEzVs10avB-DnrQ.png" /><figcaption>Glitch boilerplate project</figcaption></figure><p>Once you’ve remixed the boilerplate project, it will be cloned for you, allowing you to start building on it immediately. Take note of the preview pane within the Glitch UI and copy the preview URL, which in your case would be <a href="https://atlas-auth-boilerplate.glitch.me/">https://atlas-auth-boilerplate.glitch.me</a>. This URL serves as your application URL. With our development environment fully configured, we’re now ready to commence building our web application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wa4O78ra7PgjQ4tGp3Pkyw.png" /><figcaption>Glitch preview pane</figcaption></figure><h3>Objectives</h3><p>To begin, we’ll set up the Email/Password authentication provider for our Atlas App. This will be followed by the construction of the Signup, Confirmation and Login screen to facilitate user registration. Finally, we’ll utilise the realm-web library to connect our Web Application to Atlas App Services.</p><h3>Setup Email/Password authentication provider</h3><p>To enable user registration/login using email and password, we must activate the Email/Password authentication provider in the Atlas UI. To do this, access your newly created Atlas Application and navigate to the Authentication option located on the left-hand sidebar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0slWHAUjbmYZrt0w-ZOutw.png" /><figcaption>Atlas App Services Authentication Providers</figcaption></figure><p>Click on the <strong><em>“Edit”</em></strong> button next to Email/Password from the list of providers. This action will direct you to the provider configuration page where you can enable and set up the provider. Configure the settings as follows:</p><ul><li>Toggle <strong><em>“Provider Enabled”</em></strong> to Yes</li><li>Select <strong><em>“Send a confirmation email”</em></strong> as the user confirmation method</li><li>Set the <strong><em>“Email confirmation URL”</em></strong> to <strong><em>&lt;your-glitch-url&gt;/verify</em></strong></li><li>Specify <strong><em>“Confirm your account”</em></strong> as the Email confirmation subject.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2unQFYH1rGamIa60QPVsWg.png" /><figcaption>Enabling Email/Password authentication provider</figcaption></figure><p>After configuring the provider settings, click on <strong><em>“Save Draft” </em></strong>to save your changes. A banner will then appear at the top, prompting you to <strong><em>“Review Draft &amp; Deploy”</em></strong> your modifications. This step helps prevent accidental alterations to your production application. Click on <strong><em>“Review Draft &amp; Deploy”</em></strong>, and your changes will be deployed shortly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cGA7Fr6WIDElaIJDlbzRrg.png" /><figcaption>Review Draft &amp; Deploy</figcaption></figure><h3>Building up screens</h3><p>The boilerplate code includes several pre-built screens, but they are currently non-functional. To begin adding functionality to these screens, we must first create an instance of the App class exposed by realm-web. Update the useEffect function in your app.jsx file as demonstrated below (remember to replace &lt;ATLAS APP ID&gt; with your actual App ID):</p><pre>useEffect(() =&gt; {<br>    setRealmApp(new App(&quot;&lt;ATLAS APP ID&gt;&quot;));<br>  }, []);</pre><p>The updated signup.jsx file under the pages directory should utilise realmApp to execute user signup. Upon the user entering their email and password and clicking the Signup button, we will invoke the realmApp.emailPasswordAuth.registerUser function. This function accepts email and password parameters and attempts to create a new user in your Atlas App. Handle the onClick event of the LoadingButton component as illustrated in the following code snippet:</p><pre>&lt;LoadingButton<br>          classNames=&quot;btn btn-primary&quot;<br>          text=&quot;Signup&quot;<br>          loading={loading}<br>          disabled={!email || !password}<br>          onClick={() =&gt; {<br>            setLoading(true);<br>            realmApp?.emailPasswordAuth<br>              .registerUser({ email, password })<br>              .then(() =&gt; setSuccess(true))<br>              .catch((err) =&gt; {<br>                setSuccess(false);<br>                setError(err.error);<br>              })<br>              .finally(() =&gt; {<br>                setEmail(&quot;&quot;);<br>                setPassword(&quot;&quot;);<br>                setLoading(false);<br>              });<br>          }}<br>        /&gt;</pre><p>Upon successful creation of the user account, the user will receive a confirmation email containing a link to verify their account. This step serves as a protective measure against potential misuse of your web application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9w34DbHQBB9FYYzaNrh-hg.png" /></figure><p>To handle the user confirmation task, we need to extract the token and tokenId parameters from the verification URL contained in the confirmation email. These parameters are appended to the URL specified while enabling the email/password authentication provider. Let’s update the pages/verify.jsx file with the following code to facilitate this process:</p><pre>useEffect(() =&gt; {<br>    realmApp?.emailPasswordAuth<br>      .confirmUser({ token, tokenId })<br>      .then(() =&gt; setSuccess(true))<br>      .catch((err) =&gt; {<br>        setError(err.error);<br>      })<br>      .finally(() =&gt; setLoading(false));<br>  }, [realmApp, token, tokenId]);</pre><p>This code snippet utilises the useEffect hook to trigger the confirmation process when the component mounts. It extracts the token and tokenId parameters from the URL and passes them to the realmApp.emailPasswordAuth.confirmUser function. Upon successful confirmation, the setSuccess function is invoked to indicate successful confirmation, while any errors are handled by setting the error state. Finally, the loading state is updated accordingly.</p><p>A user account is not active until first login. To enable users to log in, let’s update the onClick event of the LoadingButton component in the pages/login.jsx file. We’ll utilise the realmApp.login function and provide it with a Credentials object created using Credentials.emailPassword(). Here’s how you can update the onClick event:</p><pre>&lt;LoadingButton<br>          classNames=&quot;btn btn-primary&quot;<br>          text=&quot;Login&quot;<br>          loading={loading}<br>          disabled={!email || !password}<br>          onClick={() =&gt; {<br>            setError(false);<br>            setLoading(true);<br>            const credentials = Credentials.emailPassword(email, password);<br>            realmApp<br>              ?.logIn(credentials)<br>              .then(() =&gt; setUser(realmApp?.currentUser))<br>              .catch((err) =&gt; setError(err.error))<br>              .finally(() =&gt; {<br>                setEmail(&quot;&quot;);<br>                setPassword(&quot;&quot;);<br>                setLoading(false);<br>              });<br>          }}<br>        /&gt;</pre><p>Upon successful login, the context should indeed be updated with the realmApp.currentUser object. Additionally, the Header component should display the user’s email address along with a logout link.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EwTdIeerjj7oWPJbAxCx5A.png" /><figcaption>Logged in User</figcaption></figure><p>Handling the logout process is straightforward with realm-web. The realmApp.currentUser object provides a logOut function to execute the logout action. Since we have set realmApp.currentUser in our AppContext, the Header component can easily handle the onClick event of the Logout link. Here’s how you can update the header.jsx file to implement this functionality:</p><pre>const logout = useCallback(() =&gt; {<br>    user?.logOut();<br>    setUser(null);<br>  }, [user]);</pre><p>And there you have it! We have successfully implemented a complete Signup/Login flow using React and the realm-web SDK. With user registration, email confirmation, login functionality, and logout capability all in place, your application is now equipped with essential user authentication features. Great job!</p><p>Completed application can be viewed <a href="https://atlas-auth-demo.glitch.me/">here</a> and the source code can be access/remixed <a href="https://glitch.com/edit/#!/atlas-auth-demo">here</a>.</p><p>As the curtain falls on this inaugural chapter, we stand at the precipice of greatness. Join us in the forthcoming chapters as we delve deeper into the realm of MongoDB data consumption and continue our quest for application excellence. Stay tuned for an enlightening journey into the realm of web application development with MongoDB Atlas!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d55ac964d06" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Darting to Success — Part 3]]></title>
            <link>https://markandeyp.medium.com/darting-to-success-part-3-77e652198617?source=rss-cba7901bffb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/77e652198617</guid>
            <category><![CDATA[anonymous-function]]></category>
            <category><![CDATA[function-generators]]></category>
            <category><![CDATA[functions-in-dart]]></category>
            <category><![CDATA[dart-programming]]></category>
            <dc:creator><![CDATA[Markandey Pathak]]></dc:creator>
            <pubDate>Thu, 27 Apr 2023 22:20:57 GMT</pubDate>
            <atom:updated>2023-04-27T22:20:57.637Z</atom:updated>
            <content:encoded><![CDATA[<h3>Darting to Success — Part 3</h3><figure><img alt="Darting to Success — Highlight image" src="https://cdn-images-1.medium.com/max/1024/0*FKxPDa_4rW3OqOPz" /><figcaption>Darting to Success</figcaption></figure><h4>Mastering Functions in Dart</h4><p>Functions are a fundamental building block in programming, and they play a crucial role in Dart, a powerful and flexible programming language. Functions in Dart allow developers to encapsulate reusable blocks of code, abstracting complex logic, and promoting code reusability. Dart supports a rich set of features for functions, including various types of parameters, anonymous functions, lexical scope and closures, functions as first-class objects, and generators.</p><p>Understanding and effectively using functions in Dart is essential for writing efficient, modular, and maintainable code. Functions enable developers to organise and structure their code, making it easier to understand, debug, and maintain. Additionally, Dart’s support for lexical closures and generators opens up powerful possibilities for advanced programming techniques. In summary, functions are a fundamental concept in Dart programming, and mastering them is crucial for building robust and efficient applications. So, let’s get started.</p><p><strong>Creating a Function —</strong></p><p>A function has 3 basic properties — <strong><em>name</em></strong>, <strong><em>return-type</em></strong><em> </em>and<em> </em><strong><em>parameters</em></strong><em>.</em></p><pre>int sum(int a, int b) {<br>  return a + b;<br>}</pre><p>In above code snippet, sum is the name of our function which has an intreturn-type. The function accepts 2 intparameters a and b. To invoke the function, we can use the below syntax —</p><pre>sum(10,20);<br>// OR<br>var result = sum(10,20);</pre><p><strong>Parameters —</strong></p><p>Dart functions can have both <em>required</em> and <em>optional</em> parameters. Required parameters are those that must be provided when the function is called, while optional parameters can be omitted. Optional parameters can further be divided into two categories: <em>named</em> and <em>positional</em>.</p><p><strong>Required parameters —</strong></p><p>Required parameters are declared by specifying the parameter name and its type in the function signature. When calling the function, you must provide a value for each required parameter in the correct order. Here’s an example —</p><pre>void sayHello(String name) {<br>  print(&#39;Hello, $name!&#39;);<br>}<br><br>void main(){<br>  sayHello(&quot;Markandey&quot;);// Hello, Markandey!<br>  sayHello(); //Error - Too few positional arguments: 1 required, 0 given<br>}</pre><p>In this example, the sayHello function takes a required parameter called name of type String. When we call the sayHello function with the argument &#39;Markandey&#39;, it prints &quot;Hello, Markandey!&quot;. However, when we call the sayHellofunction without any arguments, we get a compilation error because we haven&#39;t provided a value for the required parameter name.</p><p><strong>Optional parameters —</strong></p><p>Dart provides two kinds of optional parameters: <em>named</em> and <em>positional</em>.</p><ol><li><strong>Named parameters —</strong></li></ol><p>Named parameters are surrounded by curly braces {} in the function signature. They allow you to specify arguments by name, so the order in which you provide them doesn&#39;t matter. Here&#39;s an example —</p><pre>void sayHello({String name = &#39;World&#39;, String message = &#39;Hello&#39;}) {<br>  print(&#39;$message $name!&#39;);<br>}<br><br><br>void main() {<br>  sayHello(name: &#39;Markandey&#39;, message: &#39;Hello&#39;); // Hello Markandey!<br>  sayHello(message: &#39;Hi&#39;, name: &#39;Bob&#39;); // Hi Bob!<br>  sayHello(); // Hello World!<br>}</pre><p>In above example sayHello function takes two <em>named</em> parameters name and message . We can supply these two in any order we want or can skip them altogether as we have made them <em>optional</em> by setting a default value.</p><p>If we want a named parameter to be required, we can use required keyword and remove the default value for the parameter. For example —</p><pre>void sayHello({required String name, String message = &#39;Hello&#39;}) {<br>  print(&#39;$message $name!&#39;);<br>}<br><br>sayHello(); // Error - name is required</pre><p>2. <strong>Positional parameters —</strong></p><p>Positional parameters are surrounded by square brackets [] in the function signature. They allow you to omit arguments when calling the function, and the values you provide are assigned to the parameters in the order they appear in the function signature. Here&#39;s an example —</p><pre>void sayHello(String name, [String message = &#39;Hello&#39;]) {<br>  print(&#39;$message $name!&#39;);<br>}<br><br>void main() {<br>  sayHello(&#39;Markandey&#39;, &#39;Hi&#39;); // &quot;Hi Markandey!&quot;<br>  sayHello(&#39;Robert&#39;, &#39;Hey&#39;); // &quot;Hey Robert!&quot;<br>  sayHello(&#39;Janet&#39;); // &quot;Hello Janet!&quot;<br>}</pre><p><strong>Anonymous functions —</strong></p><p>In Dart, you can define functions without a name using lambda expressions, also known as <em>anonymous</em> functions. Anonymous functions are often used when you need to pass a function as an argument (<em>callbacks</em> for example) to another function or when you need to create a closure.</p><p>Here’s an example of an anonymous function that takes two integers as parameters and returns their sum —</p><pre>void main() {<br>  final sum = (int x, int y) =&gt; x + y;<br>  print(sum(3, 4)); // 7<br>}</pre><p>In this example, we define an anonymous function using the =&gt; arrow syntax. We assign this function to a variable called sum and then call the sum function with the arguments 3 and 4, which returns 7.</p><p><strong>The </strong><strong>main Function —</strong></p><p>The main function is the entry point of any Dart application. It has a specific syntax and requirements. Here&#39;s how you can define and use the main function in a Dart program —</p><pre>void main() {<br>  print(&#39;I am the main() guy&#39;);<br>}</pre><p>main() can accept command-line arguments as parameters as a list of strings arguments when running the Dart program from the command line.</p><pre>// Dart program that accepts command-line arguments<br>void main(List&lt;String&gt; arguments) {<br>  // Accessing command-line arguments<br>  print(&quot;Number of arguments: ${arguments.length}&quot;);<br>  print(&quot;Arguments: $arguments&quot;);<br>}</pre><p>When you run the above Dart program from the command line, you can provide arguments separated by spaces —</p><pre>dart main_function.dart arg1 arg2 arg3</pre><p><strong>Generators in Dart —</strong></p><p>Dart provides a special type of function called a <em>generator</em> function, which can be used to generate a sequence of values or data lazily. Generator functions are defined using the sync* or async*keywords and use the yield keyword to return values one at a time.</p><p>Consider following function to generate n natural numbers —</p><pre>Iterable&lt;int&gt; naturalsTo(int n){<br>  List&lt;int&gt; naturals = [];<br>  var k = 0;<br>  while(k &lt; n) {<br>    print(&#39;adding $k&#39;);<br>    naturals.add(k);<br>    k++;<br>  }<br>  return naturals;<br>}<br><br>void main() {<br>  var naturals = naturalsTo(10);<br>  for(var natural in naturals){<br>    print(natural); <br>  }<br>}</pre><p>naturalsTo function runs the loop and generates the numbers from 0 to n as soon as we invoke the function in line var naturals = naturalsTo(10); . We might or might not need all those values immediately.</p><p>When executed, the above code generates the below output —</p><pre>adding 0<br>adding 1<br>adding 2<br>adding 3<br>adding 4<br>adding 5<br>adding 6<br>adding 7<br>adding 8<br>adding 9<br>0<br>1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9</pre><p>All these numbers are stored in memory even when we don’t need them. This often is the case when we are working with relatively larger datasets. This impacts memory usage and thus performance of the applications.</p><p>Generator functions are designed to solve this exact issue. Consider the following code —</p><pre>Iterable&lt;int&gt; naturalsGenerator(int n) sync* {<br>  int k = 0;<br>  while (k &lt; n) {<br>    print(&#39;yielding $k&#39;);<br>    yield k++;<br>  }<br>}<br><br>void main() {<br>  naturals = naturalsGenerator(10);<br>  for(var natural in naturals){<br>    print(natural);<br>  }<br>}</pre><p>naturalsGenerator is a synchronous generator function (notice the sync* ). yield operator is used to generate the next value in the sequence. Instead of generating all the data at once and storing it in memory, we can use a generator to lazily generate the data as it’s needed. This can help reduce memory usage and improve performance.</p><p>When we run the above code, we get the following output —</p><pre>yielding 0<br>0<br>yielding 1<br>1<br>yielding 2<br>2<br>yielding 3<br>3<br>yielding 4<br>4<br>yielding 5<br>5<br>yielding 6<br>6<br>yielding 7<br>7<br>yielding 8<br>8<br>yielding 9<br>9</pre><p>Generators can be used in many real-life use cases in Dart (or Flutter when we get there). Here are a few examples —</p><ol><li><strong>Infinite Scrolling —</strong> In many mobile or web applications, users can scroll through a list or feed infinitely. Using generators, we can generate the list or feed items lazily, only generating the items that are needed as the user scrolls.</li><li><strong>Data Paging — </strong>When working with large datasets, it’s often more efficient to retrieve data in smaller chunks, or “pages.” Generators can be used to lazily load each page of data as it’s needed.</li><li><strong>Animation —</strong> Animations often involve generating a sequence of values over time. Generators can be used to generate these values lazily, only generating the values that are needed at each frame of the animation.</li><li><strong>Data Stream Processing —</strong> When processing data streams, it’s often more efficient to process the data in chunks rather than all at once. Generators can be used to generate the data stream chunks lazily.</li><li><strong>Data Filtering —</strong> When working with large datasets, we may only be interested in a subset of the data. Generators can be used to filter the data lazily, only generating the data items that meet the filtering criteria.</li><li><strong>Data Transformation —</strong> In some cases, we may need to transform data from one format to another. Generators can be used to generate the transformed data lazily, only generating the transformed data items as they are needed.</li></ol><h4><strong>Conclusion</strong></h4><p>In this article, we covered the essentials of working with functions in Dart, including <strong><em>defining</em> <em>functions</em></strong>, <strong><em>passing</em> <em>arguments</em></strong>, and <strong><em>returning</em> <em>values</em></strong>. We also explored advanced features such as <strong><em>anonymous functions</em></strong> and <strong><em>generators</em></strong>, which can greatly enhance your application development.</p><p>In our next article in this series, we will explore <strong><em>Dart classes and OOP concepts</em></strong>, which are a powerful feature for creating reusable code and building complex applications. We will cover class <strong><em>inheritance</em></strong>, <strong><em>interfaces</em></strong>, and <strong><em>abstract classes,</em></strong> as well as explore best practices for working with classes in Dart. So stay tuned for the next article in our “<strong><em>Darting to Success</em></strong>” series, where we will continue our journey to becoming a Dart programming expert!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77e652198617" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Darting to Success — Part 2]]></title>
            <link>https://markandeyp.medium.com/darting-to-success-part-2-213775090fc3?source=rss-cba7901bffb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/213775090fc3</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[lists]]></category>
            <category><![CDATA[maps]]></category>
            <category><![CDATA[collection]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Markandey Pathak]]></dc:creator>
            <pubDate>Mon, 10 Apr 2023 13:36:13 GMT</pubDate>
            <atom:updated>2023-04-10T13:36:13.002Z</atom:updated>
            <content:encoded><![CDATA[<h3>Darting to Success — Part 2</h3><figure><img alt="Darting to Success — Highlight image" src="https://cdn-images-1.medium.com/max/1024/0*zAmMfx3I5pUPrLOk" /><figcaption>Darting to Success</figcaption></figure><h4>Collection Data Types in Dart</h4><p>Data types are the building blocks of any application. They allow us to represent and manipulate data in various ways. In addition to the basic data types like numbers and strings, Dart also provides complex data structures such as arrays, lists, maps, and sets, which are essential for handling more complex data. In this article, we will dive into the world of complex data types in Dart, exploring their features, use cases, and how to work with them effectively.</p><h4>Lists</h4><p>In Dart, the List type is used to represent arrays, which are dynamic arrays that can grow or shrink in size. Dart does not have a built-in fixed-size array type like some other programming languages.</p><p><strong>Declaring and initialising a </strong><strong>List —</strong></p><pre>var numbers = [1, 2, 3, 4, 5]; //inferred type List&lt;int&gt;<br><br>//or<br><br>List&lt;String&gt; names = [&#39;Dart&#39;, &#39;Java&#39;, &#39;JavaScript&#39;];<br>print(names.length); // 3</pre><p><strong>Accessing/Modifying elements in a </strong><strong>List —</strong></p><pre>print(names[2]); // JavaScript<br>names[2] = &#39;C++&#39;;<br>print(names[2]); // C++<br>print(names.first); // Dart<br>print(names.last); // C++</pre><p><strong>Iterating through elements in a </strong><strong>List —</strong></p><pre>for(var i=0; i&lt;names.length; i++){<br>  print(names[i]);<br>}<br><br>// or, simply<br><br>for(var name in names){<br>  print(name);<br>}</pre><p><strong>Adding elements to a </strong><strong>List —</strong></p><pre>names[3] = &#39;PHP&#39;; // throws Index out of range exception<br><br>names.add(&#39;PHP&#39;); // appends PHP to the list<br>print(names[3]); // PHP<br><br>names.addAll([&#39;Python&#39;,&#39;R&#39;]); // appends Python and R to the list<br>names.insert(2, &#39;VBScript&#39;); // inserts VBScript at index 2 <br>                             // and shifts items to the right<br>print(names); // [Dart, Java, VBScript, JavaScript, PHP, Python, R]</pre><p><strong>Removing elements from a </strong><strong>List —</strong></p><pre>names.remove(&#39;VBScript&#39;); // removes VBScript from the list<br>print(names); // [Dart, Java, JavaScript, PHP, Python, R]<br>names.removeAt(2); // removes items at index 2 (JavaScript)<br>print(names); // [Dart, Java, PHP, Python, R]<br>names.clear(); // clears the list<br>print(names); // []</pre><p><strong>Checking for element existence in a </strong><strong>List —</strong></p><pre>names = [&#39;Dart&#39;, &#39;Java&#39;, &#39;JavaScript&#39;];<br>print(names.contains(&#39;Java&#39;)); // true<br>print(names.contains(&#39;C#&#39;)); // false</pre><p>In addition to the methods mentioned above, Dart List also provides several other useful methods such as indexOf, lastIndexOf, sublist, replaceRange, retainWhere, and many more for performing various operations on the list.</p><p>Dart <a href="https://api.dart.dev/stable/2.19.6/dart-core/List-class.html">documentation</a> provides comprehensive information about all the available methods and their usage.</p><h4>Maps</h4><p>Maps in Dart are collection objects that store data as key-value pairs. They are also sometimes referred to as dictionaries or associative arrays in other programming languages. In Dart, maps are represented by the Map class, which is part of the core libraries and provides a flexible way to store and manipulate data.</p><p><strong>Declaring and initialising a </strong><strong>Map —</strong></p><pre>// creating a Map with keys and values of String type<br>Map&lt;String, String&gt; elements = Map&lt;String, String&gt;();<br>elements[&quot;C&quot;] = &quot;Carbon&quot;;<br>elements[&quot;N&quot;] = &quot;Nitrogen&quot;;<br>elements[&quot;O&quot;] = &quot;Oxygen&quot;;<br><br>// or using shorthand<br><br>// inferred type is Map&lt;int, String&gt;<br>var userTypes = {<br>  1: &quot;Admin&quot;,<br>  2: &quot;Staff&quot;,<br>  3: &quot;User&quot;<br>};</pre><p><strong>Accessing/Modifying elements in a </strong><strong>Map —</strong></p><pre>print(elements[&quot;C&quot;]); // Carbon<br>print(userTypes[1]); // Admin<br><br>userTypes[3] = &quot;Superadmin&quot;;<br>print(userTypes[3]); // Superadmin</pre><p><strong>Iterating through elements in a </strong><strong>Map —</strong></p><p>To iterate through the key-value pairs of a map in Dart, you can use Map.entries, which is an iterable that contains MapEntry objects representing the keys and values. Each MapEntry object contains a key and a value, allowing you to access and manipulate them during iteration.</p><p>You can also use Map.keys and Map.values to iterate through the keys and values of a map in Dart. Map.keys returns an iterable of keys, and Map.values returns an iterable of values. You can use a for loop or other iterable methods to loop through these iterables and access the keys or values of the map.</p><pre>/* output<br>  C : Carbon<br>  N : Nitrogen<br>  O : Oxygen<br>*/<br>for(var element in elements.entries){<br>  print(&quot;${element.key} : ${element.value}&quot;);<br>}<br><br>/* output<br>  C<br>  N<br>  O<br>*/<br>for(var key in elements.keys){<br>  print(key);<br>}<br><br>/* output<br>  Carbon<br>  Nitrogen<br>  Oxygen<br>*/<br>for(var value in elements.values){<br>  print(value);<br>}</pre><p><strong>Other operations in a </strong><strong>Map —</strong></p><p>Maps in Dart provide several other operations like isEmpty, length, clear, containsKey, putIfAbsent, addAll, remove, update, and forEach. These operations provide flexibility and versatility for managing and manipulating key-value pairs in Dart.</p><pre>// check if map is empty<br>print(elements.isEmpty); // false<br>// check map size<br>print(elements.length); // 3<br>// remove all entries<br>elements.clear();<br>// check if a key exists<br>elements.containsKey(&quot;C&quot;); // true<br>// check if a key exists, add if doesn&#39;t<br>elements.putIfAbsent(&quot;H&quot;, () =&gt; &quot;Hydrogen&quot;); // adds key &quot;H&quot; with value Hydrogen<br>elements.putIfAbsent(&quot;C&quot;, () =&gt; &quot;Carbon&quot;); // does nothing as key &quot;C&quot; exists<br>// add all elements from a map to another map<br>// {C: Carbon, N: Nitrogen, O: Oxygen, H: Hydrogen, He: Helieum, Li: Lithium}<br>elements.addAll({&quot;He&quot;: &quot;Helieum&quot;, &quot;Li&quot;: &quot;Lithium&quot;});</pre><p>Dart <a href="https://api.dart.dev/stable/2.19.6/dart-core/Map-class.html">documentation</a> provides comprehensive information about all the available methods and their usage.</p><h4>Sets</h4><p>Sets in Dart are unordered collections of unique values, where each value can only appear once in the set. Sets are implemented using the Set class in Dart and provide various methods for performing operations on sets.</p><p><strong>Declaring and initialising a </strong><strong>Set —</strong></p><p>You can create a set in Dart using the Set constructor or by using the set literal syntax {}. For example:</p><pre>Set&lt;int&gt; numbers = Set&lt;int&gt;();<br>numbers.add(1);<br>numbers.add(2);<br>numbers.add(3);<br>numbers.add(2); // ignored as duplicate<br>print(numbers); // {1, 2, 3}<br>  <br>// OR<br>var fruits = &lt;String&gt;{&quot;Apple&quot;, &quot;Banana&quot;, &quot;Orange&quot;};<br>print(fruits); // {Apple, Banana, Orange}</pre><p><strong>Accessing/Modifying elements in a </strong><strong>Set —</strong></p><pre>print(fruits.elementAt(0)); // Apple<br>print(fruits.first) // Apple<br>print(fruits.last) // Orange<br><br>fruits.remove(&quot;Banana&quot;); // remove Banana from Set<br>print(fruits); // {Apple, Orange}</pre><p><strong>Iterating through elements in a </strong><strong>Set —</strong></p><p>You can iterate through the elements of a set using a for-in loop. You can also use skip to skip elements while iterating and take to take a certain number of elements.</p><pre>/* output<br>  Apple<br>  Orange<br>*/<br>for(var fruit in fruits){<br>  print(fruit);<br>}<br><br>var numbers = &lt;int&gt;{1,2,3,4,5,6,7,8,9,10};<br>// skip first 3 and take next 5<br>print(numbers.skip(3).take(5)); // (4, 5, 6, 7, 8)<br></pre><p><strong>Set Algebra in a </strong><strong>Set —</strong></p><p>Dart provides built-in methods for performing various set operations such as union, difference, intersection, and symmetric difference. The union() method can be used to combine two sets into a new set that contains all elements from both sets, without duplicates. The difference() method returns a new set that contains elements from the first set that are not present in the second set. The intersection() method returns a new set that contains only the elements that are common to both sets. These set operations are powerful tools for manipulating sets in Dart, enabling developers to efficiently perform set-related tasks in their applications.</p><pre>var users = {&quot;Rob&quot;, &quot;Jack&quot;, &quot;Julia&quot;, &quot;Fatima&quot;};<br>var admins = {&quot;Julia&quot;, &quot;Donald&quot;, &quot;Matt&quot;};<br>  <br>print(users.union(admins)); // {Rob, Jack, Julia, Fatima, Donald, Matt}<br>print(users.intersection(admins)); // {Julia}<br>print(users.difference(admins)); // {Rob, Jack, Fatima}</pre><p><strong>Other operations in a </strong><strong>Map —</strong></p><p>Sets in Dart provide several other operations like isEmpty, length, clear, contains, addAll, remove, and forEach. Dart <a href="https://api.dart.dev/stable/2.19.6/dart-core/Set-class.html">documentation</a> provides comprehensive information about all the available methods and their usage.</p><h4>Conclusion</h4><p>In this article, we covered the essentials of working with collections in Dart, including <strong><em>Lists</em></strong>, <strong><em>Maps</em></strong>, and <strong><em>Sets</em></strong>, and explored various collection operations with examples. These powerful data structures are fundamental to Dart programming and can greatly enhance your application development.</p><p>In the next article in this series, we will dive into Dart <strong><em>functions</em></strong> in depth, covering topics such as defining functions, passing arguments, returning values, and exploring advanced features like closures and anonymous functions. So stay tuned for the next article in our <strong><em>“Darting to Success”</em></strong> series, where we will continue our journey to becoming a Dart programming expert!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=213775090fc3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Darting to Success — Part 1]]></title>
            <link>https://markandeyp.medium.com/darting-to-success-part-1-ae24c804c0e5?source=rss-cba7901bffb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae24c804c0e5</guid>
            <category><![CDATA[beginners-guide]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Markandey Pathak]]></dc:creator>
            <pubDate>Thu, 06 Apr 2023 22:45:51 GMT</pubDate>
            <atom:updated>2023-04-06T22:45:51.475Z</atom:updated>
            <content:encoded><![CDATA[<h3>Darting to Success — Part 1</h3><figure><img alt="Darting to Success — Highlight image" src="https://cdn-images-1.medium.com/max/1024/0*3GlQa0Ii-CYdV7To" /><figcaption>Darting to Success</figcaption></figure><h3>Getting Started with Dart: An Introduction to the Basics</h3><p>Dart is an open-source programming language developed by Google. Dart is often used for web and mobile app development, server-side programming, and command-line scripts. Dart is an <strong><em>object-oriented</em></strong>, <strong><em>class-based</em></strong> language with support for interfaces, mixins, and extension methods. Dart features <strong><em>strong and static typing</em></strong>, which allows for faster code execution and fewer runtime errors.</p><p>In this article, we’ll cover the basics of Dart programming, including setting up the development environment, Dart syntax, variables and operators, control flow statements, and functions. We’ll assume you have some programming experience but no prior knowledge of Dart.</p><h4>Setting up the Development Environment</h4><p>Setting up a development environment for Dart programming is essential for several reasons, even though you can use online tools like <a href="https://dartpad.dev/"><strong>https://dartpad.dev/</strong></a> for quick experimentation and learning. Here are some reasons why setting up a local development environment is beneficial —</p><ol><li>Offline Access</li><li>Full Development Experience</li><li>Customisation and Flexibility</li><li>Real-world Development</li><li>Collaboration and Teamwork</li></ol><p>Before we can start writing Dart code, we need to set up the development environment. Here are the steps to follow —</p><h4>Step 1 — Install the Dart SDK</h4><p>The first step is to install the Dart SDK, which includes the Dart command-line tools, libraries, and virtual machine. You can download the Dart SDK from the official Dart website at <a href="https://dart.dev/get-dart">https://dart.dev/get-dart</a>. Choose the appropriate version for your operating system and follow the installation instructions.</p><h4>Step 2: Install a Text Editor</h4><p>Next, we need a text editor to write our Dart code. There are several popular text editors that support Dart, including DartPad, DartPad Online, Visual Studio Code, and IntelliJ IDEA. For this article, we’ll be using Visual Studio Code, which is a free and open-source code editor from Microsoft.</p><p>You can download Visual Studio Code from the official website at <a href="https://code.visualstudio.com/download">https://code.visualstudio.com/download</a>. Follow the installation instructions and launch Visual Studio Code.</p><h4>Step 3: Create a New Dart Project</h4><p>Now that we have the Dart SDK and a text editor installed, let’s create a new Dart project. Open Visual Studio Code and click on the <strong>“Explorer”</strong> tab on the left-hand side. Click on the <strong>“Open Folder”</strong> button and choose a location to create your new project.</p><p>Once you have created a new folder for your project, open the integrated terminal in Visual Studio Code by selecting <strong>“Terminal” &gt; “New Terminal”</strong> from the menu bar. In the terminal, run the following command to create a new Dart project —</p><pre>dart create basics</pre><p>This will create a new Dart project in the basics folder, with the following structure —</p><figure><img alt="Dart project structure" src="https://cdn-images-1.medium.com/max/323/1*U14hRBeG4FsPx9JEtd3_Og.png" /><figcaption>Dart project structure</figcaption></figure><p>The bin folder contains the main entry point of the Dart program, which is the basics.dart file. The lib folder is where you can put your Dart libraries, and the test folder is for unit tests. The pubspec.yaml file is used to manage dependencies for your Dart project.</p><h4>Step 3: Run Dart Application</h4><p>lib/basics.dart contains following very basic boilerplate code —</p><pre>int calculate() {<br>  return 6 * 7;<br>}</pre><p>calculate is a function which returns the product of 6 and 7 i.e. <strong>42 </strong>every time it is invoked.</p><p>bin/basics.dart contains the main function. main, like many other programming languages, is entry point for a Dart application. It contains the following boilerplate code —</p><pre>import &#39;package:basics/basics.dart&#39; as basics;<br><br>void main(List&lt;String&gt; arguments) {<br>  print(&#39;Hello world: ${basics.calculate()}!&#39;);<br>}</pre><p>import ‘package:basics/basics.dart’ as basics; imports the lib/basics.dart so we can use the calculate function in out bin/basics.dart code.</p><p>print function display the provided arguments on standard output device. In case above, when run, the code should print Hello world: 42! on the screen.</p><p>To run the application, on terminal (at the project root) execute following command —</p><pre>dart run</pre><figure><img alt="Dart code execution output. It displays “Hello world: 42!”" src="https://cdn-images-1.medium.com/max/551/1*kQ58KTkVxQzp_0ckOGXzyQ.png" /><figcaption>Dart code execution output</figcaption></figure><h4>Dart Syntax</h4><p>Now that we have our development environment set up, let’s dive into Dart syntax. Dart syntax is similar to other programming languages, such as Java, C++, and JavaScript. However, Dart has some unique features, such as its support for asynchronous programming and its strong and static typing system.</p><h4>Declaring Variables</h4><p>In Dart, you declare variables using the var, final, or const keywords. var is used to declare a variable whose type is inferred by the compiler. final is used to declare a variable that can only be assigned once, and const is used to declare a compile-time constant.</p><pre>var name = &#39;Markandey Pathak&#39;; // inferred type String<br>final age = 32; // type int, cannot be reassigned<br>const pi = 3.14; // type double, compile-time constant</pre><h4>Basic Data Types</h4><p>Dart has several basic data types, including int, double, bool, String, and dynamic. int represents integer values, double represents floating-point values, bool represents boolean values (true or false), String represents a sequence of characters, and dynamic represents a dynamically-typed value that can change its type at runtime.</p><p>Here’s an example of declaring variables with different data types in Dart —</p><pre>int age = 25;<br>double height = 5.7;<br>bool isStudent = true;<br>String name = &#39;Bob&#39;;<br>dynamic myVar = &#39;Hello&#39;; // can change type later</pre><h4>Operators</h4><p>Dart supports a variety of operators, including arithmetic, comparison, logical, and assignment operators. Here are some examples —</p><pre>int a = 5;<br>int b = 10;<br><br>int sum = a + b; // addition<br>int difference = a - b; // subtraction<br>int product = a * b; // multiplication<br>double quotient = a / b; // division (returns double)<br><br>bool isEqual = a == b; // equality<br>bool isNotEqual = a != b; // inequality<br>bool isGreater = a &gt; b; // greater than<br>bool isLess = a &lt; b; // less than<br><br>bool isTrue = true;<br>bool isFalse = false;<br><br>bool result = isTrue &amp;&amp; isFalse; // logical AND<br>bool result2 = isTrue || isFalse; // logical OR<br>bool result3 = !isTrue; // logical NOT<br><br>a += b; // shorthand for a = a + b<br>a *= b; // shorthand for a = a * b</pre><h4>Control Flow Statements</h4><p>Dart supports various control flow statements, including if, else, switch, for, while, and do-while. These statements allow you to control the flow of execution in your Dart program.</p><p>Here’s an example of an if statement in Dart —</p><pre>int age = 18;<br><br>if (age &gt;= 18) {<br>  print(&#39;You are an adult&#39;);<br>} else {<br>  print(&#39;You are not an adult&#39;);<br>}</pre><p>And here’s an example of a switch statement in Dart —</p><pre>String grade = &#39;A&#39;;<br><br>switch (grade) {<br>  case &#39;A&#39;:<br>    print(&#39;Excellent&#39;);<br>    break;<br>  case &#39;B&#39;:<br>    print(&#39;Good&#39;);<br>    break;<br>  case &#39;C&#39;:<br>    print(&#39;Average&#39;);<br>    break;<br>  default:<br>    print(&#39;Fail&#39;);<br>}</pre><h4>Functions</h4><p>Functions are a fundamental concept in Dart, just like in most programming languages. Dart supports both named and anonymous functions, and functions can take parameters and return values.</p><p>Here’s an example of a <strong><em>named</em></strong> function in Dart —</p><pre>int add(int a, int b) {<br>  return a + b;<br>}<br><br>int sum = add(5, 10); // calling the function<br>print(&#39;Sum: $sum&#39;); // output: Sum: 15</pre><p>And here’s an example of an <strong><em>anonymous</em></strong> function, also known as a <strong><em>lambda function,</em></strong> in Dart —</p><pre>var multiply = (int a, int b) =&gt; a * b; // multiply is a variable which holds<br>                                        // reference to an anonymous function<br>int product = multiply(3, 4); // calling the function<br>print(&#39;Product: $product&#39;); // output: Product: 12</pre><h4>Conclusion</h4><p>In this article, we covered the basics of Dart programming, including setting up the development environment, Dart syntax, variables and operators, control flow statements, and functions. We explored how to declare variables, use basic data types, work with operators, control the flow of execution with control flow statements, and create functions in Dart.</p><p>In the next article in this series, we will dive deeper into the Dart language, exploring its basic syntax, data types, and control flow. We will also explore advanced topics such as object-oriented programming, error handling, and asynchronous programming. So stay tuned for the next article in our <strong><em>“Darting to Success”</em></strong> series, where we will continue our journey to becoming a Dart programming expert!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae24c804c0e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an Offline Flutter App With MongoDB Realm]]></title>
            <link>https://medium.com/better-programming/building-an-offline-app-with-mongodb-realm-8d4d00f8646f?source=rss-cba7901bffb4------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d4d00f8646f</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[realm]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Markandey Pathak]]></dc:creator>
            <pubDate>Wed, 27 Apr 2022 02:51:38 GMT</pubDate>
            <atom:updated>2022-06-10T08:48:06.757Z</atom:updated>
            <content:encoded><![CDATA[<h4>Choosing a data store for mobile applications can be a daunting experience for Flutter developers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5-TYwC0tt3y8QbMt" /><figcaption>Photo by <a href="https://unsplash.com/@casparrubin?utm_source=medium&amp;utm_medium=referral">Caspar Camille Rubin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Realm’s mobile database is an open-source, developer-friendly alternative to KeyValue pairs, SQLite and Firestore. Start in minutes and save yourself weeks of work.</p><p>Realm is offline first, object-oriented, intuitive, and is built for mobiles.</p><p>In this article, we will build an offline mobile app using Flutter and Realm SDK.</p><h4>What we will build?</h4><p>We will be building a very simple Shopping List application where the user can view the list of items, add a new item, and toggle &amp; delete existing items.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MX-J0Q4BqRr3jxkXempgAw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mMYDCngMmnxz0wcqLoWr2g.png" /><figcaption>Application Screens</figcaption></figure><h4>What you will need?</h4><ul><li>flutter installed &amp; configured</li><li>your favorite IDE</li></ul><h4>Let’s get started</h4><p>Start by creating a flutter app using the below command on your terminal.</p><pre>flutter create shoppinglist</pre><p>This will create a folder named shoppinglist in your current working directory which will contain the source code for your flutter application and will look something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*beDDSoQAXrKqElckOvzjrQ.png" /></figure><p>Open the directory as a project in your favorite IDE.</p><h4>Install Realm as a dependency</h4><p>Next, we will add realm as a dependency in our pubspec.yaml. This can be done using the below command</p><pre>flutter pub add realm</pre><p>Alternatively, you can open the pubspec.yaml file and add realm as a dependency:</p><pre>dependencies:<br>  # other dependecies here<br>  realm: ^0.2.1+alpha</pre><p>After adding the above, you need to run the below command:</p><pre>flutter pub get</pre><p>That’s it. Now you have everything you need to get started with Realm.</p><h4>Create a Schema</h4><p>Schema is the simplest unit in any Realm application. A schema defines the structure of data your application will be utilizing.</p><p>For example, an Item in our Shopping List can have two properties</p><ul><li>text: string</li><li>done: boolean</li></ul><p>To represent an Item in our application, we will create a Schema. To do that, create a directory named schemas in the lib directory. This directory will contain all the schemas used in the application.</p><p>Now create a file named item.dart with the below content.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ef3ebba5be1bddc514a39ca057242e3/href">https://medium.com/media/8ef3ebba5be1bddc514a39ca057242e3/href</a></iframe><blockquote>@RealmModel is an Annotation class used to define Realm data model classes and their properties.</blockquote><blockquote>@PrimaryKey Indicates a primary key property. enables quick lookup of objects and enforces uniqueness of the values. It can be</blockquote><blockquote>applied to a single property in a RealmModel class</blockquote><blockquote>either String or int</blockquote><h4>Generate Schema from the RealmModel class</h4><p>Now that we have our schema class defined, we need to generate the Realm schema. Realm schema is generated by combining the _Item and RealmObject classes. Realm has made this task simpler for us. All we need to do is to run the below command</p><pre>flutter pub run realm generate</pre><p>The above command will generate a new file item.g.dart containing a class Item.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d530d402f45188722510f7537338dec8/href">https://medium.com/media/d530d402f45188722510f7537338dec8/href</a></iframe><h4>Working with Realm</h4><p>Configure and Open a Realm</p><p>To work with Realm, we first need to define a Configuration object. The constructor takes in a list of Schemas you want the Realm to work with. Optionally, you can pass a readOnly and inMemory flags indicating you want the Realm to be opened in read-only mode or Realm to be loaded in memory.</p><pre>Configuration _config =<br>      Configuration([Item.schema], readOnly: false, inMemory: false);<br>Realm _realm = Realm(_config);</pre><p>Read all Items</p><pre>RealmResults&lt;Item&gt; items = _realm.all&lt;Item&gt;();</pre><p>Write/Update/Delete operations are done in a transaction block. To create a transaction block, use write() and provide a callback as a parameter. We perform the write/update/delete operation inside the callback.</p><p>Write an Item</p><pre>_realm.write(() {<br>    _realm.add&lt;Item&gt;(Item(text, false));<br>});</pre><p>Update an Item</p><pre>_realm.write(() {<br>    item.done = true;<br>});</pre><p>Delete an Item</p><pre>_realm.write(() {<br>    _realm.delete(item);<br>});</pre><p>Close a Realm</p><pre>if (!_realm.isClosed) {<br>    _realm.close();<br>}</pre><h4>Create a Service for Realm operations</h4><p>To manage our Realm, we will create a service class that will expose methods to open/close a realm and to perform query/update/delete operations on our Realm.</p><p>Create a directory services under lib directory. Add a new file item_service.dart with the following code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f784b405a358866217ad905ed029df73/href">https://medium.com/media/f784b405a358866217ad905ed029df73/href</a></iframe><p>Now that our core business logic is ready, we will move to build the UI components and screen.</p><h4>Create UI Components</h4><blockquote>Create a directory components in the lib directory. This directory will contain all the UI components used in our ShoppingList Application.</blockquote><p>ItemListView</p><p>ItemListView is essentially a ListView which renders a list of Items in our Shopping List. ItemListView component takes three required parameters:</p><ul><li>items - A list of Item objects</li><li>onToggle - A callback function to be invoked when an item is toggled</li><li>onDelete - A callback function to be invoked when an item is deleted</li></ul><p>Add a new file named item_list_view.dart in components directory with the below code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf4220569f260a75ebba716275aa2262/href">https://medium.com/media/cf4220569f260a75ebba716275aa2262/href</a></iframe><p>AddItemView</p><p>AddItemView is comprised of an Input Field and a Button. Users can enter an item in the Input Field and when they click the Button, a new item should be created.</p><p>AddItemView component takes one required parameter:</p><ul><li>onAdd - A callback function to be invoked when an item is added</li></ul><p>Add a new file named add_item_view.dart in components directory with the below code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c5ea03d9c34b079ee112e694f8c8402/href">https://medium.com/media/2c5ea03d9c34b079ee112e694f8c8402/href</a></iframe><p>ShoppingListView</p><p>ShoppingListView is composed of the previously created components ItemListView and AddItemView and presents an aggregated view where the user can add an item and view the List of existing Items.</p><p>ShoppingListView component takes four required parameters:</p><ul><li>onAdd - A callback function to be invoked when an item is added</li><li>onToggle - A callback function to be invoked when an item is toggled</li><li>onDelete - A callback function to be invoked when an item is deleted</li><li>items - A list of Item objects</li></ul><p>Add a new file named shopping_list_view.dart in components directory with the below code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f78d6012739d7a834cd8cbc5df161330/href">https://medium.com/media/f78d6012739d7a834cd8cbc5df161330/href</a></iframe><h4>Create the Home Screen</h4><p>Now that we have our UI components and Realm service ready, we can stitch them together on our Home Screen. On our home screen, we will render our main app with ShoppingList as a child. We will also create the callback functions onAdd, onToggle and onDelete and handle various Realm operations in these functions.</p><p>Open main.dart in lib directory and replace the existing code with the below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/427b506cb19cfcd3ab0b2aa5a26230d1/href">https://medium.com/media/427b506cb19cfcd3ab0b2aa5a26230d1/href</a></iframe><h4>Run Application</h4><p>That’s it. Our application is ready to be launched. Save all the code files.</p><p>To launch the flutter application, we will first launch the emulator. Let’s find the list of available emulators.</p><pre>flutter emulators</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/0*fQ3dR9dcjx9B1Klu.png" /></figure><p>Pick one of the emulator IDs from the above output and launch one using the below command:</p><pre>flutter emulators --launch Pixel4_API30</pre><p>After the emulator is launched, you can find its device-id using the below command:</p><pre>flutter devices</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TxjLfDZ8sjvp9hLo.png" /></figure><p>Copy the device-id (emulator-5554), and run the flutter app using the below command:</p><pre>flutter run -d emulator-5554</pre><blockquote>If you are not a big fan of commands, you can use your IDE to launch emulators and run Flutter applications.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/0*kted_CSzbtAJIgbe.png" /></figure><h4>Tips &amp; Further Resources</h4><p>Now that you have a Realm application running, you can continue adding more schemas or update existing schemas.</p><p>Whenever you make a change to a schema, you need to run the below command to generate RealmObjects based on your schema definition.</p><pre>flutter pub run realm generate</pre><p>You can run the above command with a watch option to generate/update RealmObjects as and when you update your schema.</p><pre>flutter pub run realm generate --watch</pre><p>Please note, that when you update your realm schema, you need to DELETE your current realm. To do that, simply execute the below code before opening your realm.</p><pre>Realm.deleteRealm(Configuration.defaultPath);</pre><p>The source code for this application is available <a href="https://github.com/markandeyp/flutter-shopping-list">here</a></p><p>Realm Flutter is currently in Alpha stage. Realm is a very powerful ecosystem and is much more than a simple offline data store for your application. The realm team at MongoDB is working really hard to make various Realm features like Realm Sync, Realm Authentication, Realm Functions etc. available to Flutter developers.</p><p>To explore further on MongoDB Realm, you can visit the official documentation <a href="https://www.mongodb.com/realm">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d4d00f8646f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/building-an-offline-app-with-mongodb-realm-8d4d00f8646f">Building an Offline Flutter App With MongoDB Realm</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>