<?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 Amit Singh on Medium]]></title>
        <description><![CDATA[Stories by Amit Singh on Medium]]></description>
        <link>https://medium.com/@amit08cse53?source=rss-9e35367d9e61------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*QyWujEb_xGzGLcjC.</url>
            <title>Stories by Amit Singh on Medium</title>
            <link>https://medium.com/@amit08cse53?source=rss-9e35367d9e61------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 12:28:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@amit08cse53/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[ The Pleasure of Waking Tall]]></title>
            <link>https://medium.com/@amit08cse53/the-pleasure-of-waking-tall-8a62efc6787e?source=rss-9e35367d9e61------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a62efc6787e</guid>
            <category><![CDATA[money-management]]></category>
            <category><![CDATA[healthy-lifestyle]]></category>
            <category><![CDATA[life]]></category>
            <category><![CDATA[work-life-balance]]></category>
            <category><![CDATA[developer]]></category>
            <dc:creator><![CDATA[Amit Singh]]></dc:creator>
            <pubDate>Tue, 15 Jul 2025 14:04:58 GMT</pubDate>
            <atom:updated>2025-07-15T14:04:58.482Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zFroB8sd1THAnbOG.png" /></figure><p><em>Not all victories are loud — some begin with how you stand before your day.</em></p><p>There’s something deeply powerful about waking tall. It’s not about posture; it’s about presence. It’s the subtle pleasure of rising with clarity — without anxiety, without guilt, without noise.</p><p>It’s the luxury of having options, earned not inherited. And that’s the kind of strength we build quietly — through discipline, consistency, and self-respect.</p><h3>🧭 Silent Wins Build Strong Systems</h3><p>As a developer, I often think in terms of clean architectures, S.O.L.I.D Principles and background tasks. The same applies to life — what runs silently is what powers everything else.</p><p>Consistent saving, small mindset upgrades, morning routines — they’re like background sync operations. You may not notice them in the moment, but they ensure the system of your life launches clean, without warnings or stack traces.</p><h3>💰 Money Talks — Quietly</h3><p>When finances are in order, your decisions become deliberate. Saying “no” to chaos doesn’t feel risky — it feels liberating. You’re not chasing — you’re choosing.</p><p>I remember walking away from a high-paying contract because the stress wasn’t worth the cost. It was possible only because I’d built a buffer — not just of money, but of clarity.</p><h3>⚙️ Developer’s Discipline, Human Ease</h3><p>Walking tall is like booting into a stable release:</p><ul><li>No memory leaks draining your energy</li><li>No race conditions between your priorities</li><li>Just clean execution of purpose</li></ul><p>My routines — whether syncing offline-first architecture or syncing my focus each morning — are designed for scalability. Because I believe growth should feel peaceful, not panicked.</p><h3>🔚 Before You Wake, You Prepare</h3><p>Waking tall is the result of what you optimized yesterday. So when the alarm rings, it’s not a disruption — it’s a deploy. To lead. To live. To walk like someone who’s already arrived.</p><h3>✨ Your Turn</h3><p>What habits help you rise with conviction? Share your thoughts below — or send this to someone who’s ready to code a better version of their life.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a62efc6787e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GraphQL and Node js — Part 2]]></title>
            <link>https://medium.com/@amit08cse53/graphql-and-node-js-part-2-1da0c1ee065f?source=rss-9e35367d9e61------2</link>
            <guid isPermaLink="false">https://medium.com/p/1da0c1ee065f</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[Amit Singh]]></dc:creator>
            <pubDate>Sun, 01 Jun 2025 17:45:26 GMT</pubDate>
            <atom:updated>2025-06-01T17:45:26.205Z</atom:updated>
            <content:encoded><![CDATA[<h3>GraphQL and Node js — Part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wTVfseSNI7epOj3O.png" /></figure><p><strong>Introduction</strong></p><p>Welcome back to our <strong>GraphQL</strong> journey! <strong>In part 2</strong>, we’re taking the next step by introducing authentication with <strong>GraphQL</strong> and showcasing the process of crafting order mutations. Let’s dive in!</p><p>As you saw in the first part we have a query for orders but to try that, first, we need to save our orders into the database. Let’s make the <strong>createOrder</strong> mutation:</p><pre>//Orders mutation<br>    createOrder: {<br>      type: GraphQLString,<br>      args: {<br>        userId: { type: GraphQLString },<br>        firstName: { type: GraphQLString },<br>        lastName: { type: GraphQLString },<br>        address: { type: GraphQLString },<br>        city: { type: GraphQLString },<br>        country: { type: GraphQLString },<br>        zipCode: { type: GraphQLString },<br>        totalAmount: { type: GraphQLFloat },<br>        items: { type: GraphQLString },<br>      },<br>      async resolve(parent, args, req) {<br>        console.log(args);<br>        const newOrder = new Order({<br>          userId: args.userId,<br>          firstName: args.firstName,<br>          lastName: args.lastName,<br>          address: args.address,<br>          city: args.city,<br>          country: args.country,<br>          zipCode: args.zipCode,<br>          totalAmount: args.totalAmount,<br>          items: args.items,<br>          createdDate: new Date().toLocaleDateString(),<br>        });</pre><pre>        await newOrder.save();<br>        const data = {<br>          message: &quot;success&quot;,<br>        };</pre><pre>        return JSON.stringify(data);<br>      },<br>    },</pre><p>Note! Here in the items field we expect a<strong> stringify array</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*53hla9TFHLp72u4a.png" /></figure><p>Here as you see we get back the message that we defined in our mutation but you can retrieve any order attributes.</p><p>To generate a password hash, we must first install the <strong>bcrypt</strong> library. Hashing the password is a crucial method for securely storing passwords in the database, effectively preventing unauthorized individuals from accessing the actual password and adding an extra layer of security.</p><pre>npm install bcrypt</pre><p>Now let’s create the user mutations. Add the following code under the other mutations:</p><pre>//don&#39;t forget to import the bcrypt package<br>const bcrypt = require(&quot;bcrypt&quot;)<br></pre><pre>//Users mutations<br>    createUser: {<br>      type: GraphQLString,<br>      args: {<br>        username: { type: GraphQLString },<br>        email: { type: GraphQLString },<br>        password: { type: GraphQLString },<br>        isAdmin: { type: graphql.GraphQLBoolean },<br>      },<br>      async resolve(parent, args) {<br>        console.log(args);<br>        const newUser = new User({<br>          username: args.username,<br>          email: args.email,<br>          password: args.password,<br>          isAdmin: args.isAdmin,<br>        });</pre><pre>        const user = await User.findOne({ email: newUser.email });<br>        if (user) {<br>          throw new Error(&quot;Already in db&quot;);<br>        }</pre><pre>        const salt = await bcrypt.genSalt(10);<br>        newUser.password = await bcrypt.hash(newUser.password, salt);</pre><pre>        await newUser.save();<br>        const token = newUser.generateAuthToken();</pre><pre>        const data = {<br>          token: token,<br>          id: newUser.id,<br>          isAdmin: newUser.isAdmin,<br>        };<br>        return JSON.stringify(data);<br>      },<br>    },</pre><pre>    loginUser: {<br>      type: GraphQLString,<br>      args: {<br>        email: { type: GraphQLString },<br>        password: { type: GraphQLString },<br>      },<br>      async resolve(parent, args) {<br>        const user = await User.findOne({ email: args.email });<br>        if (!user) {<br>          throw new Error(&quot;Not user with that email&quot;);<br>        }<br>        const validPassword = await bcrypt.compare(<br>          args.password,<br>          user.password<br>        );</pre><pre>        if (!validPassword) {<br>          throw new Error(&quot;Invalid password&quot;);<br>        }<br>        const token = user.generateAuthToken();<br>        const data = {<br>          token: token,<br>          userId: user.id,<br>          isAdmin: user.isAdmin,<br>        };<br>        return JSON.stringify(data);<br>      },<br>    },</pre><p><strong>1. createUser Mutation</strong>:</p><ul><li>This mutation is used for creating a new user in your application.</li><li>It accepts several input arguments, including <strong>username</strong>, <strong>email</strong>, <strong>password</strong>, and <strong>isAdmin</strong>.</li><li>In the <strong>resolve</strong> function, a new user object is created based on the provided arguments.</li><li>It checks if a user with the same email already exists in the database. If one is found, it throws an error.</li><li>It generates a random <strong>“salt”</strong> and uses it to hash the user’s password for security.</li><li>The new user is then saved to the database, and an authentication token is generated for the user.</li><li>The result of this mutation is a JSON string containing the authentication token, user ID, and isAdmin status.</li></ul><p><strong>2. loginUser Mutation</strong>:</p><ul><li>This mutation is used for authenticating and logging in a user.</li><li>It takes <strong>email</strong> and <strong>password</strong> as input arguments.</li><li>In the <strong>resolve</strong> function, it searches for a user with the provided email in the database. If no user is found, it throws an error.</li><li>It then checks if the provided password matches the stored hashed password using <strong>bcrypt.compare</strong>. If the password is invalid, it throws an error.</li><li>If the user is successfully authenticated, an authentication token is generated for the user.</li><li>The result of this mutation is a JSON string containing the authentication token, user ID, and isAdmin status.</li></ul><p>These mutations are fundamental for user registration and login, ensuring the secure storage and validation of user credentials. The generated authentication tokens can be used to authorize and authenticate users in your application.</p><p>But before using these methods we need to little bit modify our user models. First, install the<strong> jsonwebtoken</strong> library.</p><pre>npm i jsonwebtoken</pre><p>The <strong>jsonwebtoken</strong> npm package is a library for creating and verifying JSON Web Tokens (JWT). JWTs are a compact, self-contained way to represent information between parties securely. They are often used for user authentication and authorization in web applications. With <strong>jsonwebtoken</strong>, you can create JWTs that encode user data and claims, and verify them to ensure their authenticity and integrity. This package is commonly used for implementing user authentication and authorization in web applications.</p><p>Let’t add this function for the user model:</p><pre>userSchema.methods.generateAuthToken = function () {<br>  const token = jwt.sign(<br>    { _id: this._id, isAdmin: this.isAdmin },<br>    &quot;jwtPrivateKey&quot; <br>  );<br>  return token;<br>};</pre><p><strong>1. userSchema.methods.generateAuthToken = function () {</strong></p><ul><li>This function is added to the <strong>userSchema</strong> as a method, which means it can be called on a user instance.</li></ul><p><strong>2. const token = jwt.sign( { _id: this._id, isAdmin: this.isAdmin }, &quot;jwtPrivateKey&quot;);</strong></p><ul><li>It uses the <strong>jwt.sign</strong> method from the <strong>jsonwebtoken</strong> library to create a JWT.</li><li>The first argument to <strong>jwt.sign</strong> is an object containing the data you want to include in the token. In this case, it typically includes the user&#39;s ID (<strong>_id</strong>) and their admin status (<strong>isAdmin</strong>).</li><li>The second argument is a secret key, usually referred to as a “JWT secret.” It should be stored securely and kept secret, typically in an environment variable. It’s important to use a strong, complex key for security.</li></ul><p><strong>3. return token;</strong></p><ul><li>Finally, the function returns the generated token, which can be used for authenticating and authorizing the user. The token contains the user’s data and a digital signature to verify its authenticity.</li></ul><p>We defined the functions so now we can try the <strong>createUser</strong> mutation which is the sign-up function.</p><pre>mutation{<br>  createUser(username:&quot;testUsername&quot;, <br>             email:&quot;test@gmail.com&quot;, <br>             password: &quot;testPassword&quot;, <br>             isAdmin: false)<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wPx8wVuF0x28GCzJ.png" /></figure><p>Voilà! We’ve obtained the token, user ID, and the isAdmin field.</p><p>Next, let’s test the <strong>loginUser</strong> mutation:</p><pre>mutation{<br>  loginUser( email:&quot;test@gmail.com&quot;, password: &quot;testPassword&quot;)<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9-Tneyq2UXNCh6di.png" /></figure><p>And we receive the same data as in the<strong> signIn </strong>method. Our final step is to create the authentication middleware, which can be used to secure our mutations and queries.</p><p>To do this, let’s create a folder named<strong> “middleware”</strong> and add a file called <strong>“auth.js”</strong></p><pre>const jwt = require(&quot;jsonwebtoken&quot;);<br>const config = require(&quot;config&quot;);</pre><pre>function isAuth(req, res, next) {<br>  const authHeader = req.get(&quot;Authorization&quot;);<br>  if (!authHeader) {<br>    req.isAuth = false;<br>    return next();<br>  }</pre><pre>  const token = authHeader.split(&quot; &quot;)[1];<br>  if (!token || token === &quot;&quot;) {<br>    {<br>      req.isAuth = false;<br>      return next();<br>    }<br>  }</pre><pre>  try {<br>    const decoded = jwt.verify(token, config.get(&quot;jwtPrivateKey&quot;));<br>    req.user = decoded;<br>    req.isAuth = true;<br>    next();<br>  } catch (ex) {<br>    req.isAuth = false;<br>    next();<br>  }<br>}</pre><pre>module.exports = isAuth;</pre><ul><li>When a request arrives, the <strong>isAuth</strong> function first attempts to retrieve the &quot;Authorization&quot; header from the request. This header often contains a JSON Web Token (JWT) that verifies a user&#39;s identity.</li><li>If there’s no “Authorization” header, it means the user is not authenticated. In this case, the <strong>req.isAuth</strong> property is set to <strong>false</strong>, and the request is allowed to continue through the subsequent middleware or route handlers without authentication.</li><li>If an “Authorization” header exists, the function extracts the JWT from the header, typically in the format “Bearer &lt;token&gt;”. It checks if the token exists and is not empty.</li><li>If no valid token is found, or if the token is empty, the user is considered unauthenticated. The <strong>req.isAuth</strong> property is set to <strong>false</strong>, and the request continues without authentication.</li><li>If a valid token is present, the function proceeds to verify the token’s authenticity using <strong>jwt.verify</strong>. This method checks the token&#39;s validity and ensures it hasn&#39;t been tampered with.</li><li>If the token is successfully verified, it is decoded to access user-related data, such as the user’s ID and potentially other information. This data is attached to the <strong>req</strong> object, making it available for use in subsequent parts of the application.</li><li>The <strong>req.isAuth</strong> property is set to <strong>true</strong>, indicating that the user is authenticated.</li><li>Regardless of whether the token verification succeeds or not, the middleware always calls <strong>next()</strong> to allow the request to continue processing through subsequent middleware or reach the designated route handler.</li><li>If there’s an error during token verification, such as an invalid or expired token, the middleware catches the exception. In this case, the user is considered unauthenticated (req.isAuth = false), and the request continues to be processed.</li></ul><p>In essence, this middleware ensures that incoming requests are checked for valid JWTs, and authenticated users can access protected resources while unauthenticated users can proceed without authentication.</p><p>Add the middleware function to our <strong>main index.js</strong> file:</p><pre>const isAuth = require(&quot;./middleware/auth&quot;);<br>...<br>//before our endpoint<br>app.use(isAuth);</pre><p>See it in action. If you want to secure your <strong>“getAllProduct”</strong> query, you can add the following line (Note: It’s important to add the <strong>“req”</strong> attribute to the resolve function):</p><pre>getAllProduct: {<br>      type: new GraphQLList(ProductType), <br>      args: { id: { type: GraphQLString } },<br>      async resolve(parent, args ,req) {<br>        <br>    if (!req.isAuth) {<br>          throw new Error(&quot;Unauthenticated&quot;);<br>        }<br>       <br>        const productList = await Product.find();<br>        return productList;<br>      },<br>    },</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zv6L8RjmKH9HBWkh.png" /></figure><p>Here’s what we’ve learned:</p><ol><li><strong>GraphQL</strong>: We’ve delved into GraphQL, a powerful query language and runtime for APIs, understanding how it enables efficient data retrieval and modification by allowing clients to request precisely what they need.</li><li><strong>User Authentication</strong>: We’ve implemented user authentication, a fundamental aspect of web applications, using JSON Web Tokens (JWTs). We’ve seen how to create, verify, and use JWTs to authenticate and authorize users securely.</li><li><strong>Database Interaction</strong>: We’ve interacted with databases, including MongoDB, for storing and retrieving data. We’ve learned how to create, update, and delete data using GraphQL mutations.</li><li><strong>Middleware</strong>: We’ve explored the concept of middleware in Node.js, understanding how it allows us to execute code during the request-response cycle, enabling tasks like authentication and data processing.</li><li><strong>Security Best Practices</strong>: We’ve emphasized the importance of security best practices, such as hashing user passwords and keeping sensitive information, like JWT secrets, confidential and securely stored.</li></ol><p>Thank you for reading this brief tutorial on connecting <strong>Node.js</strong> and <strong>GraphQL</strong>. I hope you found it enjoyable and insightful. If you have any questions or find anything confusing, you can refer to the <a href="https://github.com/amit08cse53/grapqldemo"><strong>GitHub repository here</strong>.</a></p><p><strong>See you soon!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1da0c1ee065f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GraphQL and Node js — Part 1]]></title>
            <link>https://medium.com/@amit08cse53/graphql-and-node-js-part-1-b0b60101eb9d?source=rss-9e35367d9e61------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0b60101eb9d</guid>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Amit Singh]]></dc:creator>
            <pubDate>Sun, 01 Jun 2025 17:44:43 GMT</pubDate>
            <atom:updated>2025-06-01T17:44:43.201Z</atom:updated>
            <content:encoded><![CDATA[<h3>GraphQL and Node js — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_tzR5vl2_9IZ56d-.png" /></figure><p><strong>Introduction</strong></p><p><strong>GraphQL </strong>and <strong>Node.js </strong>make a dynamic duo in modern web development. GraphQL is a query language for your API, while Node.js is a robust runtime environment for server-side applications. When combined, they empower developers to create efficient, flexible, and real-time communication between clients and servers.</p><p>The <strong>advantage of using GraphQL</strong> with Node.js lies in its ability to provide a single endpoint for clients to request precisely the data they need, minimizing over-fetching and under-fetching of information. This seamless synergy enables developers to build powerful, customizable APIs and simplifies data communication by allowing clients to specify their data requirements through queries and mutations, ensuring a more efficient and responsive backend experience.</p><p>Only one endpoint! Sounds cool, right? So why wait any longer? Let’s start developing!</p><p>First, we create the base node app with the following command:</p><pre>npm init</pre><p>After we initialized our starting app, let’s install the necessary node packages:</p><pre>npm install express</pre><p>Express module is a web application framework that simplifies the process of building web servers and APIs. It offers a wide range of features, including routing, middleware support, and a straightforward API for handling HTTP requests and responses. Express is known for its flexibility, allowing developers to create both simple single-page applications and complex, enterprise-grade projects with ease.</p><p>Let’s create our app in the index.js:</p><pre>const express = require(&quot;express&quot;);<br>const app = express();<br>const PORT = 5000;</pre><pre>app.listen(PORT, () =&gt; {<br>  console.log(&quot;Server running&quot;);<br>});</pre><p>To run our app just type <strong>node index.js</strong> and our application is running on <strong>http//:localhost:5000/</strong></p><p>Now we install the other necessary libraries and along the way you would see what these packages doing.</p><p>We will work with Mongo DB so if you not have installed on your machine then follow the instructions from here:</p><p><a href="https://www.mongodb.com/docs/manual/installation/">https://www.mongodb.com/docs/manual/installation/</a> .</p><p>After you have installed on your machine then install the mongoose package with we can interact between the node js and the database.</p><pre>npm install mongoose</pre><p>MongoDB is a popular NoSQL database management system known for its flexibility and scalability. It stores data in a document-oriented format, using BSON (Binary JSON). It is widely used in web and mobile applications, offering developers the ability to work with data in a more dynamic and agile manner compared to traditional relational databases. Our first task is to create a connection between our application and the database.</p><p>Edit the <strong>index.js</strong>:</p><pre>const express = require(&quot;express&quot;);<br>const app = express();<br>const mongoose = require(&quot;mongoose&quot;);<br>const PORT = 5000;</pre><pre>mongoose<br>  .connect(&quot;mongodb://127.0.0.1/{Your db collection name}&quot;)<br>  .then(() =&gt; console.log(&quot;Connected to MongoDB...&quot;))<br>  .catch((err) =&gt; console.error(&quot;Could not connect to MongoDB...&quot;));</pre><pre>app.listen(PORT, () =&gt; {<br>  console.log(&quot;Server running&quot;);<br>});</pre><p>So after we have the initial app and we connected to a db we can kick off our journey with GraphQL. Let’s install the necessary packages:</p><pre>npm install express-graphql graphql</pre><p><strong>Express-GraphQL</strong> is a middleware package for Node.js and <strong>Express.js </strong>that simplifies the process of creating a GraphQL API. It provides an easy way to expose a GraphQL endpoint in an Express application.</p><p><strong>Key Features</strong></p><ul><li><strong>Middleware Integration</strong>: Express-GraphQL seamlessly integrates with Express.js, making it a popular choice for adding GraphQL functionality to existing Express applications.</li><li><strong>Schema Definition</strong>: You can define your GraphQL schema using the GraphQL.js schema language, and Express-GraphQL helps in routing requests to the appropriate schema.</li><li><strong>Data Resolution</strong>: It allows you to define resolvers that specify how to fetch data from your data sources, whether it’s a database or other APIs.</li><li><strong>Query Validation</strong>: Express-GraphQL automatically validates and executes GraphQL queries and provides detailed error messages.</li></ul><p>GraphQL is a query language and runtime for APIs. It was developed by Facebook and is designed to provide a more efficient, powerful, and flexible alternative to the traditional REST API.</p><p><strong>Key Features</strong></p><ul><li><strong>Client-Defined Queries</strong>: With GraphQL, clients can request exactly the data they need, avoiding over-fetching or under-fetching of data, which is common in REST.</li><li><strong>Strongly Typed</strong>: GraphQL APIs are strongly typed. You define the types, queries, and mutations, which helps in catching errors early.</li><li><strong>Single Endpoint</strong>: GraphQL typically has a single endpoint for all requests, making it efficient and reducing the number of network requests.</li><li><strong>Real-time Data</strong>: GraphQL supports real-time data using subscriptions, enabling features like live updates and chat functionality.</li><li><strong>Introspection</strong>: You can introspect a GraphQL schema to understand its capabilities and structure.</li></ul><p>For the better project organization create a folder Schema, inside this folder, we create a folder for our model types and an index.js for the routes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/0*KTRfByO4kIdcGULR.png" /></figure><p>Type definitions</p><p>As you can see here, we have 3 types and 3 models in our database. Let’s create another folder for the database models:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/0*2H-ubzpKlkxa9bEd.png" /></figure><p>Models</p><p>In the <strong>orders</strong>, we create our <strong>order model</strong>:</p><pre>const mongoose = require(&quot;mongoose&quot;);</pre><pre>const orderSchema = new mongoose.Schema({<br>  userId: {<br>    type: String,<br>    required: true,<br>  },<br>  firstName: {<br>    type: String,<br>    required: true,<br>  },<br>  lastName: {<br>    type: String,<br>    required: true,<br>  },<br>  address: {<br>    type: String,<br>    required: true,<br>  },<br>  city: {<br>    type: String,<br>    required: true,<br>  },<br>  country: {<br>    type: String,<br>    required: true,<br>  },<br>  zipCode: {<br>    type: String,<br>    required: true,<br>  },<br>  totalAmount: {<br>    type: Number,<br>    required: true,<br>  },<br>  items: {<br>    type: String,<br>    required: true,<br>  },<br>  createdDate: {<br>    type: String,<br>    required: true,<br>  },<br>});</pre><pre>const Order = mongoose.model(&quot;Order&quot;, orderSchema);</pre><pre>exports.Order = Order;</pre><p>Create the <strong>product model</strong>:</p><pre>const mongoose = require(&quot;mongoose&quot;);</pre><pre>const productSchema = new mongoose.Schema({<br>  title: {<br>    type: String,<br>    required: true,<br>  },<br>  description: {<br>    type: String,<br>    required: true,<br>  },<br>  price: {<br>    type: Number,<br>    required: true,<br>  },<br>  discountPercentage: {<br>    type: Number,<br>    required: true,<br>  },<br>  rating: {<br>    type: Number,<br>    required: true,<br>  },<br>  stock: {<br>    type: Number,<br>    required: true,<br>  },<br>  brand: {<br>    type: String,<br>    required: true,<br>  },<br>  category: {<br>    type: String,<br>    required: true,<br>  },<br>  thumbnail: {<br>    type: String,<br>    required: true,<br>  },<br>  images: {<br>    type: String,<br>    required: true,<br>  },<br>});</pre><pre>const Product = mongoose.model(&quot;Product&quot;, productSchema);</pre><pre>exports.Product = Product;</pre><p>And finally our <strong>user model</strong>:</p><pre>const mongoose = require(&quot;mongoose&quot;);</pre><pre>const userSchema = new mongoose.Schema({<br>  username: {<br>    type: String,<br>    required: true,<br>    unique: true,<br>    minlength: 5,<br>    maxlength: 50,<br>  },<br>  email: {<br>    type: String,<br>    required: true,<br>    unique: true,<br>    minlength: 5,<br>    maxlength: 225,<br>  },<br>  password: {<br>    type: String,<br>    required: true,<br>    unique: true,<br>    minlength: 5,<br>    maxlength: 1024,<br>  },<br>  isAdmin: {<br>    type: Boolean,<br>    default: false,<br>  },<br>});</pre><pre>const User = mongoose.model(&quot;User&quot;, userSchema);</pre><pre>exports.User = User;</pre><p>These models are MongoDB models that we’ll be using to save and retrieve information from the database. In the context of a Node.js application, MongoDB models represent the structure of the data you want to store in your database. They define the schema and behavior of the data, making it easier to interact with the MongoDB database. By defining models, you can enforce a specific structure for your data and perform operations like inserts, updates, and queries efficiently. This not only simplifies the interaction with the database but also enhances code organization and maintainability, making MongoDB models a fundamental part of your application’s data layer.</p><p>Now we have the models we can create the <strong>OrderType</strong>:</p><pre>const graphql = require(&quot;graphql&quot;);<br>const {<br>  GraphQLObjectType,<br>  GraphQLInt,<br>  GraphQLString,<br>  GraphQLFloat,<br>  GraphQLList,<br>} = graphql;</pre><pre>const OrderType = new GraphQLObjectType({<br>  name: &quot;Order&quot;,<br>  fields: () =&gt; ({<br>    id: { type: GraphQLString },<br>    userId: { type: GraphQLString },<br>    firstName: { type: GraphQLString },<br>    lastName: { type: GraphQLString },<br>    address: { type: GraphQLString },<br>    city: { type: GraphQLString },<br>    country: { type: GraphQLString },<br>    zipCode: { type: GraphQLString },<br>    totalAmount: { type: GraphQLFloat },<br>    items: { type: GraphQLString },<br>    createdDate: { type: GraphQLString },<br>  }),<br>});</pre><pre>module.exports = OrderType;</pre><p>In <strong>GraphQL</strong>, a type definition like the one you provided represents the structure of data that can be queried or manipulated. Let me explain it in simpler terms:</p><p>Imagine you have an online store, and you want to retrieve information about orders placed by customers. You’d define an <strong>“OrderType”</strong> using GraphQL to specify what kind of data you can request about an order.</p><p>Here’s a breakdown of the code you provided:</p><ol><li>You import the necessary modules from the <strong>“graphql”</strong> package.</li><li>You define the <strong>“OrderType”</strong> using the <strong>“GraphQLObjectType”</strong> constructor. This is where you describe the structure of an order.</li></ol><ul><li><strong>“name”</strong> is a label for this type, in this case, <strong>“Order”.</strong></li><li><strong>“fields”</strong> is a function that returns an object. This object describes the properties (fields) of an order, and each field is associated with a specific data type.</li></ul><p>3. Inside the <strong>“fields”</strong> object, you define various properties that an order can have:</p><ul><li><strong>“id,” “userId,” “firstName,” “lastName,”</strong> and so on are fields that describe different aspects of an order.</li><li><strong>“type”</strong> specifies the data type for each field. For example, <strong>“id”</strong> and <strong>“userId”</strong> are of type <strong>“GraphQLString,” </strong>which means they hold text data.</li><li><strong>“totalAmount”</strong> is of type <strong>“GraphQLFloat,”</strong> indicating it holds numeric data.</li><li><strong>“items” </strong>is also of type <strong>“GraphQLString,”</strong> but this might represent a serialized list of items, like a JSON string.</li></ul><p>4. Finally, you export the <strong>“OrderType”</strong> so that you can use it in your <strong>GraphQL schema</strong> to define the structure of your data.</p><p>In summary, the <strong>“OrderType”</strong> is a blueprint that defines the structure of an order in your online store’s data. When a GraphQL query is made, it specifies which fields (properties) of an order should be included in the response. This makes it very flexible for clients to request only the data they need, and the <strong>“OrderType”</strong> helps ensure that the data conforms to a specific structure.</p><p>We do the same for the <strong>product</strong>:</p><pre>const graphql = require(&quot;graphql&quot;);<br>const { GraphQLObjectType, GraphQLInt, GraphQLString, GraphQLFloat } = graphql;</pre><pre>const ProductType = new GraphQLObjectType({<br>  name: &quot;Product&quot;,<br>  fields: () =&gt; ({<br>    id: { type: GraphQLString },<br>    brand: { type: GraphQLString },<br>    category: { type: GraphQLString },<br>    description: { type: GraphQLString },<br>    discountPercentage: { type: GraphQLFloat },<br>    images: { type: GraphQLString },<br>    price: { type: GraphQLFloat },<br>    rating: { type: GraphQLFloat },<br>    stock: { type: GraphQLInt },<br>    thumbnail: { type: GraphQLString },<br>    title: { type: GraphQLString },<br>  }),<br>});</pre><pre>module.exports = ProductType;</pre><p>And also for the <strong>users</strong>:</p><pre>const graphql = require(&quot;graphql&quot;);<br>const { GraphQLObjectType, GraphQLInt, GraphQLString, GraphQLFloat } = graphql;</pre><pre>const UserType = new GraphQLObjectType({<br>  name: &quot;User&quot;,<br>  fields: () =&gt; ({<br>    id: { type: GraphQLString },<br>    username: { type: GraphQLString },<br>    email: { type: GraphQLString },<br>    password: { type: GraphQLString },<br>    isAdmin: { type: graphql.GraphQLBoolean },<br>  }),<br>});</pre><pre>module.exports = UserType;</pre><p>Once we have defined our GraphQL types, we can proceed to define our queries and mutations. GraphQL queries serve the purpose of retrieving data, enabling clients to request precisely the information they require. Conversely, mutations are employed to alter server data, providing a reliable and secure means of executing write operations.</p><p>Let’s write the code into<strong> index.js:</strong></p><pre>// Import necessary GraphQL modules and dependencies.<br>const graphql = require(&quot;graphql&quot;);<br>const {<br>  GraphQLSchema,<br>  GraphQLObjectType,<br>  GraphQLInt,<br>  GraphQLString,<br>  GraphQLFloat,<br>  GraphQLList,<br>} = graphql;</pre><pre>// Import data models for products and orders.<br>const { Product } = require(&quot;../models/products&quot;);<br>const { Order } = require(&quot;../models/orders&quot;);</pre><pre>// Import user-defined data types for GraphQL.<br>const ProductType = require(&quot;./TypeDefs/ProductType&quot;);<br>const UserType = require(&quot;./TypeDefs/UserType&quot;);<br>const OrderType = require(&quot;./TypeDefs/OrderType&quot;);</pre><pre>// Define the RootQuery, which is the entry point for querying data.<br>const RootQuery = new GraphQLObjectType({<br>  name: &quot;RootQueryType&quot;,<br>  fields: {<br>    // Products Queries<br>    getAllProduct: {<br>      type: new GraphQLList(ProductType), // Define the type of data to be returned (a list of products).<br>      args: { id: { type: GraphQLString } }, // Specify any input arguments that can be used in the query (in this case, an &#39;id&#39;).<br>      async resolve(parent, args) {<br>        // The &#39;resolve&#39; function specifies how to fetch and return the requested data.<br>        // In this case, it fetches and returns a list of all products.<br>        const productList = await Product.find();<br>        return productList;<br>      },<br>    },<br>    getProduct: {<br>      type: ProductType, // Define the type of data to be returned (a single product).<br>      args: { id: { type: GraphQLString } }, // Specify an input argument &#39;id&#39;.<br>      async resolve(parent, args) {<br>        // The &#39;resolve&#39; function fetches and returns a specific product based on the provided &#39;id&#39;.<br>        const product = await Product.findById(args.id);<br>        return product;<br>      },<br>    },</pre><pre>    // Orders Queries<br>    getAllOrders: {<br>      type: new GraphQLList(OrderType), // Define the type of data to be returned (a list of orders).<br>      args: { id: { type: GraphQLString } }, // Specify an input argument &#39;id&#39;.<br>      async resolve(parent, args, req) {<br>        // The &#39;resolve&#39; function fetches and returns a list of orders for a specific user, but only if the user is authenticated.<br>        if (!req.isAuth) {<br>          throw new Error(&quot;Unauthenticated&quot;);<br>        }<br>        const orderList = await Order.find({ userId: args.id });<br>        return orderList;<br>      },<br>    },<br>  },<br>});</pre><pre>// Export a GraphQLSchema that includes the RootQuery.<br>module.exports = new GraphQLSchema({<br>  query: RootQuery,<br>});</pre><p><strong>Root Queries</strong>:</p><ul><li>The <strong>RootQuery</strong> is the entry point for querying data. It&#39;s like the main menu of options you have when you want to retrieve information.</li><li>In this code, we have defined several queries for retrieving data, such as <strong>getAllProduct</strong>, <strong>getProduct</strong>, and <strong>getAllOrders</strong>. These queries specify what data we can request.</li></ul><p><strong>Fields</strong>:</p><ul><li>Within the <strong>RootQuery</strong>, each query is defined as a &quot;field.&quot; For example, <strong>getAllProduct</strong>, <strong>getProduct</strong>, and <strong>getAllOrders</strong> are fields.</li><li>These fields specify the types of data they return and any input arguments they accept.</li></ul><p><strong>Types</strong>:</p><ul><li>GraphQL is strongly typed. Each query and the data it returns are defined by types. For example, <strong>ProductType</strong> and <strong>OrderType</strong> describe the structure of products and orders.</li></ul><p><strong>Resolvers</strong>:</p><ul><li>The <strong>resolve</strong> functions are responsible for fetching and returning the actual data when a query is executed. They determine how to retrieve the requested information from a database or other data source.</li></ul><p><strong>Input Arguments</strong>:</p><ul><li>Queries can accept input arguments to customize the results. For example, you can use the <strong>id</strong> argument to specify which product or order you want to retrieve.</li></ul><p>Now we created the schemas and our root queries let’s add our endpoint in the <strong>index.js:</strong></p><pre>const express = require(&quot;express&quot;);<br>const app = express();<br>const mongoose = require(&quot;mongoose&quot;);<br>const PORT = 5000;<br>const { graphqlHTTP } = require(&quot;express-graphql&quot;);<br>const schema = require(&quot;./Schemas&quot;);</pre><pre>mongoose<br>  .connect(&quot;mongodb://127.0.0.1/{Your db collection name}&quot;)<br>  .then(() =&gt; console.log(&quot;Connected to MongoDB...&quot;))<br>  .catch((err) =&gt; console.error(&quot;Could not connect to MongoDB...&quot;));</pre><pre>app.use(<br>  &quot;/graphql&quot;,<br>  graphqlHTTP({<br>    schema,<br>    graphiql: true,<br>  })<br>);</pre><pre>app.listen(PORT, () =&gt; {<br>  console.log(&quot;Server running&quot;);<br>});</pre><p>Having defined our queries, the next step is to interact with our database by adding, updating, or deleting data. In GraphQL, this task is addressed using mutations. Mutations provide a mechanism to modify the data within the server. They allow clients to create, edit, or remove records while ensuring a consistent and controlled way to perform write operations.</p><p>Let’s back to <strong>index.js</strong> where we defined the queries and add some mutations:</p><pre>...<br>const Mutation = new GraphQLObjectType({<br>  name: &quot;Mutation&quot;,<br>  fields: {<br>    //Product mutations<br>    createProduct: {<br>      type: ProductType,<br>      args: {<br>        brand: { type: GraphQLString },<br>        category: { type: GraphQLString },<br>        description: { type: GraphQLString },<br>        discountPercentage: { type: GraphQLFloat },<br>        images: { type: GraphQLString },<br>        price: { type: GraphQLFloat },<br>        rating: { type: GraphQLFloat },<br>        stock: { type: GraphQLInt },<br>        thumbnail: { type: GraphQLString },<br>        title: { type: GraphQLString },<br>      },<br>      async resolve(parent, args, req) {<br>        const newProduct = new Product({<br>          title: args.title,<br>          brand: args.brand,<br>          category: args.category,<br>          description: args.description,<br>          discountPercentage: args.discountPercentage,<br>          images: args.images,<br>          price: args.price,<br>          rating: args.rating,<br>          stock: args.stock,<br>          thumbnail: args.thumbnail,<br>        });</pre><pre>        await newProduct.save();</pre><pre>        return newProduct;;<br>      },<br>    },</pre><pre>    updateProduct: {<br>      type: ProductType,<br>      args: {<br>        id: { type: GraphQLString },<br>        brand: { type: GraphQLString },<br>        category: { type: GraphQLString },<br>        description: { type: GraphQLString },<br>        discountPercentage: { type: GraphQLFloat },<br>        images: { type: GraphQLString },<br>        price: { type: GraphQLFloat },<br>        rating: { type: GraphQLFloat },<br>        stock: { type: GraphQLInt },<br>        thumbnail: { type: GraphQLString },<br>        title: { type: GraphQLString },<br>      },<br>      async resolve(parent, args, req) {<br>        const newProduct = await Product.findByIdAndUpdate(args.id, {<br>          brand: args.brand,<br>          category: args.category,<br>          description: args.description,<br>          discountPercentage: args.discountPercentage,<br>          images: args.images,<br>          price: args.price,<br>          rating: args.rating,<br>          stock: args.stock,<br>          thumbnail: args.thumbnail,<br>          title: args.title,<br>        });</pre><pre>        return newProduct;<br>      },<br>    },</pre><pre>    deleteProduct: {<br>      type: ProductType,<br>      args: {<br>        id: { type: GraphQLString },<br>      },<br>      async resolve(parent, args) {<br>        console.log(args.id);</pre><pre>        const deletedProduct = await Product.findByIdAndDelete(args.id);</pre><pre>        return args;<br>      },<br>    },<br>    <br>}});</pre><pre>module.exports = new GraphQLSchema({<br>  query: RootQuery,<br>  mutation: Mutation, //add mutations here<br>});</pre><ol><li><strong>Create Product Mutation</strong>:</li></ol><ul><li>The <strong>createProduct</strong> mutation allows you to add a new product to the database.</li><li>It accepts various product details as arguments, such as brand, category, description, and price.</li><li>It creates a new product using the provided arguments and saves it to the database.</li><li>Finally, it returns the details of the newly created product.</li></ul><p><strong>2. Update Product Mutation</strong>:</p><ul><li>The <strong>updateProduct</strong> mutation is used to modify an existing product in the database.</li><li>It takes the product’s ID along with various details (e.g., brand, category, and price) as arguments.</li><li>It finds the existing product by its ID and updates its details with the provided arguments.</li><li>The updated product details are then returned.</li></ul><p><strong>3. Delete Product Mutation</strong>:</p><ul><li>The <strong>deleteProduct</strong> mutation is designed to remove a product from the database.</li><li>It requires the product’s ID as an argument.</li><li>It deletes the product with the specified ID from the database.</li><li>The mutation returns the ID of the deleted product.</li></ul><p>Now that we have everything set up for interacting with GraphQL, it’s fortunate that GraphQL provides an excellent interface called GraphiQL. By visiting the <a href="http://localhost:5000/graphql">http://localhost:5000/graphql</a> endpoint, you can easily explore and interact with your data. Here are some cool features of GraphiQL.</p><p>You can learn more from here: <a href="https://www.gatsbyjs.com/docs/how-to/querying-data/running-queries-with-graphiql/">https://www.gatsbyjs.com/docs/how-to/querying-data/running-queries-with-graphiql/</a></p><p><strong>GraphiQL Features</strong>:</p><ol><li><strong>Interactive Interface</strong>: GraphiQL provides a web-based, interactive environment where you can compose and send GraphQL queries and mutations.</li><li><strong>Auto-Complete and Documentation</strong>: It offers auto-complete suggestions for query and mutation fields and displays documentation about your GraphQL schema, making it easy to explore the available data and operations.</li><li><strong>History and Presets</strong>: You can save and reuse previous queries and share them with your team. It’s a handy feature for iterative development.</li><li><strong>Real-Time Validation</strong>: GraphiQL provides instant feedback on query and mutation syntax errors, helping you avoid common mistakes.</li><li><strong>Responsive and Customizable</strong>: The interface is responsive, works well on various screen sizes, and can be customized to suit your needs.</li></ol><p>Let’s first add some data into our database:</p><ol><li><strong>Creating a New Product:</strong></li></ol><pre>mutation {<br>  createProduct(<br>    title: &quot;First Product&quot;,<br>    brand: &quot;Example Brand&quot;,<br>    category: &quot;Electronics&quot;,<br>    description: &quot;A new product description.&quot;,<br>    discountPercentage: 5,<br>    images: &quot;image path&quot;,<br>    price: 299.99,<br>    rating: 4.7,<br>    stock: 5,<br>    thumbnail: &quot;thumbnail path&quot;,<br>  ) {<br>    id<br>    title<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uNk_JEd3_VgpykCr.png" /></figure><p>This mutation adds a new product with the specified details and returns the<strong> id</strong> and title of the newly created product.</p><p>2. <strong>Updating and existing product</strong></p><pre>mutation {<br>  updateProduct(id:&quot;653fbae451de02c94aef4382&quot;, description: &quot;Update description for the first product&quot;){<br>    id,<br>    description,<br>    title<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ye4r-gSNh1_es-rH.png" /></figure><p>This mutation modifies the description of the product with the given<strong> id </strong>and returns the<strong> id</strong>, <strong>title and the updated description</strong>.</p><p>3. <strong>Deleting a product</strong></p><pre>mutation{<br>  deleteProduct(id:&quot;653fbae451de02c94aef4382&quot;){<br>    id<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t02RNKEvPpqmshfC.png" /></figure><p>Now that we have successfully used our mutations, it’s time to try out our queries. First, I have added three new products to the database.</p><p>Query to get all products from database:</p><pre>query{<br>  getAllProduct{<br>    id,<br>    title,<br>    brand<br>  }<br>}</pre><p><strong>Here is one of the great advantages of GraphQL: you can choose precisely what data you want to retrieve from the database. In this case, I am requesting the product’s ID, title, and brand to be returned.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_3OkOYyTvRl0lPL7.png" /></figure><p>Query to get a specific product by<strong> ID</strong>:</p><pre>query {<br>  getProduct(id: &quot;653fcc789b3cf5f5cfa3e48d&quot;) {<br>    id<br>    title<br>    brand<br>    category<br>    description<br>    price<br>    stock<br>  }<br>}</pre><p>Here also you can choose what data you want to retrieve from the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DdoooP_h31VKM8G6.png" /></figure><p>Now we’ve gained some insight into using GraphQL with Node.js. However, this is only the beginning. As you can see, the significant advantage lies in using just <strong>one URL</strong> for all operations, and the ability to dynamically determine the data we want from the database.</p><p>I hope this served as a good introduction to GraphQL. In the next part, I will introduce the authentication method with GraphQL and create the order mutation. You can find the full code<strong> </strong>on <a href="https://github.com/amit08cse53/grapqldemo"><strong>GitHub</strong></a>.</p><p><strong>See you in the next part!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0b60101eb9d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Server-Driven UI : Building Dynamic Apps Flutter]]></title>
            <link>https://medium.com/@amit08cse53/server-driven-ui-building-dynamic-apps-flutter-d60b437818f4?source=rss-9e35367d9e61------2</link>
            <guid isPermaLink="false">https://medium.com/p/d60b437818f4</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-widget]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[server-driven-ui]]></category>
            <dc:creator><![CDATA[Amit Singh]]></dc:creator>
            <pubDate>Sun, 19 Jan 2025 14:08:27 GMT</pubDate>
            <atom:updated>2025-01-19T14:08:27.466Z</atom:updated>
            <content:encoded><![CDATA[<h3>Server-Driven UI : Building Dynamic Apps Flutter</h3><p>During your programming journey, you will build hell lots of applications irrespective of any technology that you use, and getting these things done is one thing <strong>but doing it the right way is what matters</strong>.</p><p><strong>New comers</strong>: Those of you who don’t know me. I write posts on programming and share my Flutter/Android Native journey from time to time. So if you are someone who is interested, make sure to follow and subscribe to my medium.</p><p>I have already used Server driven UI in Android Native and Flutter development in almost 10 + app. So very useful for me and hope you all will use this in your future development.</p><p>so lets start …</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AtqYrBaS9RgWzkKJ.png" /></figure><h3>Introduction</h3><p>Server-Driven UI (SDU) is revolutionizing how we build and maintain mobile applications. In the Flutter ecosystem, this approach allows developers to modify their app’s interface and behavior without requiring new app store submissions. This article explores implementing SDU in Flutter, its benefits, and practical implementation strategies.</p><h3>What is Server-Driven UI?</h3><p>Server-Driven UI is an architectural pattern where the UI structure and configuration are defined on the server and delivered to the client application at runtime. Instead of hardcoding views in your Flutter app, you receive UI definitions from your backend, which the app then renders dynamically.</p><h3>Key Benefits</h3><ul><li>Rapid UI updates without app store submissions</li><li>A/B testing without code changes</li><li>Consistent cross-platform experiences</li><li>Reduced maintenance overhead</li><li>Better error handling and fallback mechanisms</li></ul><h3>Implementation Architecture</h3><p>1. Backend Component</p><p>The server needs to provide JSON configurations that describe:</p><ul><li>Widget types and hierarchies</li><li>Layout parameters</li><li>Style definitions</li><li>Data bindings</li><li>Action handlers</li></ul><p>Example JSON Configuration:</p><pre>{<br>  &quot;type&quot;: &quot;container&quot;,<br>  &quot;properties&quot;: {<br>    &quot;padding&quot;: 16,<br>    &quot;child&quot;: {<br>      &quot;type&quot;: &quot;column&quot;,<br>      &quot;children&quot;: [<br>        {<br>          &quot;type&quot;: &quot;text&quot;,<br>          &quot;properties&quot;: {<br>            &quot;text&quot;: &quot;Welcome&quot;,<br>            &quot;style&quot;: {<br>              &quot;fontSize&quot;: 24,<br>              &quot;fontWeight&quot;: &quot;bold&quot;<br>            }<br>          }<br>        },<br>        {<br>          &quot;type&quot;: &quot;button&quot;,<br>          &quot;properties&quot;: {<br>            &quot;text&quot;: &quot;Get Started&quot;,<br>            &quot;onPressed&quot;: {<br>              &quot;action&quot;: &quot;navigate&quot;,<br>              &quot;route&quot;: &quot;/home&quot;<br>            }<br>          }<br>        }<br>      ]<br>    }<br>  }<br>}</pre><p>2. Flutter Implementation</p><p>First, create a widget parser that can convert JSON configurations into Flutter widgets:</p><pre>class WidgetParser {<br>  Widget parseWidget(Map&lt;String, dynamic&gt; json) {<br>    switch (json[&#39;type&#39;]) {<br>      case &#39;container&#39;:<br>        return Container(<br>          padding: EdgeInsets.all(json[&#39;properties&#39;][&#39;padding&#39;].toDouble()),<br>          child: parseWidget(json[&#39;properties&#39;][&#39;child&#39;]),<br>        );<br>      case &#39;column&#39;:<br>        return Column(<br>          children: (json[&#39;children&#39;] as List)<br>              .map((child) =&gt; parseWidget(child))<br>              .toList(),<br>        );<br>      case &#39;text&#39;:<br>        return Text(<br>          json[&#39;properties&#39;][&#39;text&#39;],<br>          style: parseTextStyle(json[&#39;properties&#39;][&#39;style&#39;]),<br>        );<br>      case &#39;button&#39;:<br>        return ElevatedButton(<br>          onPressed: () =&gt; handleAction(json[&#39;properties&#39;][&#39;onPressed&#39;]),<br>          child: Text(json[&#39;properties&#39;][&#39;text&#39;]),<br>        );<br>      default:<br>        return Container(); // Fallback widget<br>    }<br>  }</pre><pre>  TextStyle parseTextStyle(Map&lt;String, dynamic&gt; style) {<br>    return TextStyle(<br>      fontSize: style[&#39;fontSize&#39;]?.toDouble(),<br>      fontWeight: style[&#39;fontWeight&#39;] == &#39;bold&#39; <br>          ? FontWeight.bold <br>          : FontWeight.normal,<br>    );<br>  }</pre><pre>  void handleAction(Map&lt;String, dynamic&gt; action) {<br>    switch (action[&#39;action&#39;]) {<br>      case &#39;navigate&#39;:<br>        // Implement navigation logic<br>        break;<br>      // Add other action handlers<br>    }<br>  }<br>}</pre><p>3. Network Layer</p><p>Implement a service to fetch UI configurations:</p><pre>class UIConfigService {<br>  final String baseUrl;<br>  <br>  UIConfigService({required this.baseUrl});</pre><pre>  Future&lt;Map&lt;String, dynamic&gt;&gt; fetchUIConfig(String screenId) async {<br>    try {<br>      final response = await http.get(<br>        Uri.parse(&#39;$baseUrl/ui-config/$screenId&#39;)<br>      );<br>      <br>      if (response.statusCode == 200) {<br>        return json.decode(response.body);<br>      }<br>      throw Exception(&#39;Failed to load UI config&#39;);<br>    } catch (e) {<br>      // Handle errors and provide fallback UI<br>      return getFallbackConfig(screenId);<br>    }<br>  }<br>}</pre><h3>Best Practices and Considerations</h3><ol><li>Caching Strategy</li></ol><p>Implement a caching mechanism to:</p><ul><li>Reduce server load</li><li>Enable offline functionality</li><li>Improve app performance</li></ul><pre>class UIConfigCache {<br>  final Box&lt;String&gt; cache;<br>  <br>  Future&lt;Map&lt;String, dynamic&gt;&gt; getCachedConfig(String screenId) async {<br>    final cached = cache.get(screenId);<br>    if (cached != null) {<br>      return json.decode(cached);<br>    }<br>    return {};<br>  }<br>  <br>  Future&lt;void&gt; cacheConfig(String screenId, Map&lt;String, dynamic&gt; config) async {<br>    await cache.put(screenId, json.encode(config));<br>  }<br>}</pre><p>2. Version Control</p><ul><li>Implement version checking for UI configurations</li><li>Provide fallback mechanisms for incompatible versions</li><li>Maintain backward compatibility</li></ul><p>3. Security Considerations</p><ul><li>Validate all server responses</li><li>Implement proper error handling</li><li>Use HTTPS for all network requests</li><li>Sanitize dynamic content</li></ul><h3>Testing Strategies</h3><p>Unit Testing</p><pre>void main() {<br>  test(&#39;WidgetParser correctly parses text widget&#39;, () {<br>    final parser = WidgetParser();<br>    final json = {<br>      &#39;type&#39;: &#39;text&#39;,<br>      &#39;properties&#39;: {<br>        &#39;text&#39;: &#39;Hello&#39;,<br>        &#39;style&#39;: {<br>          &#39;fontSize&#39;: 16,<br>          &#39;fontWeight&#39;: &#39;bold&#39;<br>        }<br>      }<br>    };<br>    <br>    final widget = parser.parseWidget(json) as Text;<br>    expect(widget.data, equals(&#39;Hello&#39;));<br>    expect(widget.style?.fontSize, equals(16));<br>    expect(widget.style?.fontWeight, equals(FontWeight.bold));<br>  });<br>}</pre><h3>Conclusion</h3><p>Server-Driven UI in Flutter offers a powerful way to create dynamic, maintainable applications. While implementation requires careful planning and robust architecture, the benefits of rapid updates, A/B testing capabilities, and reduced maintenance make it a compelling choice for modern app development.</p><p>Remember to:</p><ul><li>Start with a simple implementation</li><li>Add complexity gradually</li><li>Maintain good testing coverage</li><li>Monitor performance metrics</li><li>Plan for backwards compatibility</li><li>Implement proper error handling</li></ul><p>The future of mobile app development is becoming increasingly dynamic, and Server-Driven UI is at the forefront of this evolution.</p><p>If any of my posts help you in any way, you can consider buying me a cup of coffee. I will personally thank you 🙏.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*ynoO_7njAHhnTHdc.png" /></figure><p><a href="https://www.buymeacoffee.com/amit08cse53">https://www.buymeacoffee.com/amit08cse53</a></p><p>Thanks, guys, That’s all for now, Make sure to give a clap 👏 and leave some engagement. If there is any correction or feedback feel free to leave a comment as well.</p><p>Check out similar posts from CodingWithAmitSingh. Connect me on <a href="https://twitter.com/amit08cse53">Twitter</a> or <a href="https://www.linkedin.com/in/amit08cse53/">Linkedin</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d60b437818f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Code Review is Important]]></title>
            <link>https://medium.com/@amit08cse53/code-review-is-important-2e6e353f29cf?source=rss-9e35367d9e61------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e6e353f29cf</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[code-review]]></category>
            <category><![CDATA[code-review-best-practice]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Amit Singh]]></dc:creator>
            <pubDate>Thu, 16 May 2024 16:49:23 GMT</pubDate>
            <atom:updated>2024-05-16T16:49:23.430Z</atom:updated>
            <content:encoded><![CDATA[<p>During your programming journey, you will build hell lots of applications irrespective of any technology that you use, and getting these things done is one thing <strong>but doing it the right way is what matters</strong>.</p><p><strong>New comers</strong>: Those of you who don’t know me. I write posts on programming and share my Flutter/Android Native journey from time to time. So if you are someone who is interested, make sure to follow and subscribe to my medium.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TWsq_heX7N4FHVkh.png" /></figure><p>Code review is all about improving the code quality. However, it can be a nightmare for engineering managers and developers when not done correctly. They may experience several code review challenges and slow down the entire development process.</p><p>Hence, following code review best practices is important.</p><h3>Create a code review checklist</h3><p>Code review checklists include a predetermined set of questions and rules that the team will follow during the code review process. A few of the necessary quality checks include:</p><ul><li>Readability and maintainability: This is the first criterion and cannot be overstated enough.</li><li>Uniform formatting: Whether the code with consistent indentation, spacing, and naming convention easy to understand?</li><li>Testing and quality assurance: Whether it have meticulous testing and quality assurance processes?</li><li>Boundary testing: Are we exploring extreme scenarios and boundary conditions to identify hidden problems?</li><li>Security and performance: Are we ensuring security and performance in our source code?</li><li>Architectural integrity: Whether the code is scalable, sustainable, and has a solid architectural design?</li></ul><p>Apart from this, answer three questions in your mind while reviewing the code. It includes:</p><ul><li>Am I able to understand what the code does?</li><li>Is the code functioning how I expect it to?</li><li>Is the code fulfilling the regular requirements?</li></ul><p>This allows you to know what to look for in a code review, streamline the code review, and focus on priorities.</p><h3>Promote code review culture</h3><p>The code review process must be an opportunity for growth and knowledge sharing rather than a critique of developers’ abilities.</p><p>To have effective code reviews, It is vital to create a culture of collaboration and learning. It includes encouraging pair programming so that developers can learn from each other and less experienced members can learn from their senior leaders.</p><p>You can establish code review guidelines that emphasize constructive feedback, respect, and empathy. Ensure that you communicate the goals of the code review and specify the roles and responsibilities of reviewers and authors of the code.</p><p>This allows the development team to know the purpose behind code review and take it as a way to improve their coding abilities and skills.</p><h3>Provide constructive feedback</h3><p>One of the code review practices is to provide feedback that is specific, honest, and actionable. Constructive feedback is important in building rapport with your software development team.</p><p>The feedback should point out the right direction rather than a confusion. It could be in the form of suggestions, highlighting potential issues, or pointing out blind spots.</p><p>Make sure that you explain the ‘Why’ behind your feedback so that it reduces the need for follow-ups and gives the necessary context. When writing comments, it should be written clearly and concisely.</p><p>This helps in improving the skills of software developers and producing better code which further results in a high-quality codebase.</p><h3>Aim for small, incremental changes</h3><p>Instead of focusing on all the changes altogether, focus on a small section to examine all aspects thoroughly. It is advisable to break them into small, manageable chunks to identify potential issues and offer suggestions for improvement.</p><p>Focusing on a small section lets reviewers examine all aspects thoroughly (Use a code review checklist). Smaller the PRs, developers can understand code changes in a short amount of time and reviewers can provide more focused and detailed reviews. Each change is given the attention it deserves and easier to adhere to the style guide.</p><p>This helps in a deeper understanding of the code’s impact on the overall project.</p><h3>Incorporate code review goals and capture metrics</h3><p>According to Goodhart’s law, “When a measure becomes a target, it ceases to be a good measure”.</p><p>To measure the effectiveness of code review, have a few tangible goals so that it gives a quantifiable picture of how your code is improving. Have a few metrics in mind to determine the efficiency of your review and analyze the impact of the change in the process.</p><p>You can use SMART criteria and start with external metrics to get the bigger picture of how your code quality is increasing. Other than this, below are a few internal key metrics that must be kept in mind:</p><ul><li>Inspection rate: The speed at which code is reviewed.</li><li>Defect rate: It is measured by dividing the number of defects found by the number of hours spent on a code review.</li><li>Defect density: It is measured by dividing the defect count by thousands of lines of code.</li></ul><p>Besides this, you can use metrics-driven code review tools to decide in advance the goals and how to measure the effectiveness.</p><h3>Don’t rush your review</h3><p>As mentioned above, don’t review the code all at once. Keep these three things in mind:</p><ul><li>Don’t review the code for longer than 60 minutes.</li><li>Limit your review to 200–400 lines of code at once.</li><li>Plan for 3 seconds of review time per line of code.</li></ul><p>This is because reviewing the code continuously can drop off the focus and attention to detail. This further makes it less effective and invites burnout.</p><p>Hence, conduct code review sessions often and in short sessions. Encourage few breaks in between and set boundaries otherwise, defects may go unnoticed and the purpose of the code review process remains unfulfilled.</p><h3>Rotate code reviewers regularly</h3><p>Relying on the same code reviewers consistently is a common challenge that can cause burnout. This can negatively impact the software development process in the long run.</p><p>Hence, encourage a rotation approach i.e. different team members can participate in reviewing the code. This brings in various skill sets and experience levels which promotes cross learning and a well-rounded review process. It also provides different points of view to get better solutions and fewer blind spots.</p><p>With this approach, team members can be familiar with different parts of the codebase, avoid bias in the review process, and understand each other’s coding styles.</p><h3>Always document code review decisions</h3><p>Documenting code review decisions is a great way to understand the overall effectiveness of the code review process. Ensure that you record and track the code review outcome for future reference. It is because this documentation makes it easier for those who may work on the codebase in the future.</p><p>It doesn’t matter if the review type is instant or synchronous.</p><p>Documentation provides insights into the reasoning behind certain choices, designs, and modifications. It helps in keeping historical records i.e. changes made over time, reasons for those changes, and any lessons learned during the review process. Besides this, it accelerates the onboarding process for new joiners.</p><p>As a result, documentation and tracking of the code review decisions encourage the continuous improvement culture within the development team.</p><h3>Focus on coding standards, not personal preference</h3><p>Emphasizing coding standards promotes consistency, readability, maintainability, and overall code quality.</p><p>Personal preferences vary widely among developers. Hence, by focusing on coding standards, team members can limit subjective arguments and rather rely on documented agreed-upon code review guidelines. It helps in addressing potential issues early in the development process and ensures the codebase remains consistent over time.</p><p>Besides this, adhering to coding standards makes it easier to scale development efforts and add new features and components seamlessly.</p><h3>Automate as much as possible</h3><p>Code review is a vital process yet it can be time-consuming. Hence, automate what can be automated.</p><p>Use code review tools to help improve the code quality and increase the level of speed, precision, and consistency. This allows reviewers to take more time in giving valuable feedback, automate, track changes, and enable easy collaboration. It also ensures that the changes don’t break existing functionality and streamline the development process.</p><h3>Conclusion</h3><p>If you prioritize the code review process, do follow the above-mentioned best practices. These code review best practices maximize the quality of the code, improve the team’s productivity, and streamline the development process.</p><p>If you made till here I think you have done a great job learning about code review best practices</p><p>If any of my posts help you in any way, you can consider buying me a cup of coffee. I will personally thank you 🙏.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*uhjARDS2S2EAX7wp.png" /></figure><p><a href="https://www.buymeacoffee.com/amit08cse53">https://www.buymeacoffee.com/amit08cse53</a></p><p>Thanks, guys, That’s all for now, Make sure to give a clap 👏 and leave some engagement. If there is any correction or feedback feel free to leave a comment as well.</p><p>Check out similar posts from CodingWithAmitSingh. Connect me on <a href="https://twitter.com/amit08cse53">Twitter</a> or <a href="https://www.linkedin.com/in/amit08cse53/">Linkedin</a></p><p>Happy reviewing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e6e353f29cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter App Lifecycle]]></title>
            <link>https://medium.com/@amit08cse53/flutter-app-lifecycle-534ab9add513?source=rss-9e35367d9e61------2</link>
            <guid isPermaLink="false">https://medium.com/p/534ab9add513</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Amit Singh]]></dc:creator>
            <pubDate>Wed, 08 May 2024 16:26:21 GMT</pubDate>
            <atom:updated>2024-05-08T16:26:21.371Z</atom:updated>
            <content:encoded><![CDATA[<p>During your programming journey, you will build hell lots of applications irrespective of any technology that you use, and getting these things done is one thing <strong>but doing it the right way is what matters</strong>.</p><p><strong>New comers</strong>: Those of you who don’t know me. I write posts on programming and share my Flutter/Android Native journey from time to time. So if you are someone who is interested, make sure to follow and subscribe to my medium.</p><p>So let’s start …</p><p>Flutter apps follow a structured lifecycle with various methods that are called at different stages. This lifecycle is crucial for managing the state, handling updates, and ensuring the proper functioning of your app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xslpOFRgrN0HMSzs.png" /></figure><h3>createState()</h3><p>This is the first method called when a StatefulWidget is instantiated. It’s responsible for creating the state object that will persist throughout the widget’s lifecycle</p><h3>initState()</h3><p>After createState(), initState() is called. This method is ideal for performing one-time initializations, such as setting up controllers or subscribing to streams</p><h3>didChangeDependencies()</h3><p>It is triggered whenever the dependencies of the widget change, offering a chance to perform actions dependent on the widget’s context or other dependencies.</p><h3>build()</h3><p>The build() method is called after didChangeDependencies() and whenever the widget needs to be rebuilt. This is where you define the structure of your widget by returning a widget tree. This method can be called multiple times during the widget&#39;s lifecycle</p><h3>didUpdateWidget()</h3><p>This method is called when the parent widget changes, causing the current widget to be rebuilt. It’s useful for comparing the old and new widget configurations and responding accordingly.</p><h3>setState()</h3><p>When the internal state of a widget changes, setState() is used to notify Flutter that the widget needs to be rebuilt. This method triggers a call to build()</p><h3>deactivate()</h3><p>Called when the StatefulWidget is about to be permanently removed from the widget tree. It’s the ideal place to release resources, such as stopping animations or disposing of controllers, to prevent memory leaks.</p><h3>dispose()</h3><p>As the widget nears its end, the dispose() method is invoked. This is the last opportunity to release resources, stop animations, or dispose of controllers before the widget is permanently removed</p><h3>Conclusion:</h3><p>Mastering the Flutter app lifecycle is essential for crafting responsive and efficient applications. By understanding these stages, developers can effectively manage state, handle updates, and ensure their apps behave seamlessly.</p><p>If you made till here I think you have done a great job learning flutter app lifecycle.</p><p>If any of my posts help you in any way, you can consider buying me a cup of coffee. I will personally thank you 🙏.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*8T8EBNLq8K8SmT-4.png" /></figure><p><a href="https://www.buymeacoffee.com/amit08cse53">https://www.buymeacoffee.com/amit08cse53</a></p><p>Thanks, guys, That’s all for now, Make sure to give a clap 👏 and leave some engagement. If there is any correction or feedback feel free to leave a comment as well.</p><p>Check out similar posts from CodingWithAmitSingh. Connect me on <a href="https://twitter.com/amit08cse53">Twitter</a> or <a href="https://www.linkedin.com/in/amit08cse53/">Linkedin</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=534ab9add513" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[var and dynamic in dart(flutter)]]></title>
            <link>https://medium.com/@amit08cse53/var-and-dynamic-in-dart-flutter-a0cb8b86628e?source=rss-9e35367d9e61------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0cb8b86628e</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[mobi̇le]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Amit Singh]]></dc:creator>
            <pubDate>Sat, 24 Feb 2024 18:32:55 GMT</pubDate>
            <atom:updated>2024-02-24T18:32:55.194Z</atom:updated>
            <content:encoded><![CDATA[<p>During your programming journey, you will build hell lots of applications irrespective of any technology that you use, and getting these things done is one thing <strong>but doing it the right way is what matters</strong>.</p><p><strong>New comers</strong>: Those of you who don’t know me. I write posts on programming and share my Flutter/Android Native journey from time to time. So if you are someone who is interested, make sure to follow and subscribe to my medium.</p><p>Have you ever wondered what var and dynamic mean and how they differ from each other?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*m45ulg-omysq6TW7.gif" /></figure><p>Well, regardless of whether you have or not, let me shed some light on it. Look at the code below!</p><pre>var myLuckyDay;<br>dynamic myFavouriteDay;</pre><p>The first thing we need to understand is that “var” is not a <strong>variable type </strong>itself, while “dynamic” is. var is a <strong>keyword </strong>used when you want dart compiler to automatically <strong>determine </strong>the <strong>type </strong>of the variable based on assigned value whereas dynamic is a type itself. <strong>Dynamic variables </strong>are those that can hold values of any type.</p><p>When I declare myLuckyDay as var myLuckyDay;, I am asking the Dart compiler to figure out the type of myLuckyDay by itself. Now, since myLuckyDay is not initialized with any value, the compiler assumes that myLuckyDay must be <strong>dynamic</strong>.</p><pre>var myLuckyDay= 1;</pre><p><strong>But </strong>here, the type of myLuckyDay is inferred and set as an integer since it is initialized with an integer value. Once its type is set as an integer, it cannot be changed throughout the program.</p><pre>var myLuckyDay = 1;  //type set as integer</pre><pre>myLuckyDay= &quot;one&quot;; //This will result in compile error(String can&#39;t be set to int variable</pre><pre>dynamic myFavouriteDay = 2; //myFavouriteDay is dynamic</pre><pre>myFavouriteDay = &quot;Two&quot;; //wont result in any error since dynamic variable can be reassigned any type of value</pre><p>So, there it is — the differences between var and dynamic. Pretty easy, right?</p><p>Let me give you guys something to ponder.</p><pre>var myLuckyDay;</pre><pre>myLuckyDay = 1; </pre><pre>myLuckyDay = &quot;January&quot;; //No error</pre><pre>myLuckyDay = [&quot;a&quot;,&quot;e&quot;,&quot;i&quot;,&quot;o&quot;,&quot;u&quot;]; //No error</pre><p>Why is reassigning myLuckyDay with a string and again with an array fine in this case? I would be glad to hear your thoughts on this.</p><p>If you made till here I think you have done a great job learning all these best practices.</p><p>If any of my posts help you in any way, you can consider buying me a cup of coffee. I will personally thank you 🙏.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*SnAOsYuZAX9MJ0Hp.png" /></figure><p><a href="https://www.buymeacoffee.com/amit08cse53">https://www.buymeacoffee.com/amit08cse53</a></p><p>Thanks, guys, That’s all for now, Make sure to give a clap 👏 and leave some engagement. If there is any correction or feedback feel free to leave a comment as well.</p><p>Check out similar posts from CodingWithAmitSingh. Connect me on <a href="https://twitter.com/amit08cse53">Twitter</a> or <a href="https://www.linkedin.com/in/amit08cse53/">Linkedin</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0cb8b86628e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why await in forEach not work?]]></title>
            <link>https://medium.com/@amit08cse53/why-await-in-foreach-not-work-7d4eabe93388?source=rss-9e35367d9e61------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d4eabe93388</guid>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Amit Singh]]></dc:creator>
            <pubDate>Sat, 04 Nov 2023 16:46:05 GMT</pubDate>
            <atom:updated>2023-11-04T17:08:45.994Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/793/0*Q5VZa3h2hv7In-Gr.png" /></figure><p>During your programming journey, you will build hell lots of applications irrespective of any technology that you use, and getting these things done is one thing <strong>but doing it the right way is what matters</strong>.</p><p><strong>New comers</strong>: Those of you who don’t know me. I write posts on programming and share my Flutter/Android Native journey from time to time. So if you are someone who is interested, make sure to follow and subscribe to my medium.</p><p>Most programming languages have iteration statements, and Dart is not an exception.<br>For one to handle highly scalable and efficient business logic using Dart, detailed knowledge of asynchronous operations, futures, and loops among others is a can’t-do-without.</p><blockquote><em>In this article, We’ll focus specifically on the </em><em>for..in and </em><em>forEach loops as used in asynchronous operations.</em></blockquote><p>Generally, both the for-in and forEach constructs are used to loop over iterables(List, Set, etc). Both have a return type of void. .i.e(a new value can not be returned from these methods), neither do they expose the current index of the iteration unlike the typical for..loop.</p><p>Enough of the general notes, let’s see how these constructs handle asynchronous operations in Dart.</p><p>Take a closer look at the examples below:</p><pre>List&lt;Person&gt; persons = [<br>  Person(<br>    name: &quot;Name 1&quot;,  <br>    images:[&quot;My Image1&quot;, &quot;My Image2&quot;],<br>  ),<br>];</pre><pre>class Person{<br>   String name;<br>   List&lt;String&gt; images;<br>   Person({this.name, this.images});<br>}</pre><pre>void main() {<br>  Future uploadImages({images, name})async{<br>    return [&quot;Image 1&quot;, &quot;image 2&quot;];<br>  }</pre><pre>Future updateProfile(Person person) async{<br>    List&lt;String&gt; newImageUrls = [];<br>    person.images.forEach((image) async{<br>       if (image.runtimeType == String) {<br>        dynamic url = await uploadImages(images: [image], name: person.name);<br>        print(&quot;forEach URL: $url&quot;);<br>        newImageUrls.addAll(url);<br>      } else {<br>        newImageUrls.add(image);<br>      }<br>    });<br>    print(&quot;Profile Images f1: $newImageUrls&quot;);<br>    person..images = newImageUrls;<br>  }<br>  updateProfile(persons[0]);<br>}</pre><p>From the above snippet, using the <strong>for..Each</strong> construct might seem like a natural choice when looping over a list using async/await. Typically, we expect the synchronous-reading magic async/await to do what it says and actually await the promises. Often times this gives an unexpected output or even throws a <strong>ReferenceError</strong> if the result of the operation is being used somewhere else in the application (as seen in the above code).</p><p>To fix this, we can either switch to the for..in construct or use the Future.forEach method. This should do the trick</p><pre> Future updateProfile2(Person person) async {<br>    List&lt;String&gt; newImageUrls = [];<br>    for (var image in person.images) {<br>      if (image.runtimeType == String) {<br>        dynamic url = await uploadImages(images: [image], name: person.name);<br>        print(&quot;for..in URL: $url&quot;);<br>        newImageUrls.addAll(url);<br>      } else {<br>        newImageUrls.add(image);<br>      }<br>    }<br>    print(&quot;Profile Images f2: ${newImageUrls}&quot;);<br><br>    person..images = newImageUrls;<br>  }</pre><p>First, we changed the for..Each block to a for..in construct…why? Switching to a for..in block solved the problem because the for..each returns the empty result set first before processing the await function inside the forEach. It just applies the function on each element and calls the next without await for the asynchronous operation to return. But the for..in construct on the other hand, actually awaits the result of the execution of the function before calling next</p><pre>Future updateProfile3(Person person) async {<br>    List&lt;String&gt; newImageUrls = [];<br><br>    await Future.forEach(person.images, (image)async{<br>       if (image.runtimeType == String) {<br>        dynamic url = await uploadImages(images: [image], name: person.name);<br>        print(&quot;Future.forEach URL: $url&quot;);<br>        newImageUrls.addAll(url);<br>      } else {<br>        newImageUrls.add(image);<br>      }<br>    });<br><br>    print(&quot;Profile Images f3: $newImageUrls&quot;);<br><br>    person..images = newImageUrls;<br>  }</pre><p>The Future.forEach() waits for each Future to be completed before moving to the next element.</p><p>When you need to wait for multiple Futures to complete irrespective of their order, you can use Future.wait() method like this:</p><pre>Future.wait(person.images.map(functionCall));</pre><p>or</p><pre>Future.wait([futureOne(), futureTwo(), …]).then((res) =&gt; functionToCallAfterResult(res));</pre><p><strong>Error handling in asynchronous code</strong><br>Errors from your asynchronous code can be handled using the try..catch block in dart. Essentially, if an error is thrown within the try block, such can be received and handled with the catch block.</p><p>If you made till here I think you have done a great job learning all these best practices.</p><p>If any of my posts help you in any way, you can consider buying me a cup of coffee. I will personally thank you 🙏.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*z68wekliy-lz-CxC.png" /></figure><p><a href="https://www.buymeacoffee.com/amit08cse53">https://www.buymeacoffee.com/amit08cse53</a></p><p>Thanks, guys, That’s all for now, Make sure to give a clap 👏 and leave some engagement. If there is any correction or feedback feel free to leave a comment as well.</p><p>Check out similar posts from CodingWithAmitSingh. Connect me on <a href="https://twitter.com/amit08cse53">Twitter</a> or <a href="https://www.linkedin.com/in/amit08cse53/">Linkedin</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d4eabe93388" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Unit Test Guidelines]]></title>
            <link>https://medium.com/@amit08cse53/flutter-unit-test-guidelines-38c2a261340b?source=rss-9e35367d9e61------2</link>
            <guid isPermaLink="false">https://medium.com/p/38c2a261340b</guid>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Amit Singh]]></dc:creator>
            <pubDate>Fri, 22 Sep 2023 19:21:06 GMT</pubDate>
            <atom:updated>2023-09-22T19:21:06.432Z</atom:updated>
            <content:encoded><![CDATA[<p>During your programming journey, you will build hell lots of applications irrespective of any technology that you use, and getting these things done is one thing <strong>but doing it the right way is what matters</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*30E-3n4Pu6_nrbNR.png" /></figure><p><em>Hello guys, this is Amit Singh and in this post, we are going to discuss some of the testability Guidelines for Unit tests.</em></p><h3>So let&#39;s start …</h3><p>Any code isn’t testable. This covers the main points to ensure your codebase is ready to accommodate and benefit from unit tests.</p><h3>What makes a code testable?</h3><p>Code is considered testable when it is designed in a way that allows automated tests to be easily created and run. This means that the code should be:</p><ol><li>Modular, with clear separation of concerns and dependencies.</li><li>Passing dependencies from constructors to allow mocking.</li><li>Following the Single Responsibility Principle (SRP).</li></ol><p>When code is testable, it allows developers to catch bugs and issues early on in the development process and ensure that changes to the code don’t introduce new problems. This can save time and resources in the long run, as it helps to prevent issues from appearing in production and reduces the need for manual testing.</p><h3>Practices to follow</h3><h4>1. Use Dependency Injection</h4><p>Dependency injection is a design pattern that allows us to inject dependencies into our code. This makes it easier to write unit tests because we can replace dependencies with mocks or stubs. In Flutter, we can use the provider package to implement dependency injection. Here is an example:</p><pre>class UserService {<br>  final HttpClient httpClient;<br>​<br>  UserService(this.httpClient);<br>​<br>  Future&lt;User&gt; getUser(String id) async {<br>    final response = await httpClient.get(&#39;/users/$id&#39;);<br>    return User.fromJson(response.data);<br>  }<br>}</pre><p>In this example, we are injecting a HttpClient dependency into the UserService. This makes it easier to test because we can replace HttpClient it with a mock during testing.</p><h4>2. Use Separation of Concerns</h4><p>Write small and focused functions: Functions that do one thing and do it well are easier to test. Avoid large functions that perform multiple tasks.</p><pre>bool isEmailValid(String email) {<br>  final regex = RegExp(r&#39;^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$&#39;);<br>  return regex.hasMatch(email);<br>}</pre><h4>3. Avoid global and static states</h4><p>Global state makes it difficult to test your code in isolation because changes in one part of the code can affect other parts. In addition to that, they can’t be mocked directly.</p><pre>class Counter {<br>  static int count = 0;<br>​<br>  static void increment() {<br>    count++;<br>  }<br>}​</pre><h4>4. Don’t call another function within the same class.</h4><p>Writing unit tests for functions calling other functions within the same class can become messy and difficult to manage, especially because you can’t mock or simulate their output.</p><pre>class Example {<br>  int add(int a, int b) {<br>    return a + b;<br>  }<br>​<br>  int multiply(int a, int b) {<br>    int result = 0;<br>    for (int i = 0; i &lt; a; i++) {<br>      result = add(result, b);<br>    }<br>    return result;<br>  }<br>}</pre><p>Suppose multiply is the main function, while add is the sub-function being called inside multiply. It becomes hard to write a test for the multiply function on its own, because it depends on the add function&#39;s implementation.</p><p>Using Dependency Injection:</p><pre>class Adder{<br>  int add(int a, int b) {<br>    return a + b;<br>  }<br>}<br>​<br>class BetterExample {<br>  final Adder _adder;<br>  <br>  BetterExample(this._adder);<br>​<br>  int multiply(int a, int b) {<br>    int result = 0;<br>    for (int i = 0; i &lt; a; i++) {<br>      result = _adder.add(result, b);<br>    }<br>    return result;<br>  }<br>}</pre><p>Now multiply depends on an instance of the Adder class, which can be easily mocked for testing. The test for the multiply function can be written without having to worry about testing the add function.</p><h4>5. Use SOLID Principles</h4><p>SOLID principles are a set of software design principles that help us write code that is maintainable, scalable, and testable.</p><ol><li>Single Responsibility Principle (SRP)<br>A class/method should have only one reason to change.</li><li>Open/Closed Principle (OCP)<br>A class should be open for extension but closed for modification.</li><li>Liskov Substitution Principle (LSP)<br>Subtypes must be substitutable for their base types.</li><li>Interface Segregation Principle (ISP)<br>Clients should not be forced to depend on methods they do not use.</li><li>Dependency Inversion Principle (DIP)<br>High-level modules should not depend on low-level modules. Both should depend on abstractions.</li></ol><p>For more details, please read: <a href="https://medium.com/@amit08cse53/solid-principles-in-a-flutter-9c022788bab6">Solid Principles</a> Blog by Amit Singh</p><p>If you made till here I think you have done a great job learning all these best practices.</p><p>If any of my posts help you in any way, you can consider buying me a cup of coffee. I will personally thank you 🙏.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*o0qgCGe99hXge1fn.png" /></figure><p><a href="https://www.buymeacoffee.com/amit08cse53">https://www.buymeacoffee.com/amit08cse53</a></p><p>Thanks, guys, That’s all for now, Make sure to give a clap 👏 and leave some engagement. If there is any correction or feedback feel free to leave a comment as well.</p><p>Check out similar posts from CodingWithAmitSingh. Connect me on <a href="https://twitter.com/amit08cse53">Twitter</a> or <a href="https://www.linkedin.com/in/amit08cse53/">Linkedin</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38c2a261340b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solid Principles in a Flutter]]></title>
            <link>https://medium.com/@amit08cse53/solid-principles-in-a-flutter-9c022788bab6?source=rss-9e35367d9e61------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c022788bab6</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[code-guide]]></category>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[app-development]]></category>
            <dc:creator><![CDATA[Amit Singh]]></dc:creator>
            <pubDate>Tue, 05 Sep 2023 18:41:34 GMT</pubDate>
            <atom:updated>2023-09-05T18:44:14.854Z</atom:updated>
            <content:encoded><![CDATA[<p>During your programming journey, you will build hell lots of applications irrespective of any technology that you use, and getting these things done is one thing <strong>but doing it the right way is what matters</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/0*Gn4dFd820oGv_j1_" /></figure><blockquote><strong><em>New comers</em></strong><em>: Those of you who don’t know me. I write post on programming and share my flutter/Android Native journey from time to time. So if you are someone who is interested, make sure to follow and subscribe to my medium.</em></blockquote><p>In this post, we are going to discuss SOLID principles.</p><p>These principles are a set of guidelines that help developers write code that is <strong>easy to maintain, extend, and test</strong>. In this article, we’ll take a look at the SOLID principles in the context of Flutter and provide real-world examples to help you understand them better.</p><h3>SOLID Principles Overview</h3><p>SOLID is an acronym that stands for five principles of object-oriented programming:</p><ol><li>Single Responsibility Principle (SRP): A class should have only one reason to change.</li><li>Open/Closed Principle (OCP): A class should be open for extension but closed for modification.</li><li>Liskov Substitution Principle (LSP): Subtypes should be substitutable for their base types.</li><li>Interface Segregation Principle (ISP): Clients should not be forced to depend on interfaces they don’t use.</li><li>Dependency Inversion Principle (DIP): High-level modules should not depend on low-level modules. Both should depend on abstractions.</li></ol><p>Now let’s dive into each principle and see how they apply in Flutter development.</p><h3>Single Responsibility Principle (SRP)</h3><p>The SRP states that a class should have only one reason to change. In other words, a class should have only one responsibility. This helps to keep the code clean, organized, and easy to maintain.</p><p>Let’s take an example of a class that handles both the UI rendering and the business logic. This is not a good design because if we want to change the UI, we have to modify the business logic code as well. Instead, we can separate the UI and the business logic into different classes to follow the SRP.</p><p>Here’s an example of how to separate the UI and business logic in Flutter:</p><pre>class MyHomePage extends StatefulWidget {<br>  @override<br>  _MyHomePageState createState() =&gt; _MyHomePageState();<br>}</pre><pre>class _MyHomePageState extends State&lt;MyHomePage&gt; {<br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: Text(&#39;My App&#39;),<br>      ),<br>      body: Center(<br>        child: Text(<br>          &#39;Hello, World!&#39;,<br>          style: TextStyle(fontSize: 30),<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><pre>class HomePageViewModel {<br>  String getText() =&gt; &#39;Hello, World!&#39;;<br>}</pre><p>In this example, the MyHomePage widget only handles the UI rendering, while the HomePageViewModel class handles the business logic. This separation makes it easier to modify each component independently without affecting the other.</p><h3>Open/Closed Principle (OCP)</h3><p>The OCP states that a class should be open for extension but closed for modification. This means that we should be able to add new features or behaviors to a class without changing its existing code. This helps to maintain the existing code and avoid introducing new bugs.</p><p>Let’s take an example of a class that handles the rendering of different shapes. We can use the OCP principle to allow the addition of new shapes without modifying the existing code.</p><p>Here’s an example of how to use the OCP principle in Flutter:</p><pre>abstract class Shape {<br>  void draw();<br>}</pre><pre>class Circle implements Shape {<br>  @override<br>  void draw() =&gt; print(&#39;Drawing a circle.&#39;);<br>}</pre><pre>class Rectangle implements Shape {<br>  @override<br>  void draw() =&gt; print(&#39;Drawing a rectangle.&#39;);<br>}</pre><pre>class ShapePainter {<br>  List&lt;Shape&gt; shapes;</pre><pre>  void paint(Canvas canvas) {<br>    shapes.forEach((shape) =&gt; shape.draw());<br>  }<br>}</pre><p>In this example, we have an abstract Shape class with a draw method that will be implemented by its concrete subclasses. The ShapePainter class takes a list of shapes and paints them on the canvas by calling their draw method.</p><p>Now, let’s say we want to add a new shape, such as a triangle. We can do this without modifying the ShapePainter class by creating a new subclass of Shape:</p><pre>class Triangle implements Shape {<br>  @override<br>  void draw() =&gt; print(&#39;Drawing a triangle.&#39;);<br>}</pre><p>And then we can use it like this:</p><pre>final shapes = [Circle(), Rectangle(), Triangle()];<br>final painter = ShapePainter(shapes);</pre><p>This way, we can add new shapes without modifying the existing code, which makes it easier to maintain and extend the application.</p><h3>Liskov Substitution Principle (LSP)</h3><p>The LSP states that subtypes should be substitutable for their base types. This means that if we have a class A that is a subtype of class B, we should be able to use an object of type A wherever an object of type B is expected, without affecting the correctness of the program.</p><p>Let’s take an example of a class hierarchy that represents different types of animals. We can use the LSP to ensure that any subclass can be used interchangeably with its superclass.</p><p>Here’s an example of how to use the LSP in Flutter:</p><pre>abstract class Animal {<br>  String name;<br>  String speak();<br>}</pre><pre>class Dog extends Animal {<br>  @override<br>  String speak() =&gt; &#39;Woof!&#39;;<br>}</pre><pre>class Cat extends Animal {<br>  @override<br>  String speak() =&gt; &#39;Meow!&#39;;<br>}</pre><pre>class AnimalApp {<br>  void run() {<br>    final animals = [Dog(), Cat()];<br>    animals.forEach((animal) =&gt; print(&#39;${animal.name} says ${animal.speak()}&#39;));<br>  }<br>}</pre><p>In this example, we have an abstract Animal class with a name property and a speak method that will be implemented by its concrete subclasses. The AnimalApp class creates a list of animals and prints out their names and the sounds they make.</p><p>Thanks to the LSP, we can treat each animal as an Animal object, even though they are actually Dog and Cat objects. This makes the code more flexible and easier to maintain.</p><h3>Interface Segregation Principle (ISP)</h3><p>The ISP states that clients should not be forced to depend on interfaces they don’t use. This means that we should break down large interfaces into smaller, more specialized ones, so that clients only need to implement the methods they actually use.</p><p>Let’s take an example of an interface that represents a shape. We can use the ISP to break down this interface into smaller interfaces that represent specific shape behaviors.</p><p>Here’s an example of how to use the ISP in Flutter:</p><pre>abstract class Shape {<br>  double get area;<br>}</pre><pre>abstract class HasPerimeter {<br>  double get perimeter;<br>}</pre><pre>class Circle implements Shape, HasPerimeter {<br>  final double radius;</pre><pre>  Circle(this.radius);</pre><pre>  @override<br>  double get area =&gt; 3.14 * radius * radius;</pre><pre>  @override<br>  double get perimeter =&gt; 2 * 3.14 * radius;<br>}</pre><pre>class Square implements Shape, HasPerimeter {<br>  final double side;</pre><pre>  Square(this.side);</pre><pre>  @override<br>  double get area =&gt; side * side;</pre><pre>  @override<br>  double get perimeter =&gt; 4 * side;<br>}</pre><p>In this example, we have an abstract Shape interface with a get area method, and an HasPerimeter interface with a get perimeter method. The Circle and Square classes implement both interfaces, since they have both an area and a perimeter.</p><p>By breaking down the Shape interface into smaller interfaces, we make it easier for clients to use only the methods they need. For example, if a client only needs to calculate the area of a shape, they can depend only on the Shape interface, and not on the HasPerimeter interface.</p><h3>Dependency Inversion Principle (DIP)</h3><p>The DIP states that high-level modules should not depend on low-level modules. Instead, both should depend on abstractions. This means that we should define interfaces or abstract classes for our dependencies, so that we can easily switch between different implementations without affecting the rest of the application.</p><p>Let’s take an example of a class that sends notifications. We can use the DIP to make this class more flexible, by defining an interface for its dependencies.</p><p>Here’s an example of how to use the DIP in Flutter:</p><pre>abstract class NotificationService {<br>  Future&lt;void&gt; sendNotification(String message);<br>}</pre><pre>class EmailService implements NotificationService {<br>  @override<br>  Future&lt;void&gt; sendNotification(String message) async {<br>    // send email notification<br>  }<br>}</pre><pre>class PushNotificationService implements NotificationService {<br>  @override<br>  Future&lt;void&gt; sendNotification(String message) async {<br>    // send push notification<br>  }<br>}</pre><pre>class NotificationSender {<br>  final NotificationService _service;</pre><pre>  NotificationSender(this._service);</pre><pre>  Future&lt;void&gt; send(String message) =&gt; _service.sendNotification(message);<br>}</pre><p>In this example, we have an abstract NotificationService interface with a sendNotification method, and two concrete implementations: EmailService and PushNotificationService. The NotificationSender class depends on the NotificationService interface, instead of depending directly on either EmailService or PushNotificationService.</p><p>By depending on an interface instead of a concrete implementation, we make it easier to switch between different notification services, without having to modify the NotificationSender class.</p><h3>Conclusion :</h3><p>Don’t get trapped by Solid</p><blockquote><em>: S.O.L.I.D Principles are principles, not rules</em></blockquote><blockquote><em>: Always use common sense while applying this. Your goal is to achieve to make your code maintainable, easy to extend.</em></blockquote><blockquote><em>: Avoid over- fragmenting your code for the sake of SRP or S.O.L.I.D</em></blockquote><blockquote><em>: Don’t try to achieve S.O.L.I.D, use S.O.L.I.D to achieve maintainability. It’s a tool, not your goal</em></blockquote><p>If you made till here I think you have done a great job learning all these best practices.</p><p>If any of my posts help you in any way, you can consider buying me a cup of coffee. I will personally thank you 🙏.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*lpj1DqO0tST1qgfr.png" /></figure><p><a href="https://www.buymeacoffee.com/amit08cse53">https://www.buymeacoffee.com/amit08cse53</a></p><p>Thanks, guys, That’s all for now, Make sure to give a clap 👏 and leave some engagement. If there is any correction or feedback feel free to leave a comment as well.</p><p>Check out similar posts from CodingWithAmitSingh. Connect me on <a href="https://twitter.com/amit08cse53">Twitter</a> or <a href="https://www.linkedin.com/in/amit08cse53/">Linkedin</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c022788bab6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>