<?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 Ashutosh Yadav on Medium]]></title>
        <description><![CDATA[Stories by Ashutosh Yadav on Medium]]></description>
        <link>https://medium.com/@ashutosh7379947493?source=rss-46a66af35978------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*PQd9eepyAvTh8KAV</url>
            <title>Stories by Ashutosh Yadav on Medium</title>
            <link>https://medium.com/@ashutosh7379947493?source=rss-46a66af35978------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 19:40:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ashutosh7379947493/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[WebSockets in Flutter]]></title>
            <link>https://medium.com/@ashutosh7379947493/websockets-in-flutter-ad873a499275?source=rss-46a66af35978------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad873a499275</guid>
            <category><![CDATA[flutter-websocket]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[flutter-development]]></category>
            <category><![CDATA[flutter-tutorial]]></category>
            <category><![CDATA[flutter-developer]]></category>
            <dc:creator><![CDATA[Ashutosh Yadav]]></dc:creator>
            <pubDate>Sat, 15 Feb 2025 05:10:30 GMT</pubDate>
            <atom:updated>2025-02-15T09:37:25.072Z</atom:updated>
            <content:encoded><![CDATA[<h4>An easy explanation with a basic chat app</h4><p>I’m currently working on my startup, <a href="https://getwaitlist.com/waitlist/23342"><strong>Stockic — a News Research App</strong></a><strong> </strong>( you can join the waitlist :), and exploring ways to display real-time stock data on the market page. During my research, I discovered that <strong>WebSockets</strong> provide the perfect solution for real-time updates.</p><p>To share this valuable insight, here’s a <strong>simple breakdown of WebSockets</strong> to help you understand the concept easily.</p><h3>WebSockets in Flutter: A Step-by-Step Guide</h3><p>WebSockets allow real-time communication between a client (Flutter app) and a server. Unlike traditional HTTP requests, WebSockets maintain a persistent connection, enabling instant bidirectional communication. This is ideal for chat applications, live notifications, real-time stock updates, and multiplayer games.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*oemH89Qw_mwlZskcuIVM3Q.png" /></figure><h3>1. Understanding WebSockets</h3><p>Before we begin coding, let’s go through some important concepts:</p><h3>What is a WebSocket?</h3><p>A WebSocket is a communication protocol that provides full-duplex (two-way) communication between a client and a server over a single TCP connection.</p><h3>Common WebSocket Terms</h3><ul><li><strong>WebSocket Server</strong>: The backend that handles WebSocket connections.</li><li><strong>WebSocket Client</strong>: The Flutter app that connects to the server.</li><li><strong>Handshake</strong>: The initial HTTP request that upgrades the connection to WebSocket.</li><li><strong>Frames</strong>: Messages sent between the client and server in small chunks.</li></ul><h3>2. Setting Up WebSockets in Flutter</h3><p>To understand websocket implementation in flutter we will build a simple Flutter app where users can send and receive real-time messages using WebSockets.</p><h3>Add Dependencies</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*Bge77xJ89IrptLqdAEqs5Q.png" /><figcaption>we_socket_channel dependency flutter</figcaption></figure><p>Add the web_socket_channel package to your pubspec.yaml:</p><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>  web_socket_channel: ^2.4.0  # Latest version may differ</pre><h3>Connect to a WebSocket Server</h3><p>For this example, we will use a public echo server: wss://echo.websocket.org (it simply returns the same message we send, which means if you can see the sent message in the received message dialogue that means the handshake is successful. I know it got a bit confusing ).</p><h4>Creating a WebSocket Manager</h4><p>Create a new file websocket_service.dart inside the lib folder:</p><pre>import &#39;package:web_socket_channel/io.dart&#39;;<br>import &#39;package:web_socket_channel/web_socket_channel.dart&#39;;class WebSocketService {<br>  late WebSocketChannel channel;<br>// Initialize WebSocket connection<br>  void connect(String url) {<br>    channel = IOWebSocketChannel.connect(url);<br>  }<br>  // Send message to the WebSocket server<br>  void sendMessage(String message) {<br>    channel.sink.add(message);<br>  }<br>  // Listen for incoming messages<br>  Stream get messages =&gt; channel.stream;<br>  // Close the connection<br>  void disconnect() {<br>    channel.sink.close();<br>  }<br>}</pre><h3>Create the UI</h3><p>Modify lib/main.dart:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:web_socket_channel/io.dart&#39;;<br>import &#39;package:web_socket_channel/web_socket_channel.dart&#39;;<br><br>void main() {<br>  runApp(MyApp());<br>}<br>class MyApp extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      debugShowCheckedModeBanner: false,<br>      home: WebSocketScreen(),<br>    );<br>  }<br>}<br>class WebSocketScreen extends StatefulWidget {<br>  @override<br>  _WebSocketScreenState createState() =&gt; _WebSocketScreenState();<br>}<br>class _WebSocketScreenState extends State&lt;WebSocketScreen&gt; {<br>  final TextEditingController _controller = TextEditingController();<br>  late WebSocketChannel _channel;<br>  String receivedMessage = &quot;&quot;;<br>  @override<br>  void initState() {<br>    super.initState();<br>    _channel = IOWebSocketChannel.connect(&#39;wss://echo.websocket.org&#39;);<br>    _channel.stream.listen((message) {<br>      setState(() {<br>        receivedMessage = message;<br>      });<br>    });<br>  }<br>  void _sendMessage() {<br>    if (_controller.text.isNotEmpty) {<br>      _channel.sink.add(_controller.text);<br>    }<br>  }<br>  @override<br>  void dispose() {<br>    _channel.sink.close();<br>    super.dispose();<br>  }<br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(title: Text(&#39;Flutter WebSocket Demo&#39;)),<br>      body: Padding(<br>        padding: const EdgeInsets.all(16.0),<br>        child: Column(<br>          children: [<br>            TextField(<br>              controller: _controller,<br>              decoration: InputDecoration(labelText: &#39;Enter message&#39;),<br>            ),<br>            SizedBox(height: 10),<br>            ElevatedButton(<br>              onPressed: _sendMessage,<br>              child: Text(&#39;Send Message&#39;),<br>            ),<br>            SizedBox(height: 20),<br>            Text(&#39;Received: $receivedMessage&#39;),<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><h3>Explanation of the Code</h3><ul><li><strong>Initializing Connection</strong>: IOWebSocketChannel.connect(url) establishes a WebSocket connection.</li><li><strong>Sending Data</strong>: _channel.sink.add(message) sends data to the server.</li><li><strong>Receiving Data</strong>: stream.listen((message) {...}) listens for incoming messages.</li><li><strong>Closing Connection</strong>: _channel.sink.close() ensures proper cleanup.</li></ul><h3>Now just run your APP</h3><h3>WebSocket Security</h3><ul><li>Use wss:// instead of ws:// for encrypted communication.</li><li>Authenticate users before allowing WebSocket connections.</li><li>Implement message validation to prevent malicious payloads.</li></ul><h3>Assignment for You</h3><p>Once you successfully run the app, test you websocket knowledge further by adding these features into your app.</p><p>Try these:</p><ol><li>Modify the app to display a chat history.</li><li>Implement WebSocket reconnection if the connection is lost.</li><li>Replace the echo server with a real WebSocket backend.</li></ol><p>Hope you find this blog helpful.</p><p>Keep fluttering!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad873a499275" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WTF is Equatable Package in Flutter]]></title>
            <link>https://blog.devgenius.io/equatable-package-flutter-a9dd618d8d0d?source=rss-46a66af35978------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9dd618d8d0d</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[equatableflutter]]></category>
            <category><![CDATA[equatable-package]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <dc:creator><![CDATA[Ashutosh Yadav]]></dc:creator>
            <pubDate>Mon, 03 Feb 2025 11:21:05 GMT</pubDate>
            <atom:updated>2025-02-04T17:27:27.149Z</atom:updated>
            <content:encoded><![CDATA[<h4>An easy explanation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*5GWct-SHlaKY89VTuLL6Dw.png" /></figure><p>In Flutter, Equatable helps us avoid unnecessary state rebuilds by ensuring efficient equality comparisons. When using state management like BLoC, state changes are frequent, and Flutter rebuilds widgets when the state updates. By default, Dart checks object equality using memory reference (==), meaning two objects with the same data are considered different if they are stored at different memory locations.</p><p>Without Equatable</p><pre>class CounterState { <br>  final int count; CounterState(this.count);<br> }<br>emit(CounterState(1));<br>emit(CounterState(1)); // This will still trigger a rebuild</pre><p>Even though the values are the same, Flutter considers them different objects and rebuilds the UI unnecessarily.</p><p>Equatable package solves this issue. You need not write many lines of code just to tell Dart that these two are the same objects. Here is how to implement Equatable.</p><pre>flutter pub add equatable // terminal command</pre><pre>import &#39;package:equatable/equatable.dart&#39;;<br>class CounterState extends Equatable { <br><br>  final int count;<br>  const CounterState(this.count);<br><br>  @override<br>  List&lt;Object?&gt; get props =&gt; [count]; // Ensures equality based on count value<br> <br>}</pre><p>The code under the @override tells Flutter that if Objects have the same <em>count</em> property value ( lets suppose 2 ) then consider it as same.</p><p>Counter1= CounterState(3)</p><p>Counter2=CounterState(3)</p><p>then ;</p><p>Counter1==Counter2==true</p><h3>Why Does Dart Consider Objects as Different ?</h3><p>By default, Dart compares objects using <strong>reference equality</strong>. This means that two objects are considered different if they occupy different memory locations, even if their contents are the same.</p><h3>Under-the-Hood Concept: Heap Memory &amp; Object References</h3><p>When we create an object using new or directly like CounterState(1), Dart stores it in <strong>heap memory</strong>, and a reference (memory address) is assigned to it. When we compare objects using ==, Dart checks whether the two references point to the same memory location.</p><h3>Example Without Equatable</h3><pre><br>class CounterState {<br>  final int count;<br>  CounterState(this.count);<br>}</pre><pre>void main() {<br>  var state1 = CounterState(1);<br>  var state2 = CounterState(1);<br>  print(state1 == state2); // false ❌ Different memory locations<br>}</pre><p>Although state1 and state2 hold the same value (count = 1), they are stored at <strong>different memory addresses</strong>, so Dart considers them different.</p><h3>How Equatable Fixes This?</h3><p>The Equatable package overrides the == operator and hashCode, making Dart compare <strong>the actual properties</strong> instead of memory references.</p><h3>Example With Equatable</h3><pre><br>import &#39;package:equatable/equatable.dart&#39;;</pre><pre>class CounterState extends Equatable {<br>  final int count;<br>  const CounterState(this.count);<br>  @override<br>  List&lt;Object?&gt; get props =&gt; [count]; // Checks based on count value<br>}<br>void main() {<br>  var state1 = CounterState(1);<br>  var state2 = CounterState(1);<br>  print(state1 == state2); // true ✅ Same data, now considered equal<br>}</pre><p>Now, since Equatable overrides == to compare based on props, Dart knows both objects are <strong>logically the same</strong>.</p><p>Real Life App Scenarios where Unnecessary Rebuilt occurs.</p><h3>API Calls in News or E-commerce Apps</h3><p>Imagine a <strong>news app</strong> or an <strong>e-commerce app</strong> fetching articles or products from an API.</p><h3>🔴 Without Equatable</h3><pre>dart<br>CopyEdit<br>class NewsState {<br>  final List&lt;String&gt; articles;<br>  NewsState(this.articles);<br>}</pre><p>If the <strong>same articles</strong> are fetched again, Flutter will still rebuild the UI because it sees NewsState([...]) as a new object.</p><h3>✅ With Equatable</h3><pre>dart<br>CopyEdit<br>class NewsState extends Equatable {<br>  final List&lt;String&gt; articles;<br>  const NewsState(this.articles);</pre><pre>  @override<br>  List&lt;Object?&gt; get props =&gt; [articles];<br>}</pre><p>Now, if the list remains unchanged, Flutter avoids unnecessary UI rebuilds.</p><p>I hope you found this blog helpful.</p><p>Keep Fluttering!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9dd618d8d0d" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/equatable-package-flutter-a9dd618d8d0d">WTF is Equatable Package in Flutter</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My First Good-Looking Web Design Using Figma]]></title>
            <link>https://blog.devgenius.io/my-first-good-looking-web-design-using-figma-cc9eb5615fda?source=rss-46a66af35978------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc9eb5615fda</guid>
            <category><![CDATA[freelance-web-designer]]></category>
            <category><![CDATA[ui-ux-design]]></category>
            <category><![CDATA[website-designing]]></category>
            <category><![CDATA[figma]]></category>
            <category><![CDATA[website-design-services]]></category>
            <dc:creator><![CDATA[Ashutosh Yadav]]></dc:creator>
            <pubDate>Fri, 26 Jul 2024 10:00:09 GMT</pubDate>
            <atom:updated>2024-07-29T16:26:35.250Z</atom:updated>
            <content:encoded><![CDATA[<h4>Freelance Website Concept Design using Figma</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*ESwBjuiCZPqvHWEI6MGFbA.png" /><figcaption>Freelance Website Design Figma</figcaption></figure><p>As an app developer, my journey has often been filled with lines of code, endless debugging sessions, and the occasional celebration of successful app builds. However, I found myself yearning for a more creative outlet. While app development was intellectually stimulating, it wasn’t fulfilling my desire for artistic expression.</p><p>So, I decided to venture into app and web design, an area still within the tech world where I could blend creativity with functionality. This move felt logical because I could transform my designs into actual apps and websites, bridging the gap between creativity and code.</p><p>Switching gears from app development to web design was like discovering a new flavor of ice cream after a lifetime of vanilla. It was exciting, refreshing, and just what I needed. Armed with a sprinkle of curiosity and a dash of enthusiasm, I decided to embark on my first web design project using Figma.</p><p>But I didn’t just dive into Figma and start designing right away (though I did give that a try initially). Realizing I needed a structured approach, I enrolled in the <strong>Figma UI UX Design Essentials</strong> course on Udemy. Huge shoutout to Daniel Walter Scott for his excellent teaching! Over the span of about 10 days, I immersed myself in the course and completed my first app design project — a coffee app.</p><p>Having completed the course, I was eager to add more impressive projects to my portfolio. I decided to start with landing pages, designing around 4–5 of them to hone my skills. Once I felt confident, I moved on to designing complete websites. “Blink” is actually my third website design and, without a doubt, my best one so far.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*CA1SbA56_xS-pYSTnWllIg.png" /><figcaption>Freelance website design</figcaption></figure><h4>The Inspiration</h4><p>The idea to design a freelance website didn’t just pop out of thin air. I was inspired by the growing gig economy and the surge in demand for freelance platforms. But more importantly, I wanted to create something that resonated with both clients and freelancers — a bridge connecting talent with opportunity.I settled on the concept of “Blink” — a sleek, modern freelance platform designed to make hiring and finding work a breeze.</p><p>To kickstart my project, I turned to my trusty YouTube channel, a treasure of tutorials, tips, and tricks for budding designers like myself. The channel, run by the incredibly talented designer Jesse Showalter (huge shoutout to him), provided step-by-step guidance on creating a freelance website design. His videos helped me understand the best approach for designing a website, offering invaluable insights and techniques that I eagerly applied to my own project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*lL44A1L882v9LJ3PJXsiLA.png" /><figcaption>Freelance website design</figcaption></figure><h4>The Design Process</h4><p>The process began with sketching out rough wireframes, mapping the user journey, and identifying key features that would set my design apart. I wanted Blink to be intuitive, visually appealing, and packed with features that cater to both clients and freelancers. I looked into multiple freelancing websites that are there in the market and took inspiration from them.</p><p>Once the wireframes were ready, I dived into Figma, my digital canvas, where the magic happened. Figma’s user-friendly interface and powerful design tools made it easy to translate my ideas into stunning visuals. I meticulously crafted each element, from the navigation bar to the call-to-action buttons, ensuring that every component was cohesive and aligned with the overall aesthetic.</p><p>The homepage of Blink features a clean, modern design with a bold headline inviting users to “Find the right Freelancer for your Work.” The use of green and white hues creates a professional yet approachable vibe. Below the fold, I incorporated sections showcasing top talents, hiring options, and success stories from reputable organizations, adding credibility and trust to the platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*nf_itiFMnrhcnf7Orljhkg.png" /><figcaption>Freelance website design</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*MFw3jDGG6maackyRyNCXIA.png" /></figure><p>There were moments of pure joy when a design element clicked perfectly, and moments of frustration when I hit a creative block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*KFXxQckz4eykv_rmTmEW3A.png" /></figure><p>Seeing the final design come together was like witnessing a symphony of colors, shapes, and ideas harmonize into a beautiful masterpiece.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*1mGyH9SMKkRi1XSptvRk8A.png" /></figure><p>As I look at the final design of Blink, I feel a profound sense of accomplishment. It’s a reminder that with a little creativity, a lot of passion, and the right tools, we can create wonders.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/215/1*tSqVd-bd3L4eXeVd7MaZWg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*DwfAW6eeid930g28gE6CMw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*0LGGt_lJOfggjrc8NbRUBA.png" /><figcaption>Inspirations, Moodboard and Component page</figcaption></figure><h3>Conclusion</h3><p>If you’re an app developer looking to explore web design, or simply someone curious about the creative process, I hope my journey inspires you to take that first step. Embrace the challenges, celebrate the victories, and most importantly, enjoy every moment of the creative process.</p><p>Stay curious, stay creative, and be happy designing!</p><p>You can get this Figma design file by showing some support here <a href="https://buymeacoffee.com/ashu18/e/281154">https://buymeacoffee.com/ashu18/e/281154</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc9eb5615fda" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/my-first-good-looking-web-design-using-figma-cc9eb5615fda">My First Good-Looking Web Design Using Figma</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I coded an app after 2.5 MONTH-BREAK and it actually looks cool !]]></title>
            <link>https://medium.com/@ashutosh7379947493/i-coded-an-app-after-2-5-month-break-and-it-looks-cool-41a14554dca5?source=rss-46a66af35978------2</link>
            <guid isPermaLink="false">https://medium.com/p/41a14554dca5</guid>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[flutter-developer]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[mobile-apps]]></category>
            <category><![CDATA[figma]]></category>
            <dc:creator><![CDATA[Ashutosh Yadav]]></dc:creator>
            <pubDate>Thu, 27 Jun 2024 16:11:02 GMT</pubDate>
            <atom:updated>2024-07-25T08:37:11.078Z</atom:updated>
            <content:encoded><![CDATA[<h4>Minimal look Weather App using Flutter (source code available)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C0G77acP5OYLG9_OoIVSug.png" /><figcaption>Minimal look weather app</figcaption></figure><p>After exploring various technologies and fields to combat coding fatigue, I decided to return to coding after 2.5 months. My goal was to create something that looked simple yet cool at the same time. So, what did I build? A Weather App. I know, I know, it seems basic, but I needed to build something to get back into the groove, so why not a weather app? It’s easy, but at the same time, it gives the satisfaction of building something useful.</p><p>With temperatures in India soaring above 50 degrees, all eyes are on news channels and weather apps, making it the perfect time to build one. I aimed for a design that was more decent, with minimal color and fewer words. So, I opened up Figma (after a few months), started designing the UI, and somehow, it looked fine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*jsDUrdNzFYko0_qDw3X-XA.png" /></figure><p>So yeah, that&#39;s what I designed. I tried to make it look as simple as possible, with no colors and nothing fancy. Decent is Cool!</p><h4>Coding part :</h4><p>Now comes the hard part (although not so hard, it’s just a weather app, and you can probably find hundreds of tutorials on YouTube) — coding it. Quick tip: if you are planning to build an app, start with the workflow. There’s no need to go all fancy; just take a paper and jot down whatever you are planning to build. Always try to think of a complete app.</p><p>For example, consider an e-commerce app. What should be its basic layout?</p><ul><li>Homepage</li><li>Different Product and Category Search Screen</li><li>Product Detail Screen</li><li>Add to Cart Screen</li><li>Order Placed Screen</li></ul><p>Of course, there is much more to it, but planning this way will give you a sense of starting an app that has a fixed ending. This approach works for me. I used to get demotivated and procrastinate a lot whenever my project was not fully planned. Since this is just a basic weather app, there was no need to design a separate workflow.</p><h4>Breaking this project into parts :</h4><p>What I do is build the complete UI of the app similar to the design in Figma, and then move on to the services and API part. After that, I try different animations. There is no need to design and try different animations in Figma, as it can be time-consuming. Instead, try animations through the code itself once your app is working fine. Again, don’t stress over animations. I simply used the animate package for animations.</p><p>One more thing: dependencies and packages are lifesavers. Don’t hesitate to use them, especially in your learning phase.</p><h4>API part is fun :</h4><p>Once you have implemented any API into the app, there is no stopping. You will actually start to love app development when you start getting comfortable with APIs and Models/Services.</p><h4><strong>The actual code</strong> :</h4><p><strong>Dependencies: </strong>These are the dependencies that I have used</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*H6vFWIj7xPH231jj49YGuA.png" /></figure><p>The <strong>heart</strong> of this app -&gt; <strong>WeatherData services class page:</strong></p><pre>import &#39;dart:convert&#39;;<br><br>import &#39;package:basicweatherapp/constants.dart&#39;;<br>import &#39;package:geocoding/geocoding.dart&#39;;<br>import &#39;package:geolocator/geolocator.dart&#39;;<br>import &#39;package:http/http.dart&#39; as https;<br><br>class WeatherData {<br>  String? cityname;<br>  static const base_url = &quot;http://api.openweathermap.org/data/2.5/weather&quot;;<br>  Position? data;<br>  <br>// this method will return the current city name we are in<br>  Future&lt;String&gt; getcurrentcity() async {<br><br>//asking for location permission<br>    LocationPermission permission = await Geolocator.requestPermission();<br>    if (permission == LocationPermission.denied) {<br>      await Geolocator.requestPermission();<br>    }<br>// gives us the latitude and losngitude data for current location<br>    Position position = await Geolocator.getCurrentPosition(<br>        desiredAccuracy: LocationAccuracy.high);<br><br>    //this will give us the current city based on latitude and longitude info<br>    List&lt;Placemark&gt; placemark =<br>        await placemarkFromCoordinates(position.latitude, position.longitude);<br>    String? city = placemark[0].locality ?? &quot;Bahraich&quot;;<br>    return city;<br>  }<br><br>// return weather data based on the city we enter<br>  Future getWeatherReport(String city) async {<br>    https.Response response =<br>        await https.get(Uri.parse(&quot;$base_url?q=$city&amp;appid=$api&amp;units=metric&quot;));<br>    if (response.statusCode == 200) {<br>      var data = jsonDecode(response.body);<br>      return data;<br>    } <br>    else {<br>      throw Exception(&quot;Failed to load weather data&quot;);<br>    }<br>  }<br>}</pre><p>Remember, I have not used any Model just to make things easy to understand.</p><p>Here is how the data will look when the API is called successfully. I hope you have some knowledge of Maps and Lists.</p><pre> {<br>     &quot;coord&quot;: {<br>       &quot;lon&quot;: -0.13,<br>       &quot;lat&quot;: 51.51<br>     },<br>     &quot;weather&quot;: [<br>       {<br>         &quot;id&quot;: 300,<br>         &quot;main&quot;: &quot;Drizzle&quot;,<br>         &quot;description&quot;: &quot;light intensity drizzle&quot;,<br>         &quot;icon&quot;: &quot;09d&quot;<br>       }<br>     ],<br>     &quot;base&quot;: &quot;stations&quot;,<br>     &quot;main&quot;: {<br>       &quot;temp&quot;: 280.32,<br>       &quot;pressure&quot;: 1012,<br>       &quot;humidity&quot;: 81,<br>       &quot;temp_min&quot;: 279.15,<br>       &quot;temp_max&quot;: 281.15<br>     },<br>     &quot;visibility&quot;: 10000,<br>     &quot;wind&quot;: {<br>       &quot;speed&quot;: 4.1,<br>       &quot;deg&quot;: 80<br>     },<br>     &quot;clouds&quot;: {<br>       &quot;all&quot;: 90<br>     },<br>     &quot;dt&quot;: 1485789600,<br>     &quot;sys&quot;: {<br>       &quot;type&quot;: 1,<br>       &quot;id&quot;: 5091,<br>       &quot;message&quot;: 0.0103,<br>       &quot;country&quot;: &quot;GB&quot;,<br>       &quot;sunrise&quot;: 1485762037,<br>       &quot;sunset&quot;: 1485794875<br>     },<br>     &quot;id&quot;: 2643743,<br>     &quot;name&quot;: &quot;London&quot;,<br>     &quot;cod&quot;: 200<br>     }</pre><p><strong>Functions and Methods: </strong>Here are a total of 5 methods that I have used in this app with proper comments ( complete code is provided further in the post ). These methods are used in the Home screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*5uCqpbos9UYL0nZWz00TZQ.png" /></figure><p><strong>The Homescreen code:</strong></p><p>I know the code may look overwhelming at first glance but you will understand everything if you go through the entire code.</p><pre><br>import &#39;package:basicweatherapp/constants.dart&#39;;<br>import &#39;package:basicweatherapp/networkErrorPage.dart&#39;;<br><br>import &#39;package:basicweatherapp/weatherdata.dart&#39;;<br>import &#39;package:basicweatherapp/widgets/Drawercontent.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_animate/flutter_animate.dart&#39;;<br><br>class HomePage extends StatefulWidget {<br>  const HomePage({super.key});<br><br>  @override<br>  State&lt;HomePage&gt; createState() =&gt; _HomePageState();<br>}<br><br>class _HomePageState extends State&lt;HomePage&gt; {<br>  TextEditingController citycontroller = TextEditingController();<br>  WeatherData weatherData = WeatherData();<br><br>  String? city;<br>  double? temp;<br>  String? condition;<br>  String? country;<br>  bool isLoading = true; // Add this state variable<br><br><br>// for getting current location city weather data<br>  void fetchData() async {<br>    setState(() {<br>      isLoading = true; // Set loading to true when starting to fetch data<br>    });<br><br>    String cityname = await weatherData.getcurrentcity();<br><br>    try {<br>      final weather = await weatherData.getWeatherReport(cityname);<br>      setState(() {<br>        city = weather[&quot;name&quot;];<br>        temp = weather[&quot;main&quot;][&quot;temp&quot;];<br>        condition = weather[&quot;weather&quot;][0][&quot;main&quot;];<br>        country = weather[&quot;sys&quot;][&quot;country&quot;];<br>        isLoading = false; // Set loading to false when data is fetched<br>      });<br>    } catch (e) {<br>      setState(() {<br>        isLoading = false; // Set loading to false even if there&#39;s an error<br>      });<br>      Navigator.push(<br>        context,<br>        MaterialPageRoute(<br>          builder: (context) =&gt; NetworkErrorPage(<br>            retryCallback: fetchData,<br>          ),<br>        ),<br>      );<br>    }<br>  }<br><br>// for getting any search city weather data<br>  void getCityData(String searchCity) async {<br>    setState(() {<br>      isLoading = true; // Set loading to true when starting to fetch data<br>    });<br><br>    try {<br>      final weather = await weatherData.getWeatherReport(searchCity);<br>      setState(() {<br>        city = weather[&quot;name&quot;];<br>        temp = weather[&quot;main&quot;][&quot;temp&quot;];<br>        condition = weather[&quot;weather&quot;][0][&quot;main&quot;];<br>        country = weather[&quot;sys&quot;][&quot;country&quot;];<br>        isLoading = false; // Set loading to false when data is fetched<br>      });<br>    } catch (e) {<br>      setState(() {<br>        isLoading = false;<br><br>        Navigator.push(<br>          context,<br>          MaterialPageRoute(<br>            builder: (context) =&gt; NetworkErrorPage(<br>              retryCallback: fetchData,<br>            ),<br>          ),<br>        ); // Set loading to false even if there&#39;s an error<br>      });<br>    }<br>  }<br><br>// for displaying different message for different temperature range<br>  String getWeatherMessage(double? temp) {<br>    if (temp == null) return &quot;Loading...&quot;;<br><br>    if (temp &lt;= 0) {<br>      return &quot;Brrr... it&#39;s freezing! Stay warm!&quot;;<br>    } else if (temp &gt; 0 &amp;&amp; temp &lt;= 10) {<br>      return &quot;Quite chilly. Don&#39;t forget your jacket!&quot;;<br>    } else if (temp &gt; 10 &amp;&amp; temp &lt;= 20) {<br>      return &quot;Cool weather. Enjoy the fresh air!&quot;;<br>    } else if (temp &gt; 20 &amp;&amp; temp &lt;= 30) {<br>      return &quot;Warm and pleasant. Perfect for outdoor activities!&quot;;<br>    } else if (temp &gt; 30 &amp;&amp; temp &lt;= 40) {<br>      return &quot;Getting hot. Stay hydrated!&quot;;<br>    } else {<br>      return &quot;Extreme heat! Take precautions and stay cool.&quot;;<br>    }<br>  }<br><br>// this will open a bottomModelSheet to search different cities.<br>  void onTap() {<br>    showModalBottomSheet(<br>      context: context,<br>      builder: (context) {<br>        return SingleChildScrollView(<br>          keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,<br>          child: Column(<br>            children: [<br>              SizedBox(<br>                height: 40,<br>              ),<br>              Padding(<br>                padding: EdgeInsets.symmetric(horizontal: 30),<br>                child: TextField(<br>                  controller: citycontroller,<br>                  decoration: InputDecoration(<br>                    hintStyle: TextStyle(<br>                      color: Colors.grey,<br>                      fontWeight: FontWeight.w300,<br>                    ),<br>                    hintText: &#39;enter city...&#39;,<br>                    prefixIcon: Image.asset(<br>                      &quot;images/city.png&quot;,<br>                    ),<br>                    enabled: true,<br>                    enabledBorder: OutlineInputBorder(),<br>                    contentPadding: EdgeInsets.all(12),<br>                  ),<br>                ),<br>              ),<br>              SizedBox(<br>                height: 20,<br>              ),<br>              Padding(<br>                padding: EdgeInsets.only(right: 25),<br>                child: Row(<br>                  mainAxisAlignment: MainAxisAlignment.end,<br>                  children: [<br>                    GestureDetector(<br>                      onTap: () {<br>                        Navigator.pop(context);<br>                        setState(() {<br>                          getCityData(citycontroller.text);<br>                        });<br>                      },<br>                      child: Hero(<br>                        tag: &quot;search&quot;,<br>                        child: Image.asset(<br>                          &quot;images/search.png&quot;,<br>                          height: 30,<br>                          width: 30,<br>                        ),<br>                      ),<br>                    )<br>                  ],<br>                ),<br>              ),<br>              SizedBox(height: MediaQuery.of(context).size.height * 0.23),<br>              Image.asset(&quot;images/cities.png&quot;),<br>              SizedBox(<br>                height: 20,<br>              )<br>            ],<br>          ),<br>        );<br>      },<br>    );<br>  }<br><br>// this method will return different &quot;image path&quot; as string <br>  String getWeatherIcon(String? maincondition) {<br>    if (maincondition == null) return &quot;images/sunny.png&quot;;<br><br>    switch (maincondition.toLowerCase()) {<br>      case &quot;clouds&quot;:<br>      case &quot;fog&quot;:<br>      case &quot;dust&quot;:<br>      case &quot;mist&quot;:<br>      case &quot;haze&quot;:<br>        return &quot;images/clouds.png&quot;;<br><br>      case &quot;rain&quot;:<br>      case &quot;drizzle&quot;:<br>      case &quot;shower rain&quot;:<br>        return &quot;images/rain.png&quot;;<br><br>      case &quot;thunderstand&quot;:<br>        return &quot;images/thunderstorm.png&quot;;<br><br>      case &quot;clear&quot;:<br>        return &quot;images/sunny.png&quot;;<br><br>      default:<br>        return &quot;images/sunny.png&quot;;<br>    }<br>  }<br><br>  WeatherData data = WeatherData();<br><br>  @override<br>  void initState() {<br>    // TODO: implement initState<br>    super.initState();<br>    fetchData();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    Size size = MediaQuery.of(context).size;<br>    return Scaffold(<br>      drawer: Drawer(<br>        child: DrawerContent(),<br>        width: size.width * 0.5,<br>      ).animate().fadeIn(duration: 1.seconds),<br>      appBar: AppBar(<br>        actions: [<br>          Padding(<br>            padding: EdgeInsets.only(right: 10),<br>            child: InkWell(<br>              onTap: () {<br>                fetchData();<br>              },<br>              child: Icon(<br>                Icons.location_on_outlined,<br>                size: 30,<br>              ).animate().fadeIn(duration: 1.seconds),<br>            ),<br>          )<br>        ],<br>      ),<br>      body: isLoading ? buildLoadingIndicator() : showUi(),<br>    );<br>  }<br><br>  Widget buildLoadingIndicator() {<br>    return Center(<br>      child: Column(<br>        mainAxisAlignment: MainAxisAlignment.center,<br>        children: [<br>          Text(<br>            &quot;loading weather data..&quot;,<br>            style: TextStyle(<br>              fontSize: 20,<br>              fontWeight: FontWeight.w300,<br>            ),<br>          ),<br>          SizedBox(<br>            height: 10,<br>          ),<br>          CircularProgressIndicator(<br>            color: Colors.black,<br>            strokeWidth: 1.5,<br>          )<br>        ],<br>      ),<br>    );<br>  }<br><br>  Widget showUi() {<br>    Size size = MediaQuery.of(context).size;<br>    return Padding(<br>      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),<br>      child: SingleChildScrollView(<br>        child: Column(<br>          children: [<br>            SizedBox(<br>              height: 15,<br>            ),<br>            Image.asset(&quot;images/city.png&quot;)<br>                .animate()<br>                .fadeIn(duration: 1.seconds),<br>            SizedBox(<br>              height: 10,<br>            ),<br>            Text(<br>              city ?? &quot;&quot;,<br>              style: TextStyle(<br>                fontSize: 25,<br>                fontWeight: FontWeight.w300,<br>              ),<br>            ).animate().fadeIn(duration: 1.seconds),<br>            Text(<br>              country ?? &quot; &quot;,<br>              style: TextStyle(<br>                fontSize: 15,<br>                fontStyle: FontStyle.italic,<br>                fontWeight: FontWeight.w300,<br>              ),<br>            ).animate().fadeIn(duration: 1.seconds),<br>            SizedBox(<br>              height: 15,<br>            ),<br>            Row(<br>              children: [<br>                Padding(<br>                  padding: EdgeInsets.only(left: 20),<br>                  child: Image.asset(<br>                    getWeatherIcon(condition),<br>                  ),<br>                ).animate().fadeIn(duration: 1.seconds),<br>                SizedBox(width: 40),<br>                Column(<br>                  children: [<br>                    Row(<br>                      children: [<br>                        Text(<br>                          temp?.toString() ?? &quot; &quot;,<br>                          style: style<br>                        ).animate().fadeIn(duration: 1.seconds),<br>                        Text(<br>                          &quot; °C&quot;,<br>                          style: style<br>                        ).animate().fadeIn(duration: 1.seconds),<br>                      ],<br>                    ),<br>                    Text(<br>                      condition ?? &quot; &quot;,<br>                      style: const TextStyle(<br>                        fontSize: 15,<br>                        fontStyle: FontStyle.italic,<br>                        fontWeight: FontWeight.w300,<br>                      ),<br>                    ).animate().fadeIn(duration: 1.seconds),<br>                  ],<br>                ),<br>              ],<br>            ),<br>            SizedBox(<br>              height: size.height * 0.12,<br>            ),<br>            Text(<br>              getWeatherMessage(temp),<br>              style: TextStyle(<br>                fontSize: 25,<br>                fontWeight: FontWeight.w300,<br>              ),<br>            )<br>                .animate()<br>                .fadeIn(duration: 1.seconds)<br>                .then(delay: 1000.ms)<br>                .slide(),<br>            SizedBox(height: size.height * 0.06),<br>            Image.asset(&quot;images/cities.png&quot;)<br>                .animate()<br>                .fadeIn(duration: 1.seconds),<br>            SizedBox(height: size.height * 0.07),<br>            InkWell(<br>                onTap: onTap,<br>                child: Hero(<br>                    tag: &quot;search&quot;, child: Image.asset(&quot;images/search.png&quot;))),<br>            SizedBox(height: 5),<br>            GestureDetector(<br>              onTap: onTap,<br>              child: Text(<br>                &#39;search other city &#39;,<br>                style: TextStyle(<br>                  fontSize: 20,<br>                  fontStyle: FontStyle.italic,<br>                  fontWeight: FontWeight.w300,<br>                ),<br>              ).animate().fadeIn(duration: 1.seconds),<br>            ),<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>And just like that, your minimal-look weather app is built! You can tweak its features and animations according to your preferences. Don’t forget to use other weather data that OpenWeatherMap.org provides, like wind speed, humidity, forecast, etc., in your app and try to be creative.</p><blockquote>If you want to get the complete source code along with the icons and all the UI components used in this app. You can find it here:<br><a href="https://buymeacoffee.com/ashu18/e/271237">https://buymeacoffee.com/ashu18/e/271237</a></blockquote><p>Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41a14554dca5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter & Firebase: Login, Signup + Auth Gateway]]></title>
            <link>https://blog.devgenius.io/flutter-firebase-login-and-signup-auth-gateway-e2efc8301f6f?source=rss-46a66af35978------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2efc8301f6f</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Ashutosh Yadav]]></dc:creator>
            <pubDate>Sun, 31 Mar 2024 06:51:11 GMT</pubDate>
            <atom:updated>2024-04-02T17:26:12.020Z</atom:updated>
            <content:encoded><![CDATA[<h4>Auto Login existing user</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bwzuuPONyRdhKfOmWo51rQ.png" /></figure><p>So this post is all about Flutter app authentication using Firebase, auto sign-in, and its importance and a little bit of humor.</p><h4><strong>Login &amp; Signup and its importance for a newly born app developer like you, yes you.</strong></h4><p>Just adding login and signup features into our app feels like starting a new million-dollar app idea, with the thought of selling your app users&#39; data or simply spying on them makes us feel so powerful, but hold on, it&#39;s just a simple login and signup feature, relax.</p><h4>Auto Login</h4><p>Now that you snapped out of your evil dreams, let’s think about how to keep our users logged in even after closing the app so that they need not to enter their details again and again, for this, we will make use of <strong>FirebaseAuth.authStateChanges()</strong> method, don&#39;t worry we will understand this how later in the post.</p><h4>Let’s start:</h4><p>So first let’s look at the dependencies that are required.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*yuCuZlYrG7jADl51CK9dyQ.png" /></figure><h4>Authentication Services Class</h4><p>So after importing all the required dependencies, we will create an Authentication service class file inside which we will put all the logic for creating a new user, signing in an existing user, and also how to sign out the user from the app. Here is the code :</p><pre>import &#39;package:firebase_auth/firebase_auth.dart&#39;;<br><br>class AuthServices {<br><br>  // FirebaseAuth instance<br><br>  FirebaseAuth _firebaseAuth = FirebaseAuth.instance;<br><br>  // sign in<br><br>  Future&lt;UserCredential&gt; signInMethod(String email, String password) async {<br>    try {<br>      UserCredential userCredential = await _firebaseAuth<br>          .signInWithEmailAndPassword(email: email, password: password);<br>      return userCredential;<br>    } on FirebaseAuthException catch (e) {<br>      throw (e.toString());<br>    }<br>  }<br><br>  // sign up<br><br>  Future&lt;UserCredential&gt; signUpMethod(String email, String password) async {<br>    try {<br>      UserCredential userCredential = await _firebaseAuth<br>          .createUserWithEmailAndPassword(email: email, password: password);<br>      return userCredential;<br>      <br>    } on FirebaseAuthException catch (e) {<br>      throw (e.toString());<br>    }<br>  }<br><br>  // signout<br><br>  Future&lt;void&gt; signout() async {<br>    return await _firebaseAuth.signOut();<br>  }<br>}</pre><p>So first I have created a FirebaseAuth instance <strong>_firebaseAuth</strong> which acts as an entry point to the firebase authentication. Now through _firebaseAuth we have created three different methods namely <strong>signInMethod() </strong>to sign-in existing user<strong>,</strong> <strong>signUpMethod()</strong> for registering a new user, and lastly <strong>signOut()</strong> method for logging out the user. Also be clear that <strong>signInMethod()</strong> and <strong>signUpMthod()</strong> will return <strong>Future</strong> of type <strong>UserCredential. </strong>We will make use of these methods in the login and register pages by creating an object of class AuthServices. So lets look at Login and Register screen.</p><h4>Login Screen</h4><p>Here is the code for our login screen and don&#39;t worry about that <strong>toggle()</strong> function, it is just a <strong>required</strong> method that needs to be passed in the <strong>LoginPage </strong>class so that we can toggle from login to register page in case the user is not an existing member of your app and similarly we will require this<strong> toggle() </strong>method in the <strong>RegisterPage</strong> also in case user is already a member of your app. So let&#39;s look at the login code.</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:project_login/authservices/authservices.dart&#39;;<br><br>class LoginPage extends StatefulWidget {<br>  final void Function() toggle;<br>  const LoginPage({super.key, required this.toggle});<br><br>  @override<br>  State&lt;LoginPage&gt; createState() =&gt; _LoginPageState();<br>}<br><br>class _LoginPageState extends State&lt;LoginPage&gt; {<br>  TextEditingController emailcontroller = TextEditingController();<br>  TextEditingController passwordController = TextEditingController();<br><br>  AuthServices authServices = AuthServices();<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: Text(&quot;Login page &quot;),<br>      ),<br>      body: Center(<br>        child: Column(<br>          children: [<br>            Padding(<br>              padding: const EdgeInsets.all(20.0),<br>              child: TextField(<br>                  controller: emailcontroller,<br>                  decoration: InputDecoration(<br>                    hintText: &quot;email..&quot;,<br>                    enabledBorder: OutlineInputBorder(),<br>                  )),<br>            ),<br>            SizedBox(<br>              height: 20,<br>            ),<br>            Padding(<br>              padding: const EdgeInsets.all(20),<br>              child: TextField(<br>                controller: passwordController,<br>                decoration: InputDecoration(<br>                  hintText: &quot;password..&quot;,<br>                  enabledBorder: OutlineInputBorder(),<br>                ),<br>              ),<br>            ),<br>            SizedBox(<br>              height: 20,<br>            ),<br>            ElevatedButton(<br>                onPressed: () {<br>                  authServices.signInMethod(<br>                      emailcontroller.text, passwordController.text);<br>                },<br>                child: Text(&quot;Login&quot;)),<br>            SizedBox(<br>              height: 20,<br>            ),<br>            Row(<br>              mainAxisAlignment: MainAxisAlignment.center,<br>              children: [<br>                Text(&quot;Not a member &quot;),<br>                TextButton(<br>                    onPressed: widget.toggle,<br>                    child: Text(<br>                      &quot;Register&quot;,<br>                      style: TextStyle(fontWeight: FontWeight.bold),<br>                    ))<br>              ],<br>            )<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>And here is the RegisterPage code :</p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>import &#39;package:project_login/authservices/authservices.dart&#39;;<br><br>class Register extends StatefulWidget {<br>  const Register({super.key, required this.toggle});<br>  final void Function() toggle;<br><br>  @override<br>  State&lt;Register&gt; createState() =&gt; _LoginPageState();<br>}<br><br>class _LoginPageState extends State&lt;Register&gt; {<br>  TextEditingController emailcontroller = TextEditingController();<br>  TextEditingController passwordController = TextEditingController();<br>  AuthServices authServices = AuthServices();<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: Text(&quot;Register page &quot;),<br>      ),<br>      body: Center(<br>        child: Column(<br>          mainAxisAlignment: MainAxisAlignment.center,<br>          children: [<br>            Padding(<br>              padding: const EdgeInsets.all(20.0),<br>              child: TextField(<br>                  controller: emailcontroller,<br>                  decoration: InputDecoration(<br>                    hintText: &quot;email..&quot;,<br>                    enabledBorder: OutlineInputBorder(),<br>                  )),<br>            ),<br>            SizedBox(<br>              height: 20,<br>            ),<br>            Padding(<br>              padding: const EdgeInsets.all(20.0),<br>              child: TextField(<br>                controller: passwordController,<br>                decoration: InputDecoration(<br>                  hintText: &quot;password..&quot;,<br>                  enabledBorder: OutlineInputBorder(),<br>                ),<br>              ),<br>            ),<br>            SizedBox(<br>              height: 20,<br>            ),<br>            ElevatedButton(<br>                onPressed: () {<br>                  authServices.signUpMethod(<br>                      emailcontroller.text, passwordController.text);<br>                },<br>                child: Text(&quot;sign-up&quot;)),<br>            Row(<br>              mainAxisAlignment: MainAxisAlignment.center,<br>              children: [<br>                Text(&quot;Already a member ? &quot;),<br>                TextButton(<br>                  onPressed: widget.toggle,<br>                  child: Text(<br>                    &quot;Login&quot;,<br>                    style: TextStyle(fontWeight: FontWeight.bold),<br>                  ),<br>                )<br>              ],<br>            )<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>Now we will create a Page through which we can handle all this toggling stuff which will eventually return the required screen i.e. login to our signup that is why we will call this page LoginOrSignup, what a genius! . Here is the code.</p><pre>import &#39;dart:math&#39;;<br><br>import &#39;package:flutter/foundation.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:project_login/pages/login.dart&#39;;<br>import &#39;package:project_login/pages/register.dart&#39;;<br><br>class LoginOrRegister extends StatefulWidget {<br>  const LoginOrRegister({super.key});<br><br>  @override<br>  State&lt;LoginOrRegister&gt; createState() =&gt; _LoginOrRegisterState();<br>}<br><br>class _LoginOrRegisterState extends State&lt;LoginOrRegister&gt; {<br>  bool loginPage = true;<br><br>  void toggle() {<br>    setState(() {<br>      loginPage = !loginPage;<br>    });<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    if (loginPage) {<br>      return LoginPage(<br>        toggle: toggle,<br>      );<br>    } else {<br>      return Register(<br>        toggle: toggle,<br>      );<br>    }<br>  }<br>}</pre><p>Here is the code for the Authentication gate which helps in finding out whether the user is already signed in or needs to sign-in/sign-up by making use of Stream data. Lets look at the code.</p><pre><br><br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:project_login/pages/login.dart&#39;;<br>import &#39;package:project_login/authservices/loginorsignup.dart&#39;;<br>import &#39;package:project_login/pages/mainscreen.dart&#39;;<br><br>class AuthGate extends StatefulWidget {<br>  const AuthGate({super.key});<br><br>  @override<br>  State&lt;AuthGate&gt; createState() =&gt; _AuthGateState();<br>}<br><br>class _AuthGateState extends State&lt;AuthGate&gt; {<br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: StreamBuilder(<br>        stream: FirebaseAuth.instance.authStateChanges(),<br>        builder: (context, snapshot) {<br>          if (snapshot.hasData) {<br>            return HomeScreen();<br>          } else {<br>            return LoginOrRegister();<br>          }<br>        },<br>      ),<br>    );<br>  }<br>}</pre><p>Here you can see , in the body of Scaffold I have passed the StreamBuilder widget which asks for the source of stream and a builder. Now for the stream I have provided it with <strong>FirebaseAuth.instance.authStateChanges()</strong> which holds the current users logged in status in the form of snapshot, and if this snapshot does not have any data, it means user either have to login or signup and if snapshot has some data it means the user he has already signed in to the app and will be directed to the <strong>MainScreen()</strong> or <strong>Homepage</strong> of your app. You can create a basic homepage for now , something like this.</p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>class HomeScreen extends StatelessWidget {<br>  const HomePage({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: Center(<br>        child: Text(&quot;YaYY... you are logged in&quot;),<br>      ),<br>    );<br>  }<br>}</pre><h4>Main.dart()</h4><p>Here is the code of the <strong>main.dart </strong>file :</p><pre>import &#39;package:firebase_core/firebase_core.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:project_login/authservices/authgate.dart&#39;;<br>import &#39;package:project_login/firebase_options.dart&#39;;<br><br>void main() async {<br>  WidgetsFlutterBinding.ensureInitialized();<br><br>  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);<br>  runApp(const MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      debugShowCheckedModeBanner: false,<br>      home: AuthGate(),<br>    );<br>  }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2efc8301f6f" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/flutter-firebase-login-and-signup-auth-gateway-e2efc8301f6f">Flutter &amp; Firebase: Login, Signup + Auth Gateway</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Food-Delivery-App using  FLUTTER & FIREBASE: Full Source Code]]></title>
            <link>https://blog.devgenius.io/food-delivery-app-using-flutter-firebase-full-source-code-1f4986a370aa?source=rss-46a66af35978------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f4986a370aa</guid>
            <category><![CDATA[flutter-beginner]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[app-source-code]]></category>
            <category><![CDATA[flutter-project]]></category>
            <dc:creator><![CDATA[Ashutosh Yadav]]></dc:creator>
            <pubDate>Sat, 23 Mar 2024 16:06:13 GMT</pubDate>
            <atom:updated>2024-04-08T17:39:47.524Z</atom:updated>
            <content:encoded><![CDATA[<h3>Food-Delivery-App using FLUTTER &amp; FIREBASE</h3><h3>Full Source Code</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*OXSTBJvemL_k7XZ6JPE6cQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*_oe-FXgQ1NEg4G__T8MgDQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*9kNdbzaTxmmmIvyIRIPgcw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*Ac8plfLHbDotyaxdm6Pbpw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*J8z4LqRg5UHz12ctRfXoXw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*xEoolg6PsxUtXFCurYJ6qg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*-72EbUhB3p0-NcHWRhrs7g.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*0ARg0Ub1VrN7WlwLrahYmA.jpeg" /></figure><h3>Project Overview:</h3><p>This app is pre-built, fully functional, and ready to use right out of the box. It comes with email authentication and a robust backend powered by Firebase.</p><p>With this app, users can easily create an account, explore the menu, add items to their cart, and securely input their card payment details. Once the order is placed, Firebase ensures real-time updates and saves the order for seamless tracking.</p><p>Plus, users get a detailed receipt summarizing their order for easy reference.</p><h3>Perfect Project for Skill Building</h3><ol><li>Comprehensive Features: The app encompasses a wide range of functionalities commonly found in ecommerce and delivery apps, making it an ideal project for developers to build and expand their skill set.</li><li>Scalability and Customization: The modular structure of the source code allows developers to understand how to build scalable apps and customize features according to specific project requirements.</li></ol><h3>Project folders:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/179/1*55I_OIWJ_E6ex4Ly1ig3sw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/193/1*Eki_S8Zn3LEaxoY6g-uQRA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*FbRSgIC2o5NpAzUixljXOQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/1*9eGlmgh5xyjjdu1v6y95Vg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/1*9kE6UQFzVum5nB21CtX_0w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/193/1*mz6_bA6Yic_0Fte7TeNP5Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/1*sAn2IJCrVHzQ_oSfV_FdaQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YH6zABXcadrocM1v7MwIkA.png" /><figcaption>Firebase Firestore data</figcaption></figure><h3>Source Code :</h3><p><a href="https://www.buymeacoffee.com/ashu18/e/235265">Food-Delivery-App (Source code)</a></p><p>Purchasing the source code of our Food Delivery App is a smart investment for developers learning Flutter. It offers a practical, comprehensive, and challenging project that can significantly accelerate your learning journey and equip you with the skills needed to excel in Flutter app development.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7PWivfz0pPY862r2nkg2YA.jpeg" /></figure><p>Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f4986a370aa" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/food-delivery-app-using-flutter-firebase-full-source-code-1f4986a370aa">Food-Delivery-App using  FLUTTER &amp; FIREBASE: Full Source Code</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Secure Password Generator in Golang]]></title>
            <link>https://blog.devgenius.io/building-a-secure-password-generator-in-golang-c7a834349086?source=rss-46a66af35978------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7a834349086</guid>
            <category><![CDATA[golang-project]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[password-generator]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[golang-development]]></category>
            <dc:creator><![CDATA[Ashutosh Yadav]]></dc:creator>
            <pubDate>Sun, 10 Mar 2024 12:24:15 GMT</pubDate>
            <atom:updated>2024-03-11T17:15:21.484Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In today’s digital world, ensuring the security of our online accounts is paramount. One way to enhance security is by using strong, unique passwords for each account. However, generating such passwords can be a tedious task. To address this challenge, I’ve developed a customizable password generator tool in Go that allows users to create strong passwords tailored to their preferences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VD4S4AD2eHFRxI7k9Ce30w.png" /><figcaption>golang</figcaption></figure><h3>Project Overview</h3><p>Creating secure passwords involves a careful balance between randomness and complexity. My goal was to create a password generator tool that strikes this balance effectively while giving users control over the password’s length and character composition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*8wdQVh2pmVT6-DztvY0z6Q.png" /></figure><h3>Implementation</h3><p>The implementation of the password generator tool revolves around user input and randomization techniques. Here’s a breakdown of the key components:</p><h3>User Input</h3><p>The tool prompts the user to specify the desired password length and whether they want to include lowercase letters, uppercase letters, numbers, and special characters in the password.</p><h3>Randomization</h3><p>The tool utilizes Go’s math/rand package along with the current time as a seed to generate random passwords. It selects characters randomly from the specified character sets to create diverse and unpredictable passwords.</p><h3>Password Validation</h3><p>This is the most important concept in terms of password generation. <strong>To ensure the generated passwords meet the specified criteria (e.g., including at least one of each character type), the tool includes validation checks before finalizing the password.</strong></p><h3>Code Overview</h3><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;math/rand&quot;<br> &quot;time&quot;<br>)<br><br>const lowercaseLetters = &quot;abcdefghijklmnopqrstuvwxyz&quot;<br>const uppercaseLetters = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;<br>const numbers = &quot;0123456789&quot;<br>const specialChars = &quot;!@#$%^&amp;*-{};&#39;.&lt;&gt;/?`&quot;<br><br>func main() {<br> var useLetters, useNumbers, useSpecialChars, useUppercaseLetters bool<br><br> var useLetters_, useNumbers_, useSpecialChars_, useUppercaseLetters_ string<br><br> fmt.Println(&quot;Enter the size of your password&quot;)<br> var length int<br> fmt.Scanln(&amp;length)<br><br> fmt.Println(&quot;do you want lowerCase in your password : y/n&quot;)<br> fmt.Scanln(&amp;useLetters_)<br> if useLetters_ == &quot;y&quot; || useLetters_ == &quot;Y&quot; {<br>  useLetters = true<br> } else {<br>  useLetters = false<br> }<br><br> fmt.Println(&quot;do you want numbers in your password : y/n&quot;)<br> fmt.Scanln(&amp;useNumbers_)<br> if useNumbers_ == &quot;y&quot; || useNumbers_ == &quot;Y&quot; {<br>  useNumbers = true<br> } else {<br>  useNumbers = false<br> }<br> fmt.Println(&quot;do you want special characters in your password : y/n&quot;)<br><br> fmt.Scanln(&amp;useSpecialChars_)<br> if useSpecialChars_ == &quot;y&quot; || useSpecialChars_ == &quot;Y&quot; {<br>  useSpecialChars = true<br> }<br><br> fmt.Println(&quot;do you want upperCase letters in your password: y/n&quot;)<br><br> fmt.Scanln(&amp;useUppercaseLetters_)<br> if useUppercaseLetters_ == &quot;y&quot; || useSpecialChars_ == &quot;Y&quot; {<br>  useUppercaseLetters = true<br> }<br><br> password := passwordGenerate(length, useLetters, useUppercaseLetters, useNumbers, useSpecialChars)<br> fmt.Println(&quot;Generated password:&quot;, password)<br><br>}<br><br>func passwordGenerate(length int, useLetter bool, uppercaseletters bool, useNumbers bool, useSpecial bool) string {<br> var characterSet string<br><br> <br> if useLetter {<br>  characterSet += lowercaseLetters<br>  if uppercaseletters {<br>   characterSet += uppercaseLetters<br>  }<br> }<br> if useNumbers {<br>  characterSet += numbers<br> }<br><br> if useSpecial {<br>  characterSet += specialChars<br> }<br><br> if len(characterSet) == 0 {<br>  panic(&quot;Please select at least one character set&quot;) // Ensure at least one set is chosen<br> }<br><br> bytes := make([]byte, length)<br><br> bt := tryingPasswords(bytes, characterSet)<br><br> if length &lt;= 2 {<br>  tryingPasswords(bytes, characterSet)<br> }<br><br> if useLetter == true &amp;&amp; useNumbers == true &amp;&amp; useSpecial == true &amp;&amp; uppercaseletters == true {<br>  for checkLetters(bt) == false || checkNumbers(bt) == false || checkSpecials(bt) == false || uppercaseletters == false {<br>   tryingPasswords(bytes, characterSet)<br>  }<br> }<br> if useLetter == true &amp;&amp; useNumbers == true &amp;&amp; uppercaseletters == true {<br>  for checkLetters(bt) == false || checkNumbers(bt) == false || uppercaseletters == false {<br>   tryingPasswords(bytes, characterSet)<br>  }<br> }<br><br> if useLetter == true &amp;&amp; useSpecial == true &amp;&amp; uppercaseletters == true {<br>  for checkLetters(bt) == false || checkSpecials(bt) == false || uppercaseletters == false {<br>   tryingPasswords(bytes, characterSet)<br>  }<br> }<br> if useNumbers == true &amp;&amp; useSpecial == true &amp;&amp; uppercaseletters == true {<br>  for checkNumbers(bt) == false || checkSpecials(bt) == false || uppercaseletters == false {<br>   tryingPasswords(bytes, characterSet)<br>  }<br> }<br><br> if useSpecial == true &amp;&amp; uppercaseletters == true {<br>  for checkSpecials(bt) == false || uppercaseletters == false {<br>   tryingPasswords(bytes, characterSet)<br>  }<br> }<br><br> if useNumbers == true &amp;&amp; uppercaseletters == true {<br>  for checkNumbers(bt) == false || checkUpperCase(bt) {<br>   tryingPasswords(bytes, characterSet)<br>  }<br> }<br><br> return string(bytes)<br>}<br><br>func tryingPasswords(bytes []byte, characterSet string) []byte {<br> source := rand.NewSource(time.Now().UnixNano())<br> r := rand.New(source)<br> for i := range bytes {<br>  randomIndex := byte(r.Intn(len(characterSet) - 1))<br>  bytes[i] = characterSet[randomIndex]<br><br> }<br> return bytes<br>}<br><br>func checkNumbers(char []byte) bool {<br> for i := range numbers {<br>  for j := 0; j &lt; len(char); j++ {<br>   if numbers[i] == char[j] {<br>    return true<br>   }<br>  }<br> }<br><br> return false<br>}<br><br>func checkLetters(char []byte) bool {<br> for i := range lowercaseLetters {<br>  for j := 0; j &lt; len(char); j++ {<br>   if lowercaseLetters[i] == char[j] {<br>    return true<br>   }<br>  }<br> }<br><br> return false<br>}<br><br>func checkSpecials(char []byte) bool {<br> for i := range specialChars {<br>  for j := 0; j &lt; len(char); j++ {<br>   if specialChars[i] == char[j] {<br>    return true<br>   }<br>  }<br> }<br><br> return false<br>}<br><br>func checkUpperCase(char []byte) bool {<br> for i := range uppercaseLetters {<br>  for j := 0; j &lt; len(char); j++ {<br>   if uppercaseLetters[i] == char[j] {<br>    return true<br>   }<br>  }<br> }<br><br> return false<br>}</pre><h3>Conclusion</h3><p>With the customizable password generator tool I’ve developed, users can easily create strong and secure passwords tailored to their specific requirements. By providing control over password length and character types, this tool offers flexibility without compromising security.</p><h3><strong>Github link :</strong></h3><h4><a href="https://github.com/Kryptonite-18/passwordGenerator_go.git">https://github.com/Kryptonite-18/passwordGenerator_go.git</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7a834349086" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/building-a-secure-password-generator-in-golang-c7a834349086">Building a Secure Password Generator in Golang</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Text Analyzer Program in Go: A Beginner’s Guide]]></title>
            <link>https://blog.devgenius.io/text-analyzer-program-in-go-a-beginners-guide-34ed8efa38cf?source=rss-46a66af35978------2</link>
            <guid isPermaLink="false">https://medium.com/p/34ed8efa38cf</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[text-analyzer-golang]]></category>
            <category><![CDATA[golang-project]]></category>
            <dc:creator><![CDATA[Ashutosh Yadav]]></dc:creator>
            <pubDate>Sat, 09 Mar 2024 07:39:12 GMT</pubDate>
            <atom:updated>2024-03-11T17:15:25.549Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vW3j4KdDKZ4I68FBz9303g.png" /></figure><p>This tutorial guides you through creating a text analyzer program in Go, perfect for those new to the language. I’ll break down the code step-by-step, explaining its functionality in plain language and providing explanations for core concepts.</p><p><strong>What we’ll build :</strong></p><p>The program will analyze a text file you provide, calculating:</p><ul><li>Character count: The total number of characters in the text.</li><li>Word count: The total number of words (separated by spaces or newlines).</li><li>Line count: The total number of lines in the text.</li><li>Word frequency: How many times each word appears in the text.</li></ul><p>You will also learn how to make a .txt file in your project directory and reading the text within the file. The input will be taken from your terminal itself, so let’s delve into the code.</p><h3>Some Basic Steps :</h3><p>Open your code editor (ex- vsCode), select your project&#39;s directory, and create a <em>main.go</em> file. Inside this file write package main and create a func main. That’s all for the starters</p><pre>package main<br><br>func main(){<br>  ....<br>}</pre><p>These are the imports that we will be working with:</p><pre>import (<br>    &quot;fmt&quot;<br>    &quot;os&quot;<br>    &quot;strings&quot;<br>)</pre><p>Ok so our entire project will be divided into two parts namely : <br>1) <strong><em>main function</em></strong> (all the codes inside <em>func main()</em> ) <br>2) <strong><em>Helper function</em></strong></p><p>These will be our Helper functions :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*lUTKNkpWPVpLI6O-0lVtlA.png" /></figure><p>let&#39;s look at the code of each helper function one by one :</p><ol><li>writeFile(filename string, s string) error<br><strong>Functionality:</strong> This function writes the provided text (s) to a new file named filename.</li></ol><pre>func writeFile(filename string, s string) error {<br>  // Convert the string to a byte slice for writing to the file<br>  data := []byte(s)<br>  // Write the data to the file with file permissions set to 0666 (read and write for everyone)<br>  err := os.WriteFile(filename, data, 0666)<br>  if err != nil {<br>    // Handle errors (e.g., file creation issues)<br>    fmt.Printf(&quot;Some thing went wrong !! %v&quot;, err)<br>    os.Exit(1) // Exit the program with an error code<br>  }<br>  return err<br>}</pre><p><strong>Explanation:</strong></p><ul><li>The function takes two arguments: filename (string) and s (string).</li><li>It converts the s string to a byte slice data using []byte(s). This is because os.WriteFile it expects a byte slice for writing to the file.</li><li>It writes the data to the specified filename using os.WriteFile. The file permissions are set to 0666, allowing everyone to read and write.</li><li>If an error occurs during writing (e.g., file permission issues), the function prints the error message, exits the program with an error code (1), and returns the error.</li></ul><p><strong>2. </strong>readFromFile(filename string) string</p><p><strong>Functionality:</strong> This function reads the content of a file (filename) and returns it as a string.</p><pre>func readFromFile(filename string) string {<br>  // Read the entire file contents into a byte slice<br>  data, err := os.ReadFile(filename)<br>  if err != nil {<br>    fmt.Println(&quot;Error reading file:&quot;, err)<br>    os.Exit(1) // Exit the program with an error code<br>  }<br>  // Convert the byte slice to a string<br>  return string(data)<br>}</pre><p><strong>Explanation:</strong></p><ul><li>The function takes one argument: filename (string).</li><li>It reads the entire content of the file using os.ReadFile and stores it in a byte slice data.</li><li>If there’s an error reading the file, the function prints the error message, exits the program with an error code (1), and returns an empty string.</li><li>It converts the data byte slice to a string using string(data) and returns the string.</li></ul><p><strong>3. </strong>countCharacters(text string) int</p><p><strong>Functionality:</strong> This function calculates and returns the total number of characters in the provided text (text).</p><pre>func countCharacters(text string) int {<br>  // The length of the string represents the character count<br>  return len(text)<br>}</pre><p><strong>Explanation:</strong></p><ul><li>The function takes one argument: text (string).</li><li>It uses the len function on the text string to get its length. The length represents the total number of characters in the string.</li><li>It returns the character count (integer).</li></ul><p><strong>4. </strong>countWords(text string) int</p><p><strong>Functionality:</strong> This function calculates and returns the total number of words in the provided text (text).</p><pre>func countWords(text string) int {<br>  // Split the text into words using spaces or newlines as delimiters<br>  words := strings.Fields(text)<br>  // The length of the resulting slice represents the word count<br>  return len(words)<br>}</pre><p><strong>Explanation:</strong></p><ul><li>The function takes one argument: text (string).</li><li>It uses strings.Fields(text) to split the text into a slice of strings (words), considering spaces or newlines as word separators.</li><li>It returns the length of the words slice, which represents the total number of words in the text.</li></ul><p><strong>5. </strong>countLines(text string) int</p><p><strong>Functionality:</strong> This function calculates and returns the total number of lines in the provided text (text).</p><pre>func countLines(text string) int {<br>  // Split the text into lines using newlines as delimiters<br>  lines := strings.Split(text, &quot;\n&quot;)<br>  // The length of the resulting slice represents the line count<br>  return len(lines)<br>}</pre><p><strong>Explanation:</strong></p><ul><li>It splits the text string into a slice of strings (lines) using strings.Split(text, &quot;\n&quot;). The delimiter here is &quot;\n&quot;, representing the newline character.</li><li>It returns the length of the lines slice, which represents the total number of lines in the text.</li></ul><p><strong>6. </strong>countFrequency(s []string) map[string]int</p><p><strong>Functionality:</strong> This function calculates the frequency (number of occurrences) of each word in the provided slice of words (s) and returns a map that stores the word as the key and its frequency as the value.</p><pre>func countFrequency(s []string) map[string]int {<br>  // Create a map to store word frequencies (word: frequency)<br>  m := make(map[string]int)<br>  for _, word := range s {<br>    // Check if the word already exists in the map<br>    count, ok := m[word]<br>    if !ok {<br>      // If the word is not found, initialize its count to 1<br>      count = 1<br>    } else {<br>      // If the word is found, increment its count<br>      count++<br>    }<br>    // Update the word&#39;s count in the map<br>    m[word] = count<br>  }<br>  return m<br>}</pre><p><strong>Explanation:</strong></p><ul><li>The function takes one argument: s ([]string), a slice containing the words to analyze.</li><li>It creates a map m of type map[string]int using make(map[string]int). This map will store the word (string) as the key and its frequency (count, integer) as the value.</li><li>It iterates through the s slice using a for loop.</li><li>Inside the loop, it uses range s to get the current word in each iteration.</li><li>It checks if the current word already exists in the map using m[word].</li><li>If the word is not found (!ok), it initializes its count to 1 in the map using m[word] = 1.</li><li>If the word is found (ok), it retrieves the existing count using count and increments it by 1 using count++.</li><li>Finally, it updates the word&#39;s count in the map using m[word] = count.</li><li>The function returns the frequency map m.</li></ul><p><strong>7. </strong>printingFrequnecy(m map[string]int, s []string)</p><p><strong>Functionality:</strong> This function iterates through the word frequency map (m) and the word slice (s) to print each word, its frequency, and a separator for a clear presentation. It also uses a visited map (visited) to avoid printing the same word multiple times.</p><pre>func printingFrequnecy(m map[string]int, s []string) {<br>  // Create a map to keep track of visited words (to avoid duplicates)<br>  visited := make(map[string]bool)<br>  fmt.Println(&quot;Printing frequency of each word : &quot;)<br>  for _, word := range s {<br>    // Check if the word has already been printed<br>    if !visited[word] {<br>      // Print the word, its frequency, and a separator<br>      fmt.Printf(&quot;%s =&gt; %d time(s)  ,  &quot;, word, m[word])<br>      // Mark the word as visited to avoid duplicates<br>      visited[word] = true<br>    }<br>  }<br>  fmt.Println() // Print a newline for better formatting<br>}</pre><p><strong>Explanation:</strong></p><ul><li>The function takes two arguments: m (map[string]int), the frequency map, and s ([]string), the original word slice.</li><li>It creates a map visited of type map[string]bool using make(map[string]bool). This map will track whether a word has already been printed to avoid duplicates.</li><li>It prints a heading “Printing frequency of each word : “.</li><li>It iterates through the s slice using a for loop.</li><li>Inside the loop, it checks if the current word has already been visited using !visited[word].</li><li>If the word has not been visited, it prints the word, its frequency from the m map using m[word], and a separator using fmt.Printf with appropriate formatting.</li><li>It then marks the word as visited in the visited map using visited[word] = true.</li><li>Finally, it prints a newline (fmt.Println()) for better formatting at the end of the loop.</li></ul><p>I know I know, it is difficult to digest all this, but don&#39;t worry all you need is to understand what&#39;s going on.</p><p>Now let&#39;s look at the code inside <em>main function.</em></p><pre>func main() {<br> filename := &quot;myText.txt&quot;<br><br> _, err := os.Stat(filename)<br> if err == nil {<br>  os.Remove(filename)<br> }<br><br> writeFile(&quot;myText.txt&quot;, strings.Join(os.Args[1:], &quot; &quot;))<br><br> text := readFromFile(&quot;myText.txt&quot;)<br> s := strings.Fields(text)<br><br> characterCount := countCharacters(text)<br> wordCount := countWords(text)<br> lineCount := countLines(text)<br> m := countFrequency(s)<br><br> printingFrequnecy(m, s)<br><br> fmt.Printf(&quot; \nCharacter count: %d\n&quot;, characterCount)<br> fmt.Printf(&quot;Word count: %d\n&quot;, wordCount)<br> fmt.Printf(&quot;Line count: %d\n&quot;, lineCount)<br>}</pre><p>I know , after reading all those helper functions, it is very easy to connect all the dots inside the main function, all I did was use the helper functions and nothing else, but just for the sake of project completion lets go through the code inside this main function.</p><p><strong>i) File handling :</strong></p><pre>filename := &quot;myText.txt&quot;<br><br>_, err := os.Stat(filename)<br>if err == nil {<br>    os.Remove(filename)<br></pre><p>We start by defining a filename for our text file. If the file already exists, we remove it to avoid appending duplicate content.</p><p><strong>ii) Writing Text to File:</strong></p><pre>writeFile(&quot;myText.txt&quot;, strings.Join(os.Args[1:], &quot; &quot;))</pre><p>Here, we write the text provided as command-line arguments to the file. We use strings.Join to concatenate all arguments into a single string.</p><p><strong>iii) Reading Text from File:</strong></p><pre>text := readFromFile(&quot;myText.txt&quot;)</pre><p>We read the content of the file back into a string variable named text using the readFromFile function.</p><p><strong>iv) Analyzing Text:</strong></p><pre>characterCount := countCharacters(text)<br>wordCount := countWords(text)<br>lineCount := countLines(text)<br>m := countFrequency(s)</pre><p>We calculate various statistics such as character count, word count, line count, and word frequency using helper functions.</p><p><strong>v) Printing Results:</strong></p><pre>printingFrequnecy(m, s)<br><br>fmt.Printf(&quot; \nCharacter count: %d\n&quot;, characterCount)<br>fmt.Printf(&quot;Word count: %d\n&quot;, wordCount)<br>fmt.Printf(&quot;Line count: %d\n&quot;, lineCount)</pre><p>Finally, we print the results of our analysis, including word frequency and other statistics.</p><p>This is end look of the project</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ikA6oTkTxQVQn9yCh1EeJQ.png" /></figure><p>you can see how our code prints the frequency of each word, total count of characters, word count, and line count.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4pwh2aZET4ryAI0QBetIpQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34ed8efa38cf" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/text-analyzer-program-in-go-a-beginners-guide-34ed8efa38cf">Text Analyzer Program in Go: A Beginner’s Guide</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Goroutines and Channels in Go: A Beginner’s Guide]]></title>
            <link>https://medium.com/@ashutosh7379947493/goroutines-and-channels-in-go-a-beginners-guide-a8acac799212?source=rss-46a66af35978------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8acac799212</guid>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[concurrency-programming]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[golang-developer]]></category>
            <category><![CDATA[goroutines-and-channels]]></category>
            <dc:creator><![CDATA[Ashutosh Yadav]]></dc:creator>
            <pubDate>Thu, 07 Mar 2024 15:47:58 GMT</pubDate>
            <atom:updated>2024-03-07T15:47:58.975Z</atom:updated>
            <content:encoded><![CDATA[<p>Go is a programming language that supports concurrency, which means it can run multiple tasks at the same time. Concurrency can make programs faster, more responsive, and more scalable. But how does Go achieve concurrency? The answer is through two key features: goroutines and channels.</p><figure><img alt="Golang goroutine and channel" src="https://cdn-images-1.medium.com/max/1024/1*M8TCn_MPCDwDY7L8wZynIA.png" /></figure><h3>What are goroutines?</h3><p>Goroutines are lightweight threads of execution that are managed by the Go runtime. They are cheap to create and can run simultaneously with other goroutines within the same process. You can think of them as independent functions that can communicate with each other. Found it a bit difficult to understand lets ease it for you.</p><p>Let’s imagine you’re at a restaurant, and there’s a chef (your program) preparing multiple dishes simultaneously. Now, each dish represents a task that the chef needs to complete. In traditional programming, the chef would prepare one dish at a time, and while waiting for one dish to cook, they can’t start working on another dish until the first one is done. This can be inefficient because there’s a lot of waiting around. Now, imagine if the chef could work on multiple dishes at the same time. They start cooking one dish, then while it’s cooking, they start preparing another dish, and so on. This is essentially what a goroutine does in Go programming language. I hope its more clear now. Now to create a goroutine, you just need to use the go keyword before a function call. For example:</p><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br>    &quot;time&quot;<br>)<br><br>func main() {<br>    go hello() // create a goroutine that calls hello<br>    fmt.Println(&quot;main function&quot;)<br>}<br><br>func hello() {<br>    fmt.Println(&quot;Hello, world!&quot;)<br>    time.Sleep(2 * time.Second) // pause for 2 seconds<br>    fmt.Println(&quot;Hello, again!&quot;)<br>}</pre><p>Output: you can get two type of outputs in your terminal (mostly the 1st type)</p><pre>1) main function<br>     <br>       or <br><br>2) main function<br>   Hello, world!<br>   Hello, again!</pre><p>As soon as we use go in front of our function hello() , a child (helper) goroutine is formed which will take care of the return of the hello(), whereas our main goroutine will move forward to the next line of code thinking that its work is over at the hello() line. As soon as the main goroutine reaches the end line code of the main function, your code stops executing and this is the downside of using go routines without synchronization technique.</p><p>Although Golang is very smart as compared to other languages, but in case of goroutines it gets fooled.Notice that the main function does not wait for the goroutine to finish. This is because goroutines are asynchronous, meaning they do not block the execution of the main function. If you want to wait for a goroutine to finish, you need to use a synchronization mechanism, and this is where we need Channels.</p><h3>What are channels?</h3><p>Channels are a way for goroutines to communicate and synchronize their execution. A channel is a data transfer pipe where data can be written into or read from. One goroutine can send data to a channel, and another goroutine can receive data from the same channel. Yeah yeah I know, let me explain in simpler words.</p><p>Imagine you have two workers in a factory, one is a painter, and the other is a builder. The builder makes walls, and the painter paints them. Now, how do they communicate? They might use a conveyor belt to pass the walls from the builder to the painter. In Go, channels are like that conveyor belt. They allow different parts of your program (goroutines) to communicate by passing values between them.</p><p>To create a channel, you need to use the make function with the chan keyword and the type of the data that the channel will hold. For example:</p><pre>c := make(chan int) // create a channel of type int</pre><p>To send data to a channel, you need to use the &lt;- operator. For example:</p><pre>c &lt;- 42 // send 42 to the channel c</pre><p>To receive data from a channel, you also need to use the &lt;- operator. For example:</p><pre>x := &lt;-c // receive data from the channel c and assign it to x</pre><p>Sending and receiving data from a channel is blocking, meaning it will wait until the other side is ready. This way, channels can be used to synchronize the execution of goroutines.</p><p>Let’s modify the previous program to use a channel to wait for the goroutine to finish:</p><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br>    &quot;time&quot;<br>)<br><br>func main() {<br>    c := make(chan bool) // create a channel of type bool<br>    go hello(c) // create a goroutine that calls hello and passes the channel<br>    fmt.Println(&quot;main function&quot;)<br>    &lt;-c // wait for the goroutine to send data to the channel<br>    fmt.Println(&quot;main function ends&quot;)<br>}<br><br>func hello(c chan bool) {<br>    fmt.Println(&quot;Hello, world!&quot;)<br>    time.Sleep(2 * time.Second) // pause for 2 seconds<br>    fmt.Println(&quot;Hello, again!&quot;)<br>    c &lt;- true // send true to the channel<br>}</pre><p>Output:</p><pre>main function<br>Hello, world!<br>Hello, again!<br>main function ends</pre><p>Notice that the main function waits for the goroutine to finish before exiting. This is because the channel blocks the execution until both sides are ready.</p><h3>Conclusion</h3><p>Goroutines and channels are powerful features of Go that enable concurrency and communication. Goroutines are lightweight threads of execution that can run simultaneously and independently. Channels are data transfer pipes that can synchronize the execution of goroutines. By using goroutines and channels, you can write concurrent programs that are fast, responsive, and scalable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8acac799212" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter + Firebase : Basic(CRUD) App Tutorial]]></title>
            <link>https://medium.com/@ashutosh7379947493/flutter-firebase-basic-crud-app-tutorial-562663186e41?source=rss-46a66af35978------2</link>
            <guid isPermaLink="false">https://medium.com/p/562663186e41</guid>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[flutter-beginner]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter-tutorial]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Ashutosh Yadav]]></dc:creator>
            <pubDate>Fri, 02 Feb 2024 13:38:55 GMT</pubDate>
            <atom:updated>2024-02-02T13:38:55.833Z</atom:updated>
            <content:encoded><![CDATA[<h3>Flutter + Firebase : Basic(CRUD) App Tutorial</h3><h4>Build your first CRUD-featured app (NoteTaking).</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q6ep4cMTHNQi6AV0LETB0Q.png" /></figure><p>First, create a flutter project using the <strong>flutter create &lt;name of project&gt;</strong> command and then type code &lt;project_name&gt; to open in vsCode or create using Android Studio.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*deKbt5iUPG5kAtEmKm96Sg.png" /><figcaption>creating a new flutter project</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*NSltSdLAo9QsQBXmxaxNBQ.png" /></figure><p>Your project will open in the vsCode with all boilerplate code written. Before changing anything let&#39;s add our app with the firebase. Enter the following code in the terminal.</p><pre>firebase login</pre><pre>dart pub global activate flutterfire_cli</pre><p>Now that your Flutterfire cli is now activated go ahead and create a new project in your Firebase console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*OOxmyzxRJQcEOptpXvCJ2g.png" /></figure><p>After you have created your Firebase project, head back to vsCode and write the following command in the terminal.</p><pre>flutterfire configure</pre><p>All your Firebase projects will be shown in the terminal, select the name of your project and continue, and then it will ask you for which device you want your app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*aD0j3BMeacRtDZwrUpxKpA.png" /></figure><p>select your devices as you like.</p><p>And that&#39;s it, your app is now Firebase-ready. Let&#39;s move forward to the coding part now.</p><p>Come to <strong><em>main.dart</em></strong>, we have to make some changes here, so that our app gets initialized with Firebase. This is like telling our main() function that it is linked with Firebase now using <strong><em>await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform),</em></strong></p><pre>import &#39;package:basic_crud_app/firebase_options.dart&#39;;<br>import &#39;package:basic_crud_app/homepage.dart&#39;;<br>import &#39;package:firebase_core/firebase_core.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br><br>void main() async {<br>  WidgetsFlutterBinding.ensureInitialized();<br>  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);<br>  runApp(const MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return const MaterialApp(<br>      debugShowCheckedModeBanner: false,<br>      home: HomePage(),<br>    );<br>  }<br>}</pre><p>Your <strong>pubspec.yaml</strong> file dependencies should look like this ( you can <strong>ignore</strong> <strong>google_fonts </strong>package).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*-DaT7HFLbj7t3-z4YrnH9Q.png" /></figure><p>Now let&#39;s create a homepage screen. which will just return the scaffold only for now.</p><p>Now we will move on to create a FireBase services class in new file which will contain all the logic of <strong>creating/reading/updating/and deleting</strong> the notes. So just create a <strong>firebase_services.dart</strong> file in the <strong>lib </strong>folder. Your <strong>lib</strong> folder should look something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*8SPXWivSpSqco9CNMVwuqw.png" /></figure><p>Now go on to firebase_services.dart and create a class named <strong>FirestoreServices</strong> or anything similar and this class will contain methods for creating /reading/updating and deleting. I have tried my best to explain what&#39;s going. Do read the //comments I have provided in the code, this will make you understand the code more easily.</p><pre>import &#39;package:cloud_firestore/cloud_firestore.dart&#39;;<br><br>class FirestoreServices {<br>  // creating a collection named &#39;notes&#39; under which<br>  // all the new notes will be stored. <br>  final CollectionReference? notes =<br>      FirebaseFirestore.instance.collection(&#39;notes&#39;);<br><br>  // adding a new note logic within our &#39;notes&#39; collection <br>  // by creating 2 fields named<br>  // &#39;note&#39; (note we enter) and &#39;timestamp&#39;(time of entry)<br>  <br>  Future&lt;void&gt; addNote(String note) {<br>    return notes!.add(<br>      {&#39;note&#39;: note, &#39;timestamp&#39;: Timestamp.now()},<br>    );<br>  }<br><br>  // reading data within the &#39;notes&#39; collection<br>  // we have made earlier in the form of snapshots<br><br>  Stream&lt;QuerySnapshot&gt; showNotes() {<br>    final notesStream =<br>        notes!.orderBy(&#39;timestamp&#39;, descending: true).snapshots();<br><br>    return notesStream;<br>  }<br><br>  // update the data by accessing the particular<br>  // docId of the note which we want to update.<br><br>  Future&lt;void&gt; updateNotes(String docId, String newNote, Timestamp time) {<br>    return notes!.doc(docId).update({&#39;note&#39;: newNote, &#39;timestamp&#39;: time});<br>  }<br><br>  // delete the data by accessing the particular<br>  // which we want to delete.<br><br>  Future&lt;void&gt; deleteNote(String docId) {<br>    return notes!.doc(docId).delete();<br>  }<br>}</pre><p>Let&#39;s understand the code inside the FirestoreServices class, first of all, we have created a collection named ‘notes’ which of type <strong>CollectionReference</strong> provided by the <strong>core_firestore</strong> package. This is like an entry point inside your <strong>firebase</strong> or to be more accurate <strong>firestore database</strong>.</p><p>Let&#39;s look at all the methods one by one inside our class FirestoreServices.</p><ol><li><strong><em>addNote() </em></strong>(for adding new note)</li></ol><pre>// adding a new note logic within our &#39;notes&#39; collection <br>  // by creating 2 fields named<br>  // &#39;note&#39; (note we enter) and &#39;timestamp&#39;(time of entry)<br>  <br>  Future&lt;void&gt; addNote(String note) {<br>    return notes!.add(<br>      {&#39;note&#39;: note, &#39;timestamp&#39;: Timestamp.now()},<br>    );<br>  }</pre><p>If you look at the <strong>addNote()</strong> method, what you will find is nothing but adding a new ‘note’ and ‘timestamp’ field in your ‘notes’ collection. Let me show you how it looks inside the <strong>Firestore</strong> <strong>database</strong> this will clear it up much more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z5k80wJa5-ar2qqd8TCjdA.png" /><figcaption>Firestore Database (collection-&gt;documents -&gt;fields)</figcaption></figure><p>As you can see inside the<strong> ‘notes’ </strong>collection we have our documents (having <strong>unique docId</strong> ) and when we click on any documents we can see different <strong>fields</strong> we have assigned. I think this will help you to understand what’s happening inside Firestore.</p><p>Let&#39;s move forward and look at the showNotes() function which will allow our app to show different notes on the screen.</p><p>2. <strong><em>showNotes() </em></strong>(for showing notes on the app screen)</p><pre>// reading data within the &#39;notes&#39; collection<br>  // we have made earlier in the form of snapshots<br><br>  Stream&lt;QuerySnapshot&gt; showNotes() {<br>    final notesStream =<br>        notes!.orderBy(&#39;timestamp&#39;, descending: true).snapshots();<br><br>    return notesStream;<br>  }</pre><p>As you can see<strong> showNotes()</strong> will return <strong>Stream&lt;QuerySnapshots&gt;</strong> which means it will return<strong> stream </strong>(continuous flow) of <strong>snapshot</strong> (document) from your database, and we have ordered it in such way that the latest document will shown first, so that you can see your newly added note on the top of the screen.</p><p>3.<strong><em> updateNotes() </em></strong>(for updating your changes/editing notes)</p><pre>// update the data by accessing the particular<br>  // docId of the note which we want to update.<br><br>  Future&lt;void&gt; updateNotes(String docId, String newNote, Timestamp time) {<br>    return notes!.doc(docId).update({&#39;note&#39;: newNote, &#39;timestamp&#39;: time});<br>  }</pre><p>As you can see this method requires 3 arguments namely doctId, newNote, and time, which we will pass when we call this method at the homepage() inside the edit button widget’s<strong> onPressed(){}</strong> function (you will find the code ahead). Now why we need these arguments ? Simply because we should have access to note which we are going to edit, and that can be done by passing docId. As you can see in the image provided, we can only access the particular note fields by clicking on the <strong>docId</strong>. I hope it&#39;s clear. The <strong>newNote </strong>is passed so that we can use newNote as the updated note for the <strong>‘notes’</strong> field, similarly we pass time to update the ‘timestamp’ with the initial time because we do not want to edit time also when we update our note or you can just ignore the time argument and create a field as <strong>‘timestamp’ : Timestamp.now().</strong> I know it’s a bit tricky to understand but everything will get clear when you look at the homePage() file code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z5k80wJa5-ar2qqd8TCjdA.png" /></figure><p>4.<strong><em> deleteNote() </em></strong>(for deleting the note)</p><p>Finally for deleting, we just access the docId of the note you want to delete and simply use <strong>.delete() </strong>method to remove it from your database.</p><p>That&#39;s all you have to know to build a basic CRUD app. I will provide you the homepage() code.</p><pre>import &#39;dart:ui&#39;;<br><br>import &#39;package:basic_crud_app/firebase_services.dart&#39;;<br>import &#39;package:cloud_firestore/cloud_firestore.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter/widgets.dart&#39;;<br>import &#39;package:google_fonts/google_fonts.dart&#39;;<br><br>class HomePage extends StatefulWidget {<br>  const HomePage({super.key});<br><br>  @override<br>  State&lt;HomePage&gt; createState() =&gt; _HomePageState();<br>}<br><br>class _HomePageState extends State&lt;HomePage&gt; {<br>  TextEditingController controller = TextEditingController();<br>  FirestoreServices firestoreServices = FirestoreServices();<br>  void showNoteBox(String? textToedit, String? docId, Timestamp? time) {<br>    showDialog(<br>      context: context,<br>      builder: (context) {<br>        if (textToedit != null) {<br>          controller.text = textToedit;<br>        }<br>        return AlertDialog(<br>          title: Text(<br>            &quot;Add note&quot;,<br>            style: GoogleFonts.alexandria(fontSize: 16),<br>          ),<br>          content: TextField(<br>            decoration: InputDecoration(hintText: &#39;Note here...&#39;),<br>            style: GoogleFonts.alexandria(),<br>            controller: controller,<br>          ),<br>          actions: [<br>            ElevatedButton(<br>              onPressed: () {<br>                if (docId == null) {<br>                  firestoreServices.addNote(controller.text);<br>                } else {<br>                  firestoreServices.updateNotes(docId, controller.text, time!);<br>                }<br>                controller.clear();<br>                Navigator.pop(context);<br>              },<br>              child: Text(<br>                &#39;add&#39;,<br>                style: GoogleFonts.alexandria(),<br>              ),<br>            )<br>          ],<br>        );<br>      },<br>    );<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      backgroundColor: Colors.purple[50],<br>      appBar: AppBar(<br>        centerTitle: true,<br>        backgroundColor: Colors.purple[50],<br>        title: Text(<br>          &quot;C R U D&quot;,<br>          style: GoogleFonts.alexandria(),<br>        ),<br>      ),<br>      floatingActionButton: FloatingActionButton.extended(<br>        backgroundColor: Colors.purple[100],<br>        label: Text(<br>          &#39;add&#39;,<br>          style: GoogleFonts.alexandria(fontSize: 18),<br>        ),<br>        icon: Icon(Icons.add),<br>        onPressed: () async {<br>          showNoteBox(null, null, null);<br>        },<br>      ),<br>      body: StreamBuilder(<br>        stream: FirestoreServices().showNotes(),<br>        builder: (context, snapshot) {<br>          if (snapshot.hasData) {<br>            List noteList = snapshot.data!.docs;<br>            return ListView.builder(<br>              itemCount: noteList.length,<br>              itemBuilder: (context, index) {<br>                DocumentSnapshot document = noteList[index];<br>                String docId = document.id;<br>                Map&lt;String, dynamic&gt; data =<br>                    document.data() as Map&lt;String, dynamic&gt;;<br>                String note = data[&#39;note&#39;];<br>                Timestamp time = data[&#39;timestamp&#39;];<br>                return Column(<br>                  children: [<br>                    Padding(<br>                      padding: const EdgeInsets.symmetric(horizontal: 14),<br>                      child: ListTile(<br>                        contentPadding: EdgeInsets.all(16),<br>                        shape: RoundedRectangleBorder(<br>                            borderRadius: BorderRadius.circular(16)),<br>                        tileColor: Colors.purple[100],<br>                        title: Padding(<br>                          padding: const EdgeInsets.all(8.0),<br>                          child: Text(<br>                            note,<br>                            style: GoogleFonts.alexandria(<br>                                textStyle: TextStyle(<br>                                    color: Colors.purple[800], fontSize: 19)),<br>                          ),<br>                        ),<br>                        trailing: Column(<br>                          children: [<br>                            Row(<br>                              mainAxisSize: MainAxisSize.min,<br>                              children: [<br>                                IconButton(<br>                                  color: Colors.purple[400],<br>                                  icon: Icon(Icons.edit),<br>                                  onPressed: () {<br>                                    showNoteBox(note, docId, time);<br>                                  },<br>                                ),<br>                                IconButton(<br>                                    color: Colors.purple[400],<br>                                    onPressed: () {<br>                                      firestoreServices.deleteNote(docId);<br>                                    },<br>                                    icon: Icon(Icons.delete))<br>                              ],<br>                            ),<br>                          ],<br>                        ),<br>                      ),<br>                    ),<br>                    Padding(<br>                      padding: const EdgeInsets.symmetric(<br>                          horizontal: 14, vertical: 4),<br>                      child: Row(<br>                        mainAxisAlignment: MainAxisAlignment.end,<br>                        children: [<br>                          Text(<br>                            time.toDate().hour.toString(),<br>                            style: const TextStyle(<br>                                color: Colors.purple,<br>                                fontWeight: FontWeight.bold),<br>                          ),<br>                          Text(&quot;:&quot;),<br>                          Text(<br>                            time.toDate().minute.toString(),<br>                            style: const TextStyle(<br>                                color: Colors.purple,<br>                                fontWeight: FontWeight.bold),<br>                          ),<br>                        ],<br>                      ),<br>                    )<br>                  ],<br>                );<br>              },<br>            );<br>          } else {<br>            return Center(<br>              child: Text(&quot;Nothing to show...add notes&quot;),<br>            );<br>          }<br>        },<br>      ),<br>    );<br>  }<br>}</pre><p>I know the code is horrible at first glance but worry not, its pretty simple. The only thing you need to know in this code is the <strong>StreamBuilder()</strong> which is the <strong>body</strong> of our <strong>Scaffold. So StreamBuilder() r</strong>equires a <strong>stream</strong> source (which in our case is from<strong> showNotes() </strong>method from our <strong>FirestoreService class) </strong>and a<strong> builder </strong>that will return build our screen to reflect<strong> </strong>our<strong> note </strong>and in our app the builder is <strong>ListviewBuilder</strong>.</p><p>This is what your app would look like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vCUpMQt7G31iv-N7TkZtbw.jpeg" /><figcaption>Basic Notetaking app</figcaption></figure><p>source code: <a href="https://github.com/Kryptonite-18/crud_app.git">https://github.com/Kryptonite-18/crud_app.git</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=562663186e41" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>