<?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 Eman Yaqoob on Medium]]></title>
        <description><![CDATA[Stories by Eman Yaqoob on Medium]]></description>
        <link>https://medium.com/@emanyaqoob?source=rss-c74b278e156a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QaolrC_wcKaIEo1fjn_EIg.jpeg</url>
            <title>Stories by Eman Yaqoob on Medium</title>
            <link>https://medium.com/@emanyaqoob?source=rss-c74b278e156a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 19:20:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@emanyaqoob/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[Why learn RAG?]]></title>
            <link>https://medium.com/@emanyaqoob/why-learn-rag-3c7d489e1fa4?source=rss-c74b278e156a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c7d489e1fa4</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[mls]]></category>
            <dc:creator><![CDATA[Eman Yaqoob]]></dc:creator>
            <pubDate>Mon, 29 Jun 2026 13:00:02 GMT</pubDate>
            <atom:updated>2026-06-29T13:00:02.553Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_GbzO-MN_0XRFArdsnNRow.png" /></figure><h3>RAG Explained Simply: Embeddings, Vector Databases, Better Retrieval, Evaluation, and the Basic Components You Need to Know</h3><p>Artificial intelligence feels powerful when it can answer questions, summarize information, and write useful content. But there is one problem: a normal AI model does not automatically know your private documents, company policies, product details, website content, or latest business information. It can only answer from what it was trained on, plus whatever information you give it in the prompt.</p><p>This is where <strong>RAG</strong>, or <strong>Retrieval-Augmented Generation</strong>, becomes important.</p><p>RAG is one of the most useful concepts in modern AI development because it connects a language model with your own data. Instead of asking the AI to guess, RAG first searches your documents, finds the most relevant information, and then gives that information to the AI so it can produce a grounded answer.</p><p>In simple words, RAG means: <strong>search first, answer second</strong>.</p><p>Imagine you are sitting in a library. Someone asks you a question about a company policy. You do not guess the answer from memory. You first open the right file, find the correct section, read the important paragraph, and then answer. A RAG system works in the same way.</p><p>It helps AI become more reliable, useful, and connected to real information.</p><h3>Why RAG Is Important</h3><p>A large language model can answer many general questions, but it may struggle when the question depends on specific information. For example, if someone asks, “What are your delivery charges?” the AI cannot know the answer unless that information exists in the provided documents.</p><p>A good RAG system should not invent the answer. If the delivery charges are not written in the documents, it should say something like, “I do not know based on the provided documents.”</p><p>That may look like a weak answer at first, but it is actually a sign that the system is working correctly. A reliable AI assistant should know when it does not have enough information. Guessing is dangerous, especially in customer support, legal documents, finance, education, healthcare, and business automation.</p><p>RAG reduces hallucination by giving the AI trusted context before it answers. The language model still generates the final response, but the knowledge comes from your documents.</p><h3>The Simple RAG Pipeline</h3><p>A RAG pipeline is the full process that takes your documents and turns them into an AI-powered question-answering system.</p><p>The basic flow looks like this:</p><p>Documents are collected, cleaned, split into smaller pieces, converted into embeddings, stored in a vector database, searched when a user asks a question, and then passed to a language model for the final answer.</p><p>This may sound technical, but the idea is simple. A large document is too big to send to the AI every time. So we break it into smaller chunks and save those chunks in a searchable format. When the user asks a question, the system finds the best chunks and gives only those pieces to the model.</p><p>For example, if your documents include refund policy, shipping policy, warranty details, and service information, and the user asks, “How long does shipping take?” the system should retrieve the shipping policy section, not the refund policy or warranty section.</p><p>That is the purpose of retrieval.</p><h3>Documents: The Starting Point of RAG</h3><p>Every RAG system begins with data. This data can come from many sources. It can be PDFs, Word documents, website pages, Markdown files, CSV files, Notion pages, help center articles, product descriptions, company policies, or database records.</p><p>The quality of your RAG system depends heavily on the quality of your documents. If your documents are unclear, outdated, or missing important information, the AI will also give weak answers.</p><p>For example, if your shipping policy says, “Delivery may take some time,” the AI cannot give a specific answer. But if the document says, “Standard shipping takes 3 to 5 business days,” the AI can answer clearly.</p><p>This is why good RAG development is not only about coding. It is also about preparing clean, accurate, and well-structured knowledge.</p><h3>Document Loading</h3><p>Document loading means reading the content from files or sources and bringing it into your program.</p><p>A simple RAG project may load .md or .txt files from a folder. A more advanced system may load PDFs, scrape website pages, connect to Google Drive, read a database, or pull content from an API.</p><p>The goal of the loader is simple: take external information and turn it into plain text that the system can process.</p><p>For beginners, Markdown files are a good starting point because they are clean, easy to edit, and simple to understand. Once the basic idea is clear, you can move to PDFs, websites, and databases.</p><h3>Chunking: Splitting Documents Into Smaller Pieces</h3><p>Chunking is one of the most important parts of RAG.</p><p>A document can be very long. If you send a full 50-page document to the AI for every question, the system will become slow, expensive, and noisy. The model may also get confused because it receives too much irrelevant information.</p><p>Chunking solves this problem by splitting long text into smaller sections.</p><p>For example, a shipping policy document may be split into chunks like standard shipping, express shipping, tracking information, delays, and delivery charges. When the user asks about tracking, the system can retrieve only the tracking chunk.</p><p>Good chunks should be large enough to contain useful meaning, but small enough to stay focused. If a chunk is too small, it may lose context. If a chunk is too large, it may include too many mixed topics.</p><p>A beginner-friendly starting point is to split text into medium-sized chunks with a small overlap. Overlap means a few words or sentences are repeated between chunks so important context is not lost.</p><p>In professional RAG systems, chunking can become more advanced. Instead of splitting by character count only, the system may split by headings, paragraphs, sections, pages, or semantic meaning. The better your chunking, the better your retrieval will usually be.</p><h3>Embeddings: Turning Text Into Meaning</h3><p>Embeddings are the heart of modern RAG systems.</p><p>An embedding is a numerical representation of text. In simple words, it turns text into a list of numbers that represents meaning.</p><p>For example, the sentence “How long does shipping take?” and the sentence “What is the delivery time?” use different words, but they have similar meaning. An embedding model can understand that these two sentences are related.</p><p>This is different from normal keyword search. A keyword search only looks for exact words. If the document uses the word “delivery” but the user asks about “shipping,” a simple keyword system may miss the answer. Embeddings help solve this problem because they search by meaning, not just exact words.</p><p>The process looks like this: text goes into an embedding model, and the model outputs a vector, which is a list of numbers. Similar meanings produce vectors that are close to each other. Different meanings produce vectors that are far apart.</p><p>You do not need to manually understand the numbers. The important idea is this: embeddings help computers compare meaning.</p><p>Without embeddings, RAG would be much weaker.</p><h3>Vector Databases: Storing Meaning for Search</h3><p>Once you create embeddings, you need a place to store them. This is where a vector database comes in.</p><p>A normal database stores things like names, emails, prices, dates, and order IDs. A vector database stores embeddings and allows fast similarity search.</p><p>Think of a vector database as a smart library. Instead of asking, “Find the exact word refund,” you can ask, “Find the text that is most similar in meaning to this question.”</p><p>This is very powerful.</p><p>If the user asks, “Can I get my money back?” the vector database may find a chunk called “Refund Policy,” even if the user never used the word refund. This happens because the meaning is similar.</p><p>Popular vector databases include Chroma, FAISS, Pinecone, Weaviate, Qdrant, and PostgreSQL with pgvector. For beginners, Chroma is a good choice because it is easy to run locally. For production systems, developers often choose tools based on scale, speed, cost, and deployment needs.</p><p>The vector database usually stores three things: the chunk text, the embedding, and metadata.</p><p>Metadata is extra information about the chunk. It may include the file name, page number, section title, category, date, author, or document type. Metadata helps the system filter and organize results more intelligently.</p><h3>Retrieval: Finding the Right Context</h3><p>Retrieval is the step where the system searches the vector database and finds the most relevant chunks for the user’s question.</p><p>When a user asks a question, the question is also converted into an embedding. Then the system compares that question embedding with the stored document embeddings. The closest matches are returned as relevant chunks.</p><p>For example, if the user asks, “What is the refund period?” the retriever should find the chunk that says, “Our refund period is 14 days after delivery.”</p><p>This retrieved text becomes the context for the language model.</p><p>Retrieval is extremely important because the final answer depends on the quality of the retrieved context. If the retriever finds the wrong chunks, the AI may give a weak or incorrect answer. If the retriever finds the right chunks, the AI has a much better chance of answering correctly.</p><p>A simple rule is: <strong>bad retrieval creates bad answers</strong>.</p><h3>The Prompt: Giving Context to the AI</h3><p>After retrieval, the system builds a prompt for the language model. This prompt usually includes instructions, retrieved context, and the user’s question.</p><p>A simple RAG prompt may say:</p><p>“Answer the question using only the provided context. If the answer is not in the context, say you do not know based on the provided documents.”</p><p>This instruction is very important. It tells the model not to guess. The AI should answer only from the retrieved information.</p><p>The prompt is where the RAG system controls the behavior of the model. A good prompt can make the assistant clear, honest, and grounded. A weak prompt may allow the model to invent information.</p><p>In professional systems, prompts are carefully designed and tested. They may include tone rules, formatting rules, source citation rules, and safety instructions.</p><h3>The Language Model: Generating the Final Answer</h3><p>The language model is the part that writes the final response. It does not search your documents by itself in a basic RAG system. The retrieval system finds the information, and the language model turns that information into a natural answer.</p><p>This is why RAG is a combination of retrieval and generation.</p><p>Retrieval finds the knowledge. Generation explains the knowledge.</p><p>For example, the retrieved chunk may say, “Standard shipping usually takes 3 to 5 business days after the order is confirmed.” The language model can turn that into a friendly answer: “Standard shipping usually takes 3 to 5 business days after your order is confirmed.”</p><p>The model makes the answer readable and conversational, but the facts come from the documents.</p><h3>Better Retrieval: Making RAG More Accurate</h3><p>Basic RAG is useful, but it is not always enough. Sometimes the system retrieves irrelevant chunks or misses important details. Better retrieval means improving the search process so the AI receives stronger context.</p><p>One way to improve retrieval is better chunking. If your chunks are clean and focused, the retriever can find better matches. If your chunks mix many topics together, retrieval becomes harder.</p><p>Another improvement is metadata filtering. For example, if a user asks about pricing, the system can filter results to only pricing-related documents. If a user asks about warranty, it can search only warranty documents.</p><p>Hybrid search is another powerful method. It combines semantic search with keyword search. Semantic search understands meaning, while keyword search catches exact terms such as product names, invoice numbers, policy codes, or technical phrases.</p><p>Reranking is also useful. A vector database may return ten possible chunks. A reranker reviews those chunks again and places the best ones at the top. This helps the language model receive the most useful context.</p><p>Query rewriting can also improve results. Sometimes users ask unclear questions like, “What about charges?” The system can rewrite the query into something clearer, such as, “What are the delivery charges, shipping fees, or order delivery costs?”</p><p>Better retrieval is what separates a simple demo from a strong real-world RAG application.</p><h3>Evaluation: Testing Whether Your RAG System Works</h3><p>Many beginners build a RAG chatbot and stop once it gives an answer. But professionals test the system.</p><p>Evaluation means checking whether the RAG system is actually working well.</p><p>There are two main areas to evaluate: retrieval and answer quality.</p><p>Retrieval evaluation checks whether the system found the correct chunks. If the user asks about shipping time, did the system retrieve the shipping policy? If the user asks about refund rules, did it retrieve the refund policy?</p><p>Answer evaluation checks whether the final response is correct, clear, complete, and supported by the provided context.</p><p>A good RAG answer should be faithful to the documents. Faithfulness means the answer does not include unsupported claims. If the documents do not mention delivery charges, the AI should not invent delivery charges.</p><p>This is exactly why a response like “I do not know based on the provided documents” can be a good result. It means the system avoided hallucination.</p><p>To evaluate your RAG system, create a set of test questions. For each question, write the expected answer or expected keywords. Then run your chatbot and check whether it retrieves the right context and answers correctly.</p><p>For example, if your document says the refund period is 14 days, your test question can be, “What is the refund period?” The expected answer should include “14 days.”</p><p>Evaluation helps you find weak spots in your documents, chunking, retrieval, and prompts.</p><h3>Sources and Citations</h3><p>A professional RAG system should show sources when possible. Sources help users trust the answer.</p><p>If the assistant says, “The refund period is 14 days,” it is better to also show that the answer came from refund_policy.md or page 2 of a PDF.</p><p>Source citations are especially important for business, research, legal, educational, and technical use cases. They allow users to verify the answer and understand where the information came from.</p><p>Without sources, the user has to trust the AI blindly. With sources, the user can check the original document.</p><h3>Memory and RAG Are Not the Same</h3><p>Many beginners confuse memory with RAG.</p><p>Memory stores information about a user or conversation. For example, the system may remember that a user prefers short answers or works in SEO.</p><p>RAG retrieves information from documents or databases. For example, it may retrieve a refund policy, product description, or company guide.</p><p>Memory is about personalization. RAG is about knowledge retrieval.</p><p>A strong AI assistant may use both, but they solve different problems.</p><h3>Common Beginner Mistakes in RAG</h3><p>One common mistake is expecting the AI to answer questions from information that was never added to the documents. If delivery charges are missing from your shipping policy, the AI cannot answer that question correctly. You need to add the information and re-ingest the documents.</p><p>Another mistake is using poor chunking. If documents are split randomly or important context is cut off, retrieval becomes weak.</p><p>Some beginners also forget to update the vector database after editing documents. If you add new information to a file, you must run the ingestion process again so the new chunks and embeddings are stored.</p><p>Another mistake is allowing the AI to answer without context. In RAG, the model should be instructed to use only the retrieved information. Otherwise, it may guess.</p><p>Finally, many people ignore evaluation. Without testing, you cannot know whether your RAG system is reliable.</p><h3>A Simple Real-World Example</h3><p>Suppose you build a customer support chatbot for an online store. You add documents for refund policy, shipping policy, warranty, services, and pricing.</p><p>A customer asks, “How long does standard shipping take?”</p><p>The system converts the question into an embedding, searches the vector database, retrieves the shipping policy chunk, sends that chunk to the language model, and generates the answer: “Standard shipping usually takes 3 to 5 business days after the order is confirmed.”</p><p>Now suppose the customer asks, “What are delivery charges?”</p><p>If your documents do not mention delivery charges, the correct answer is: “I do not know based on the provided documents.”</p><p>To fix this, you add a sentence to the shipping policy, such as, “Standard delivery charges are $5, express delivery charges are $12, and free delivery is available on orders above $100.” Then you run ingestion again. After that, the chatbot can answer delivery charge questions correctly.</p><p>This example shows the most important RAG lesson: the AI is only as good as the knowledge you give it.</p><h3>The Basic Components of a RAG System</h3><p>A complete beginner-friendly RAG system usually has several basic components working together.</p><p>The document loader reads your files. The chunker splits the text into useful sections. The embedding model converts chunks into vectors. The vector database stores those vectors. The retriever searches for the most relevant chunks. The prompt builder combines context with the user’s question. The language model generates the final answer. The source system shows where the answer came from. The evaluation system tests whether the answers are correct.</p><p>Each part has a clear job. When one part is weak, the whole system becomes weaker.</p><p>If your documents are poor, the answer will be poor. If your chunks are messy, retrieval will be poor. If your prompt is weak, the model may hallucinate. If you do not evaluate, you will not know what is broken.</p><p>RAG is not just one technology. It is a pipeline.</p><h3>Final Thoughts</h3><p>RAG is one of the most important skills for anyone learning AI agents, AI automation, chatbots, and document-based AI applications. It allows language models to answer from real information instead of relying only on training data or guessing.</p><p>The idea is simple: collect knowledge, split it into chunks, convert it into embeddings, store it in a vector database, retrieve the right context, and let the language model answer using that context.</p><p>Once you understand this pipeline, you can build many useful applications. You can create PDF chatbots, website support bots, company knowledge assistants, invoice assistants, SEO research tools, legal document search systems, and customer support automation.</p><p>The key lesson is this: a good RAG system does not try to know everything. It knows how to find the right information before answering.</p><p>That is what makes RAG powerful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c7d489e1fa4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Deploy Flutter Web App on Firebase Hosting (2025 Update)]]></title>
            <link>https://medium.com/@emanyaqoob/deploy-flutter-web-app-on-firebase-hosting-2025-update-ca65f84a4832?source=rss-c74b278e156a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca65f84a4832</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[hosting]]></category>
            <dc:creator><![CDATA[Eman Yaqoob]]></dc:creator>
            <pubDate>Wed, 19 Feb 2025 10:48:02 GMT</pubDate>
            <atom:updated>2025-02-19T10:48:02.672Z</atom:updated>
            <content:encoded><![CDATA[<p>Firebase Hosting is one of the best options for deploying <strong>Flutter Web</strong> apps. It provides fast delivery with global CDN, free SSL, and easy integration with other Firebase services. This tutorial covers <strong>the latest updates</strong> (2025) and <strong>step-by-step deployment</strong> of a Flutter Web app on Firebase Hosting.</p><h3>✅ Prerequisites</h3><p>Before we start, make sure you have:</p><ul><li>✅ <strong>Flutter Installed</strong> (Latest stable version)</li><li>✅ <strong>Firebase CLI Installed</strong></li><li>✅ <strong>A Google Firebase Project</strong></li></ul><h3>Step 1: Enable Flutter Web</h3><p>Flutter now <strong>supports Web by default</strong>, but you need to ensure it’s enabled in your project. Run:</p><pre>flutter config --enable-web</pre><p>Now, check if Web is available:</p><pre>flutter devices</pre><p>If <strong>Chrome (web)</strong> or <strong>Web Server</strong> appears, Web is enabled.</p><h3>Step 2: Create a Firebase Project</h3><p>1️⃣ Go to <strong>Firebase Console</strong><br>2️⃣ Click <strong>“Add Project”</strong><br>3️⃣ Enter a project name (e.g., flutter-web-app)<br>4️⃣ Disable <strong>Google Analytics</strong> (optional) and click <strong>Create</strong></p><p>✅ <strong>Once the project is ready, go to Project Settings &gt; General &gt; Your Apps</strong></p><h3>Step 3: Install Firebase CLI (If Not Installed)</h3><p>To deploy Flutter Web, you need <strong>Firebase CLI</strong>. If you haven’t installed it yet, run:</p><pre>npm install -g firebase-tools</pre><p>⚡ <strong>Verify installation:</strong></p><pre>firebase --version</pre><p>If you get a version like v12.0.0+, Firebase CLI is installed! 🎉</p><h3>Step 4: Login &amp; Initialize Firebase in Your Project</h3><h3>🔹 Login to Firebase</h3><p>Run:</p><pre>firebase login</pre><p>A browser will open. Sign in with your Google account.</p><h3>🔹 Initialize Firebase in Your Flutter Project</h3><p>Go to your Flutter project’s root directory and run:</p><pre>firebase init</pre><h3>🛠️ During Initialization, Select:</h3><ul><li><strong>Hosting:</strong> Select <strong>&quot;Use an existing project&quot;</strong> and choose your Firebase project.</li><li><strong>Public Directory:</strong> Type build/web (because Flutter Web builds into this directory).</li><li><strong>Rewrite index.html:</strong> Choose <strong>Yes</strong> to allow Firebase to handle routing.</li><li><strong>Single-page App:</strong> Choose <strong>Yes</strong> (for Flutter Web apps).</li></ul><p>✅ Firebase is now initialized in your Flutter project!</p><h3>Step 5: Build the Flutter Web App</h3><p>Now, generate the Web build of your Flutter app:</p><pre>flutter build web</pre><p>This will create a build/web directory, which is what we’ll deploy.</p><h3>Step 6: Deploy to Firebase Hosting</h3><p>Run:</p><pre>firebase deploy</pre><p>After deployment, Firebase will provide a <strong>Hosting URL</strong> like:</p><pre>✔ Hosting URL: https://your-project.web.app</pre><p>🎉 <strong>Your Flutter Web app is now live!</strong></p><h3>Step 7: Enable Custom Domain (Optional)</h3><p>If you want to use a custom domain like yourapp.com:<br>1️⃣ In <strong>Firebase Console</strong>, go to <strong>Hosting</strong><br>2️⃣ Click <strong>&quot;Add custom domain&quot;</strong><br>3️⃣ Enter your domain (e.g., yourapp.com)<br>4️⃣ Firebase will give you <strong>DNS Records</strong> → Add these to your domain provider<br>5️⃣ Wait for propagation (usually a few minutes to hours)</p><p>✅ Once done, Firebase will provide <strong>free SSL</strong> and handle <strong>HTTPS automatically</strong>! 🔥</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*54JXbIEUzG9sF_JySNhsYg.png" /></figure><h3>🎯 Final Thoughts</h3><p>Firebase Hosting is <strong>fast, secure, and free</strong> for small-scale projects. Now your <strong>Flutter Web app</strong> is live, and you can integrate it with Firebase Auth, Firestore, or other Firebase services!</p><p>🔥 <strong>Next Steps:</strong></p><ul><li>Enable Firebase <strong>Auth</strong> for login/signup</li><li>Connect <strong>Firestore</strong> as a database</li><li>Setup <strong>Cloud Functions</strong> for backend logic</li></ul><p>Would you like a tutorial on adding Firebase Auth to your Flutter Web app? 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca65f84a4832" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter State Management: Choosing the Right Approach]]></title>
            <link>https://medium.com/@emanyaqoob/flutter-state-management-choosing-the-right-approach-64b2ccf59235?source=rss-c74b278e156a------2</link>
            <guid isPermaLink="false">https://medium.com/p/64b2ccf59235</guid>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[apps]]></category>
            <dc:creator><![CDATA[Eman Yaqoob]]></dc:creator>
            <pubDate>Wed, 19 Feb 2025 10:14:30 GMT</pubDate>
            <atom:updated>2025-02-19T10:14:30.016Z</atom:updated>
            <content:encoded><![CDATA[<p>State management is one of the most debated topics in Flutter development. Choosing the wrong approach can lead to performance issues, unnecessary re-renders, and complex debugging. In this tutorial, we’ll explore different state management techniques, their issues, and when to use each one.</p><h3>🔹 What is State Management?</h3><p>State management in Flutter refers to managing the data that a UI needs to rebuild correctly. There are two types of state in Flutter:</p><ol><li><strong>Ephemeral (UI-Local) State</strong> → Temporary state confined to a widget, like the current page index of a BottomNavigationBar.</li><li><strong>App-wide (Global) State</strong> → State that needs to be shared across multiple widgets, like user authentication status or theme settings.</li></ol><h3>🔥 Common State Management Approaches &amp; Their Use Cases</h3><h3>1️⃣ setState (Built-in, Beginner-Friendly)</h3><p><strong>Best for:</strong> Simple, local UI state (like toggling a button or updating a counter).<br><strong>Issues:</strong> Doesn’t work well for complex apps with multiple widgets needing the same state.</p><h3>✅ When to Use setState</h3><ul><li>When state affects only a single widget.</li><li>When state changes infrequently.</li><li>For small-scale applications.</li></ul><h3>❌ When NOT to Use setState</h3><ul><li>When state needs to be shared between multiple widgets.</li><li>When dealing with large-scale applications with complex state logic.</li></ul><p>📌 <strong>Example:</strong></p><pre>class CounterScreen extends StatefulWidget {<br>  @override<br>  _CounterScreenState createState() =&gt; _CounterScreenState();<br>}<br><br>class _CounterScreenState extends State&lt;CounterScreen&gt; {<br>  int _count = 0;<br><br>  void _incrementCounter() {<br>    setState(() {<br>      _count++;<br>    });<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: Center(<br>        child: Column(<br>          mainAxisAlignment: MainAxisAlignment.center,<br>          children: [<br>            Text(&quot;Counter: $_count&quot;),<br>            ElevatedButton(onPressed: _incrementCounter, child: Text(&quot;Increment&quot;))<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><h3>2️⃣ InheritedWidget / InheritedModel (Built-in, Advanced Use)</h3><p><strong>Best for:</strong> Passing state efficiently to child widgets without unnecessary rebuilds.<br><strong>Issues:</strong> Complex to implement and not beginner-friendly.</p><h3>✅ When to Use InheritedWidget</h3><ul><li>When a state needs to be shared between multiple widgets.</li><li>When avoiding unnecessary widget rebuilds is important.</li></ul><h3>❌ When NOT to Use InheritedWidget</h3><ul><li>For simple state management where setState is enough.</li><li>When using Provider, since it offers better usability.</li></ul><p>📌 <strong>Example:</strong></p><pre>class CounterState extends InheritedWidget {<br>  final int count;<br>  final Function() increment;<br><br>  CounterState({required this.count, required this.increment, required Widget child}) : super(child: child);<br><br>  static CounterState? of(BuildContext context) =&gt; context.dependOnInheritedWidgetOfExactType&lt;CounterState&gt;();<br><br>  @override<br>  bool updateShouldNotify(CounterState oldWidget) =&gt; oldWidget.count != count;<br>}</pre><h3>3️⃣ Provider (Recommended for Most Apps)</h3><p><strong>Best for:</strong> Apps with moderate to complex state needs, dependency injection, and easy integration.<br><strong>Issues:</strong> Can become hard to manage in large apps without proper structuring.</p><h3>✅ When to Use Provider</h3><ul><li>When multiple widgets need to access and modify the same state.</li><li>When using dependency injection for better modularity.</li><li>When avoiding unnecessary widget rebuilds.</li></ul><h3>❌ When NOT to Use Provider</h3><ul><li>For simple local state that setState can handle.</li><li>When state logic becomes too complex (consider Riverpod instead).</li></ul><p>📌 <strong>Example:</strong></p><pre>class CounterProvider with ChangeNotifier {<br>  int _count = 0;<br>  int get count =&gt; _count;<br><br>  void increment() {<br>    _count++;<br>    notifyListeners();<br>  }<br>}<br><br>void main() {<br>  runApp(ChangeNotifierProvider(<br>    create: (context) =&gt; CounterProvider(),<br>    child: MyApp(),<br>  ));<br>}</pre><h3>4️⃣ Riverpod (Improved Provider, Best for Scalability)</h3><p><strong>Best for:</strong> Large-scale apps with better performance, testability, and dependency injection.<br><strong>Issues:</strong> Requires learning a different API compared to Provider.</p><h3>✅ When to Use Riverpod</h3><ul><li>When needing better performance with fewer unnecessary rebuilds.</li><li>When state should be easily testable.</li><li>When needing multiple state types (state, future, and stream providers).</li></ul><h3>❌ When NOT to Use Riverpod</h3><ul><li>When working on a small project where Provider is enough.</li><li>When unfamiliar with Riverpod’s new concepts.</li></ul><p>📌 <strong>Example:</strong></p><pre>final counterProvider = StateProvider&lt;int&gt;((ref) =&gt; 0);<br><br>class CounterScreen extends ConsumerWidget {<br>  @override<br>  Widget build(BuildContext context, WidgetRef ref) {<br>    final count = ref.watch(counterProvider);<br>    return Scaffold(<br>      body: Center(child: Text(&#39;Counter: $count&#39;)),<br>      floatingActionButton: FloatingActionButton(<br>        onPressed: () =&gt; ref.read(counterProvider.notifier).state++,<br>        child: Icon(Icons.add),<br>      ),<br>    );<br>  }<br>}</pre><h3>5️⃣ BLoC / Cubit (For Complex, Enterprise-Level Apps)</h3><p><strong>Best for:</strong> Large-scale apps with structured state management and event-driven architecture.<br><strong>Issues:</strong> More boilerplate code and steeper learning curve.</p><h3>✅ When to Use BLoC</h3><ul><li>When state changes need to be predictable and event-driven.</li><li>When working on enterprise-level applications.</li><li>When working with streams and reactive programming.</li></ul><h3>❌ When NOT to Use BLoC</h3><ul><li>When working on a small app where Provider or Riverpod is sufficient.</li><li>When you need a lightweight solution without much boilerplate.</li></ul><p>📌 <strong>Example:</strong></p><pre>class CounterCubit extends Cubit&lt;int&gt; {<br>  CounterCubit() : super(0);<br><br>  void increment() =&gt; emit(state + 1);<br>}<br><br>class CounterScreen extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return BlocProvider(<br>      create: (_) =&gt; CounterCubit(),<br>      child: BlocBuilder&lt;CounterCubit, int&gt;(<br>        builder: (context, count) {<br>          return Scaffold(<br>            body: Center(child: Text(&#39;Counter: $count&#39;)),<br>            floatingActionButton: FloatingActionButton(<br>              onPressed: () =&gt; context.read&lt;CounterCubit&gt;().increment(),<br>              child: Icon(Icons.add),<br>            ),<br>          );<br>        },<br>      ),<br>    );<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*ozQ8jWjsTpVblwNJgTfgkg.png" /></figure><h3>🛠️ Final Thoughts</h3><p>Choosing the right state management solution depends on your project’s needs. If you’re working on a <strong>small app</strong>, setState or Provider is usually enough. If you need <strong>scalability and better performance</strong>, Riverpod is a great choice. For <strong>large enterprise apps</strong>, BLoC is the best option.</p><p>💡 <strong>Pro Tip:</strong> If you’re unsure, start with Provider, and if your app grows in complexity, migrate to Riverpod or BLoC. 🚀</p><p>Would you like a comparison between Riverpod and BLoC in more depth?</p><p>SEE YOU.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64b2ccf59235" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Localization with Riverpod and SharedPreferences.]]></title>
            <link>https://medium.com/@emanyaqoob/flutter-localization-with-riverpod-and-sharedpreferences-d3919fb9bb02?source=rss-c74b278e156a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3919fb9bb02</guid>
            <category><![CDATA[language]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[localization]]></category>
            <category><![CDATA[sharedpreferences]]></category>
            <category><![CDATA[riverpod]]></category>
            <dc:creator><![CDATA[Eman Yaqoob]]></dc:creator>
            <pubDate>Wed, 07 Aug 2024 19:09:42 GMT</pubDate>
            <atom:updated>2024-08-07T19:28:38.708Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vyvkyUnyXlr8hScfaMD4Fw.png" /></figure><p>This tutorial will guide you through creating a Flutter project with localization support, using Riverpod for state management, and SharedPreferences for storing the user’s language preference.</p><p>Create a New Flutter Project</p><pre>flutter create localization_example<br>cd localization_example</pre><p><strong>Update </strong><strong>pubspec.yaml</strong> Add the following dependencies to your pubspec.yaml file:</p><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>  flutter_localizations:<br>    sdk: flutter<br>  intl: any<br>  shared_preferences: ^2.0.15<br>  flutter_riverpod: ^2.0.0</pre><p><strong>Add </strong><strong>l10n.yaml File</strong> Create a file named l10n.yaml in the root directory of your project with the following content:</p><pre>arb-dir: lib/l10n<br>template-arb-file: app_en.arb<br>output-localization-file: app_localizations.dart</pre><h4>Create Localization Files</h4><p><strong>Add ARB Files</strong> Create a directory named l10n inside the lib folder. Inside lib/l10n, create two files: app_en.arb and app_fr.arb.</p><p>lib/l10n/app_en.arb</p><pre>{<br>  &quot;@@locale&quot;: &quot;en&quot;,<br>  &quot;chooseLanguageTitle&quot;: &quot;Choose Your Language&quot;,<br>  &quot;@chooseLanguageTitle&quot;: {<br>    &quot;description&quot;: &quot;Title for the Choose Language screen&quot;<br>  }<br>}</pre><p>lib/l10n/app_fr.arb</p><pre>{<br>  &quot;@@locale&quot;: &quot;fr&quot;,<br>  &quot;chooseLanguageTitle&quot;: &quot;Choisissez votre langue&quot;,<br>  &quot;@chooseLanguageTitle&quot;: {<br>    &quot;description&quot;: &quot;Titre pour l&#39;écran Choisissez votre langue&quot;<br>  }<br>}</pre><p><strong>Enable Code Generation</strong> Open pubspec.yaml and add the following under the flutter section:</p><pre>flutter:<br>  generate: true</pre><p>Run flutter pub get to fetch the new dependencies and set up the code generation.</p><h4>Implement Localization</h4><p>Create a notifier to manage language state using Riverpod:</p><pre>import &#39;package:flutter_riverpod/flutter_riverpod.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:shared_preferences/shared_preferences.dart&#39;;<br><br>class AppLanguageNotifier extends StateNotifier&lt;Locale&gt; {<br>  AppLanguageNotifier() : super(const Locale(&#39;en&#39;));<br><br>  Future&lt;void&gt; fetchLocale() async {<br>    var prefs = await SharedPreferences.getInstance();<br>    String? languageCode = prefs.getString(&#39;language_code&#39;);<br>    if (languageCode != null) {<br>      state = Locale(languageCode);<br>    }<br>  }<br><br>  Future&lt;void&gt; changeLanguage(Locale type) async {<br>    var prefs = await SharedPreferences.getInstance();<br>    if (state != type) {<br>      state = type;<br>      await prefs.setString(&#39;language_code&#39;, type.languageCode);<br>    }<br>  }<br>}<br><br>final appLanguageProvider = StateNotifierProvider&lt;AppLanguageNotifier, Locale&gt;(<br>  (ref) {<br>    final notifier = AppLanguageNotifier();<br>    notifier.fetchLocale();<br>    return notifier;<br>  }<br>);</pre><p><strong>Update </strong><strong>main.dart </strong>Replace the contents of lib/main.dart with the following code:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_gen/gen_l10n/app_localizations.dart&#39;;<br>import &#39;package:flutter_localizations/flutter_localizations.dart&#39;;<br>import &#39;package:flutter_riverpod/flutter_riverpod.dart&#39;;<br><br>void main() {<br>  runApp(ProviderScope(child: MyApp()));<br>}<br><br>class MyApp extends ConsumerWidget {<br>  const MyApp({super.key});<br><br>  @override<br>  Widget build(BuildContext context, WidgetRef ref) {<br>    final appLocale = ref.watch(appLanguageProvider);<br><br>    return MaterialApp(<br>      debugShowCheckedModeBanner: false,<br>      locale: appLocale,<br>      supportedLocales: const [<br>        Locale(&#39;en&#39;, &#39;&#39;),<br>        Locale(&#39;fr&#39;, &#39;&#39;),<br>      ],<br>      localizationsDelegates: const [<br>        AppLocalizations.delegate,<br>        GlobalMaterialLocalizations.delegate,<br>        GlobalWidgetsLocalizations.delegate,<br>        GlobalCupertinoLocalizations.delegate,<br>      ],<br>      home: ChooseLanguage(),<br>    );<br>  }<br>}</pre><h4>Home Screen Widget</h4><p>Implement a widget to change languages:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_riverpod/flutter_riverpod.dart&#39;;<br>import &#39;package:flutter_localizations/flutter_localizations.dart&#39;;<br>import &#39;package:your_project_name/localization/app_localizations.dart&#39;; // Adjust the import path to your project structure<br>import &#39;package:your_project_name/providers/app_language_provider.dart&#39;; // Adjust the import path to your project structure<br><br>class ChooseLanguage extends ConsumerStatefulWidget {<br>  const ChooseLanguage({super.key});<br><br>  @override<br>  ConsumerState&lt;ConsumerStatefulWidget&gt; createState() =&gt; _ChooseLanguageState();<br>}<br><br>class _ChooseLanguageState extends ConsumerState&lt;ChooseLanguage&gt; {<br>void _changeLanguage(Locale locale) {<br>    final notifier = ref.read(appLanguageProvider.notifier);<br>    notifier.changeLanguage(locale);<br>  }<br>  @override<br>  Widget build(BuildContext context) {<br><br><br>    return Scaffold(<br>      appBar: AppBar(<br>        title: Text(&#39;language changer&#39;),<br>      ),<br>      body: Padding(<br>        padding: const EdgeInsets.all(16.0),<br>        child: Column(<br>          mainAxisAlignment: MainAxisAlignment.center,<br>          children: [<br>            Text(<br>              AppLocalizations.of(context)!.chooseLanguageTitle,<br>              style: Theme.of(context).textTheme.headline6,<br>            ),<br>            const SizedBox(height: 20),<br>            FilledButton(<br>              onPressed: () =&gt; _changeLanguage(const Locale(&#39;en&#39;, &#39;&#39;)),<br>              style: FilledButton.styleFrom(<br>                shape: RoundedRectangleBorder(<br>                  borderRadius: BorderRadius.circular(5.0),<br>                ),<br>                minimumSize: const Size(double.infinity, 50),<br>              ),<br>              child: Text(<br>                &#39;English&#39;,<br>                style: Theme.of(context).textTheme.titleMedium?.copyWith(<br>                      color: Colors.white,<br>                    ),<br>                textAlign: TextAlign.center,<br>              ),<br>            ),<br>            const SizedBox(height: 10),<br>            FilledButton(<br>              onPressed: () =&gt; _changeLanguage(const Locale(&#39;fr&#39;, &#39;&#39;)),<br>              style: FilledButton.styleFrom(<br>                shape: RoundedRectangleBorder(<br>                  borderRadius: BorderRadius.circular(5.0),<br>                ),<br>                minimumSize: const Size(double.infinity, 50),<br>              ),<br>              child: Text(<br>                &#39;French&#39;,<br>                style: Theme.of(context).textTheme.titleMedium?.copyWith(<br>                      color: Colors.white,<br>                    ),<br>                textAlign: TextAlign.center,<br>              ),<br>            ),<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><h4>Build and Run Your Project</h4><p>Run the project to see the localization in action:</p><pre>flutter run</pre><p>You should be able to change languages and see the text updated based on the selected locale.</p><p>Thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3919fb9bb02" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ref.read, ref.watch, and ref.listen]]></title>
            <link>https://medium.com/@emanyaqoob/ref-read-ref-watch-and-ref-listen-77ed93e0ed3a?source=rss-c74b278e156a------2</link>
            <guid isPermaLink="false">https://medium.com/p/77ed93e0ed3a</guid>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[flutter-state-management]]></category>
            <category><![CDATA[provider]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Eman Yaqoob]]></dc:creator>
            <pubDate>Sat, 27 Jul 2024 07:39:50 GMT</pubDate>
            <atom:updated>2024-07-29T08:09:28.710Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wadytIXJdkXCqtxcVJQldw.png" /></figure><p>Great questions! Understanding ref.watch(), ref.read(), and ref.listen() is key to effectively using Riverpod for state management. Here’s a detailed explanation of each:</p><h3>1. ref.watch()</h3><p><strong>Purpose</strong>:</p><ul><li>ref.watch() is used to <strong>read a provider</strong> and <strong>listen for changes</strong> to the provider&#39;s state.</li></ul><p><strong>Behavior</strong>:</p><ul><li>When you use ref.watch(), the widget that uses this function will <strong>rebuild</strong> whenever the state provided by the provider changes.</li><li>This is useful for displaying dynamic data that should update automatically when the underlying state changes.</li></ul><p><strong>Usage</strong>:</p><ul><li>Use ref.watch() in ConsumerWidget or Consumer to <strong>reactively rebuild</strong> the UI based on the current state.</li><li>It should be used when you need the UI to reflect changes in the provider’s state in real-time.</li></ul><pre>final productState = ref.watch(productProvider(productId));</pre><p>In this example, productState will hold the current state of the product, and the widget will rebuild if the state changes.</p><h3>2. ref.read()</h3><p><strong>Purpose</strong>:</p><ul><li>ref.read() is used to <strong>read the provider&#39;s state</strong> without listening for changes. It provides the current state or notifier.</li></ul><p><strong>Behavior</strong>:</p><ul><li>When you use ref.read(), the widget does not rebuild if the provider’s state changes.</li><li>It is used for one-time reads or for triggering actions that don’t need to update the UI in response to state changes.</li></ul><p><strong>Usage</strong>:</p><ul><li>Use ref.read() when you need to <strong>perform an action</strong> that depends on the current state but don’t need the widget to rebuild based on state changes.</li><li>Ideal for triggering actions like calling methods on a notifier, or when you want to access a provider without rebuilding the UI.</li></ul><p><strong>Example</strong>:</p><pre>final productNotifier = ref.read(productProvider(productId).notifier);</pre><p>In this example, productNotifier is used to call methods like increment() or decrement() without causing a rebuild.</p><h3>3. ref.listen()</h3><p><strong>Purpose</strong>:</p><ul><li>ref.listen() is used to <strong>listen for changes</strong> to a provider’s state and <strong>perform side effects</strong> when the state changes.</li></ul><p><strong>Behavior</strong>:</p><ul><li>It allows you to <strong>react to changes</strong> in state with custom logic or side effects (e.g., showing a snackbar or navigating to a new screen).</li><li>Unlike ref.watch(), it does not rebuild the widget but triggers actions when the state changes.</li></ul><p><strong>Usage</strong>:</p><ul><li>Use ref.listen() for <strong>side effects</strong> or to react to state changes in a way that doesn’t involve rebuilding the UI.</li><li>It’s useful for handling things like logging, analytics, or navigation based on state changes.</li></ul><p><strong>Example</strong>:</p><pre>ref.listen&lt;ProductState&gt;(<br>  productProvider(productId),<br>  (previous, next) {<br>    if (next.isFavorite != previous?.isFavorite) {<br>      // Perform some side effect, e.g., show a snackbar<br>    }<br>  },<br>);</pre><p>In this example, the ref.listen() callback will trigger whenever the isFavorite property changes, allowing you to perform actions like showing a message.</p><h3>Summary</h3><ul><li><strong>ref.watch()</strong>: Use it to <strong>display</strong> data and <strong>automatically rebuild</strong> the widget when the state changes.</li><li><strong>ref.read()</strong>: Use it to <strong>access</strong> the current state or notifier <strong>without rebuilding</strong> the widget.</li><li><strong>ref.listen()</strong>: Use it to <strong>react</strong> to state changes with <strong>side effects</strong> without rebuilding the widget.</li></ul><p>By understanding and using these functions appropriately, you can efficiently manage and respond to state changes in your Riverpod-based Flutter applications</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77ed93e0ed3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Change provider into Riverpod]]></title>
            <link>https://medium.com/@emanyaqoob/change-provider-into-riverpod-64eb28a54e35?source=rss-c74b278e156a------2</link>
            <guid isPermaLink="false">https://medium.com/p/64eb28a54e35</guid>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[riverpod]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[provider]]></category>
            <dc:creator><![CDATA[Eman Yaqoob]]></dc:creator>
            <pubDate>Sat, 27 Jul 2024 07:32:07 GMT</pubDate>
            <atom:updated>2024-07-29T08:07:17.231Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LK8cFEfBuZ4qg_KxtocayA.png" /><figcaption>riverpod</figcaption></figure><pre>import &#39;package:flutter/material.dart&#39;;<br><br>class ProductProvider with ChangeNotifier {<br>  int _counterValue;<br>  bool _isFavorite;<br><br>  ProductProvider(this._counterValue, this._isFavorite);<br><br>  int get counterValue =&gt; _counterValue;<br>  bool get isFavorite =&gt; _isFavorite;<br><br>  void increment() {<br>    _counterValue++;<br>    notifyListeners();<br>  }<br><br>  void decrement() {<br>    if (_counterValue &gt; 0) {<br>      _counterValue--;<br>      notifyListeners();<br>    }<br>  }<br><br>  void toggleFavorite() {<br>    _isFavorite = !_isFavorite;<br>    notifyListeners();<br>  }<br>}</pre><p>we all know this is the example of cart feature in a ecommerce app lets change this code into flutter riverpod ;</p><pre><br>class ProductState {<br>  final int counterValue;<br>  final bool isFavorite;<br><br>  ProductState({required this.counterValue, required this.isFavorite});<br>}<br><br>class ProductNotifier extends StateNotifier&lt;ProductState&gt; {<br>  ProductNotifier() : super(ProductState(counterValue: 1, isFavorite: false));<br><br>  void increment() {<br>    state = ProductState(<br>      counterValue: state.counterValue + 1,<br>      isFavorite: state.isFavorite,<br>    );<br>  }<br><br>  void decrement() {<br>    if (state.counterValue &gt; 0) {<br>      state = ProductState(<br>        counterValue: state.counterValue - 1,<br>        isFavorite: state.isFavorite,<br>      );<br>    }<br>  }<br><br>  void toggleFavorite() {<br>    state = ProductState(<br>      counterValue: state.counterValue,<br>      isFavorite: !state.isFavorite,<br>    );<br>  }<br>}<br><br>final productProvider =<br>    StateNotifierProvider.family&lt;ProductNotifier, ProductState, int&gt;(<br>  (ref, productId) =&gt; ProductNotifier(),<br>);<br> explain this in detail i wana learn this code </pre><ol><li>ProductState Class</li></ol><pre>class ProductState {<br>  final int counterValue;<br>  final bool isFavorite;<br><br>  ProductState({required this.counterValue, required this.isFavorite});<br>}</pre><ul><li><strong>Purpose</strong>: This class is a simple data holder for the state of a product.</li><li><strong>Fields</strong>:</li><li>counterValue: An integer that represents the count for a product (e.g., quantity in a shopping cart).</li><li>isFavorite: A boolean that indicates whether the product is marked as a favorite.</li></ul><h3>2. ProductNotifier Class</h3><pre>class ProductNotifier extends StateNotifier&lt;ProductState&gt; {<br>  ProductNotifier() : super(ProductState(counterValue: 1, isFavorite: false));<br><br>  void increment() {<br>    state = ProductState(<br>      counterValue: state.counterValue + 1,<br>      isFavorite: state.isFavorite,<br>    );<br>  }<br><br>  void decrement() {<br>    if (state.counterValue &gt; 0) {<br>      state = ProductState(<br>        counterValue: state.counterValue - 1,<br>        isFavorite: state.isFavorite,<br>      );<br>    }<br>  }<br><br>  void toggleFavorite() {<br>    state = ProductState(<br>      counterValue: state.counterValue,<br>      isFavorite: !state.isFavorite,<br>    );<br>  }<br>}</pre><ul><li><strong>Purpose</strong>: ProductNotifier extends StateNotifier and is used to manage and mutate the state of a product.</li><li><strong>Constructor</strong>:</li><li>Initializes with a default state where counterValue is 1 and isFavorite is false.</li><li><strong>Methods</strong>:</li><li>increment(): Increases the counterValue by 1. This updates the state with the new counterValue while keeping the isFavorite status the same.</li><li>decrement(): Decreases the counterValue by 1, only if counterValue is greater than 0. This updates the state with the new counterValue while keeping the isFavorite status the same.</li><li>toggleFavorite(): Toggles the isFavorite status. This updates the state with the current counterValue and toggles the isFavorite boolean.</li></ul><h3>3. productProvider</h3><pre>final productProvider = StateNotifierProvider.family&lt;ProductNotifier, ProductState, int&gt;(<br>  (ref, productId) =&gt; ProductNotifier(),<br>);</pre><ul><li><strong>Purpose</strong>: Defines a provider for ProductNotifier that uses Riverpod&#39;s family feature to handle multiple instances of ProductNotifier, each with its own state.</li><li><strong>Components</strong>:</li><li>StateNotifierProvider.family: This is a specialized provider that allows you to create a StateNotifier with parameters. In this case, the parameter is productId.</li><li>ProductNotifier: The type of StateNotifier being provided. Each ProductNotifier instance manages the state for a specific product.</li><li>ProductState: The type of state managed by ProductNotifier.</li><li>int: The type of parameter used to create each instance of ProductNotifier. Here, it’s the product ID, which ensures each product&#39;s state is managed independently.</li><li><strong>How It Works</strong>:</li><li><strong>When a widget requests the </strong><strong>productProvider</strong>, it provides a productId (e.g., a unique identifier for a product).</li><li><strong>Riverpod uses this </strong><strong>productId</strong> to create or access the appropriate instance of ProductNotifier and its associated state.</li><li><strong>Each </strong><strong>ProductNotifier instance</strong> is managed separately, allowing different products to have independent states.</li></ul><h3>Summary</h3><ol><li><strong>State Management</strong>: ProductState holds the state, and ProductNotifier manages and updates this state.</li><li><strong>Provider Setup</strong>: productProvider is a Riverpod provider that creates and manages ProductNotifier instances, each uniquely identified by productId.</li><li><strong>Usage</strong>: In your widgets, you use ConsumerWidget or Consumer to read and manipulate the state using productProvider, passing in the productId to get or modify the correct instance of ProductNotifier.</li></ol><p>This setup allows you to manage state for multiple products independently, with each product maintaining its own counterValue and isFavorite status.</p><p>Happy coding….</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64eb28a54e35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Hive Database Tutorial]]></title>
            <link>https://medium.com/@emanyaqoob/flutter-hive-database-tutorial-59eeb2f8cc79?source=rss-c74b278e156a------2</link>
            <guid isPermaLink="false">https://medium.com/p/59eeb2f8cc79</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[local-database]]></category>
            <category><![CDATA[hive]]></category>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[maps]]></category>
            <dc:creator><![CDATA[Eman Yaqoob]]></dc:creator>
            <pubDate>Sun, 28 Jan 2024 16:26:57 GMT</pubDate>
            <atom:updated>2024-06-10T16:02:18.291Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CC52z5KEhnvSVA_ZxBuZtA.png" /><figcaption>Hive in flutter</figcaption></figure><p>This is a basic tutorial on how to use the Hive local database in Flutter for handling maps.</p><h3>Step 1: Add Dependencies</h3><p>First, make sure to add the necessary dependencies to your pubspec.yaml file:</p><pre>dependencies:<br>  hive: ^2.0.4<br>  hive_flutter: ^1.1.0<br>  path_provider: ^2.0.14</pre><h3>Step 2: Initialize Hive</h3><p>In your main.dart file, initialize Hive in the main function before running the app:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:hive/hive.dart&#39;;<br>import &#39;package:hive_flutter/hive_flutter.dart&#39;;<br><br>void main() async {<br> final dir = await getApplicationDocumentsDirectory();<br> Hive.defaultDirectory = dir.path; <br> runApp(MyApp());<br>}</pre><h3>Step 3: Create a Hive Box</h3><p>Modify your CustomButton widget to interact with Hive. In this example, let&#39;s create a simple todo list:</p><pre>// Import necessary packages<br>import &#39;package:hive/hive.dart&#39;;<br><br>// ... (your existing ui code )<br><br>CustomButton(<br>  buttonText: &#39;Add Todo&#39;,<br>  onPressed: () async {<br>    final todoBox = await Hive.openBox&lt;Map&gt;(&#39;todos&#39;);<br><br>    // Example todo map<br>    final todoMap = {<br>      &#39;title&#39;: &#39;Example Todo&#39;,<br>      &#39;description&#39;: &#39;This is a sample todo item.&#39;,<br>    };<br><br>    // Save the todo map to the Hive box<br>    todoBox.add(todoMap);<br><br>    // Display todos in the console<br>    for (var i = 0; i &lt; todoBox.length; i++) {<br>      print(&#39;Todo #$i: ${todoBox.getAt(i)}&#39;);<br>    }<br>  },<br>)</pre><h3>Step 4: Display Todos</h3><p>Create a new screen to display the saved todos:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:hive/hive.dart&#39;;<br>import &#39;package:hive_flutter/hive_flutter.dart&#39;;<br><br>class TodoListScreen extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: Text(&#39;Todo List&#39;),<br>      ),<br>      body: ValueListenableBuilder(<br>        valueListenable: Hive.box&lt;Map&gt;(&#39;todos&#39;).listenable(),<br>        builder: (context, Box&lt;Map&gt; box, _) {<br>          return ListView.builder(<br>            itemCount: box.length,<br>            itemBuilder: (context, index) {<br>              final todo = box.getAt(index);<br>              return ListTile(<br>                title: Text(todo?[&#39;title&#39;] ?? &#39;&#39;),<br>                subtitle: Text(todo?[&#39;description&#39;] ?? &#39;&#39;),<br>              );<br>            },<br>          );<br>        },<br>      ),<br>    );<br>  }<br>}</pre><h3>Open a Hive Box</h3><p>When you call Hive.box(name: &#39;todos&#39;) for the first time with a given name, Hive will create a new box for you. If you call it again with the same name, Hive will return the already existing box.</p><p>You can also use Hive.box() without providing a name. In this case, Hive will return the default box.</p><p>There are optional parameters you can pass to Hive.box():</p><p>Parameter</p><p>nameLabel your box with a distinct name.</p><p>directorySelect a home for your box. If omitted, Hive uses the defaultDirectory.</p><p>encryptionKeyHand over this key, and Hive will encrypt your box. Keep it safe!</p><p>maxSizeMiBThe maximum size of the box in MiB. Go for a modest number.</p><h3>Close a Hive Box</h3><p>It’s not advised to close boxes that might be accessed again. This prevents unnecessary overhead of reopening the box and ensures smooth data retrieval.</p><p>To close a box just call box.close(). Wipe the box from the face of the earth with box.deleteFromDisk().</p><h3>Inserting Data</h3><pre>box.put(&#39;friends&#39;, [&#39;Buzzy&#39;, &#39;Stinger&#39;, &#39;Honey&#39;]);<br>box.put(&#39;memories&#39;, {&#39;firstFlight&#39;: &#39;Sunny Day&#39;, &#39;bestNectar&#39;: &#39;Rose&#39;});<br>box.putAll({&#39;favoriteFlower&#39;: &#39;Lavender&#39;, &#39;wingSpeed&#39;: 210});</pre><p>Here, the put method is used to store a list under the key &#39;friends&#39;. The list includes three strings representing the names of the friends: &#39;Buzzy&#39;, &#39;Stinger&#39;, and &#39;Honey&#39;.</p><p>The line of code is using the putAll method to store multiple key-value pairs in a Hive box.</p><h3>Deleting Data</h3><p>Time for some spring cleaning in the hive! To remove a single entry from your box, use box.delete():</p><pre>final deleted = box.delete(&#39;lavenderHoney&#39;);<br>print(&#39;Honey eaten: $deleted&#39;); // Honey eaten: true</pre><p>Perhaps it’s time for a complete reset, making space for a fresh batch of honey. If you’re looking to remove all key-value pairs from a box.</p><pre>box.clear();</pre><p>This tutorial assumes you have a basic understanding of Flutter development and Hive usage. Make sure to adapt the code according to your specific needs and data models.</p><p>Happy coding !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59eeb2f8cc79" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Navigation and Routing]]></title>
            <link>https://medium.com/@emanyaqoob/certainly-e41bc25617a6?source=rss-c74b278e156a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e41bc25617a6</guid>
            <category><![CDATA[routing]]></category>
            <dc:creator><![CDATA[Eman Yaqoob]]></dc:creator>
            <pubDate>Sat, 19 Aug 2023 12:02:39 GMT</pubDate>
            <atom:updated>2024-08-08T03:01:45.799Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*sxE55qFuMAiJneG84zlEXg.png" /><figcaption>navigation and routing</figcaption></figure><h3>Flutter Navigation</h3><p>In the world of mobile app development, efficient navigation is a crucial aspect of providing a smooth user experience. Flutter, a popular cross-platform framework, offers an intuitive way to manage navigation and routing within your app. In this tutorial, we’ll guide you through the process of creating a Flutter application with named routes and parameter passing. By the end of this tutorial, you’ll have a fully functional Flutter app with multiple screens that you can navigate between seamlessly.</p><p>Setting Up Routing Constants:</p><p>Create a constants.dart file to define routing constants:</p><p>To start, create a constants.dart file to define routing constants. These constants will be used to specify the routes throughout your app.</p><pre>const String homeRoute = &#39;/&#39;;<br>const String feedRoute = &#39;/feed&#39;;<br>const String detailsRoute = &#39;/details&#39;;<br>const String settingsRoute = &#39;/settings&#39;;</pre><p>Create a router.dart file to handle routing logic:</p><p>Next, create a router.dart file to handle the routing logic. This router will determine which screen to display based on the specified route.</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;constants.dart&#39;;<br>import &#39;views/home.dart&#39;;<br>import &#39;views/feed.dart&#39;;<br>import &#39;views/details.dart&#39;;<br>import &#39;views/settings.dart&#39;;<br><br>class Router {<br>  static Route&lt;dynamic&gt; generateRoute(RouteSettings settings) {<br>    switch (settings.name) {<br>      case homeRoute:<br>        return MaterialPageRoute(builder: (_) =&gt; Home());<br>      case feedRoute:<br>        return MaterialPageRoute(builder: (_) =&gt; Feed());<br>      case detailsRoute:<br>        var data = settings.arguments as String;<br>        return MaterialPageRoute(builder: (_) =&gt; Details(data));<br>      case settingsRoute:<br>        return MaterialPageRoute(builder: (_) =&gt; Settings());<br>      default:<br>        return MaterialPageRoute(<br>          builder: (_) =&gt; Scaffold(<br>            body: Center(<br>              child: Text(&#39;No route defined for ${settings.name}&#39;),<br>            ),<br>          ),<br>        );<br>    }<br>  }<br>}</pre><p>Create view files: home.dart, feed.dart, details.dart, and settings.dart.</p><p>Now, create separate view files for each screen: home.dart, feed.dart, details.dart, and settings.dart. These files will define the content and structure of each screen.</p><p>Here’s a simplified example of the view files</p><pre>// home.dart<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;../constants.dart&#39;;<br>import &#39;../router.dart&#39;;<br><br>class Home extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      floatingActionButton: FloatingActionButton(<br>        onPressed: () {<br>          Navigator.pushNamed(context, feedRoute);<br>        },<br>        child: Icon(Icons.arrow_forward),<br>      ),<br>      body: Center(child: Text(&#39;Home&#39;)),<br>    );<br>  }<br>}<br><br>// feed.dart<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;../constants.dart&#39;;<br>import &#39;../router.dart&#39;;<br><br>class Feed extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      floatingActionButton: FloatingActionButton(<br>        onPressed: () {<br>          Navigator.pushNamed(context, detailsRoute, arguments: &#39;Data from Feed&#39;);<br>        },<br>        child: Icon(Icons.arrow_forward),<br>      ),<br>      body: Center(child: Text(&#39;Feed&#39;)),<br>    );<br>  }<br>}<br><br>// details.dart<br>import &#39;package:flutter/material.dart&#39;;<br><br>class Details extends StatelessWidget {<br>  final String data;<br>  Details(this.data);<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: Center(child: Text(&#39;Details: $data&#39;)),<br>    );<br>  }<br>}<br><br>// settings.dart<br>import &#39;package:flutter/material.dart&#39;;<br><br>class Settings extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: Center(child: Text(&#39;Settings&#39;)),<br>    );<br>  }<br>}</pre><p>Setting Up the Main Application:</p><p>In your main.dart file, set up the main application by defining a MaterialApp widget. This widget specifies the initial route and how to generate routes using the Router class you created.</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;router.dart&#39;;<br>import &#39;constants.dart&#39;;<br><br>void main() {<br>  runApp(MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      onGenerateRoute: Router.generateRoute,<br>      initialRoute: homeRoute,<br>    );<br>  }<br>}</pre><p>Now you have a complete Flutter application with 3–4 screens using named routes and parameters. When you run the app, you should be able to navigate between the different screens by tapping on the floating action buttons and see the data being passed to the Details screen.</p><p>This approach allows for efficient navigation between screens while passing data when needed. As you continue to develop your Flutter app, you can expand upon this foundation to create a fully-featured and user-friendly mobile application. Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e41bc25617a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Future & Streams in dart]]></title>
            <link>https://medium.com/@emanyaqoob/future-streams-in-dart-7e2bd86ebbfd?source=rss-c74b278e156a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e2bd86ebbfd</guid>
            <category><![CDATA[future-streams-in-dart]]></category>
            <dc:creator><![CDATA[Eman Yaqoob]]></dc:creator>
            <pubDate>Wed, 21 Jun 2023 08:03:06 GMT</pubDate>
            <atom:updated>2023-09-25T07:15:20.268Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S_nRN3700QlmGQwI8CMNOQ.png" /></figure><h3><strong>Future</strong></h3><p>Dart’s Future class is used to represent a value that will be available in the future. Futures are commonly used in asynchronous programming to handle long-running tasks without blocking the main thread.</p><p>Generally we will need to work with a future value in following cases:</p><ul><li>getting data from a server</li><li>querying data from a database</li><li>reading a file</li><li>doing a complicated computational work.</li></ul><p><strong>Getting data from a server:</strong></p><pre>Future&lt;String&gt; fetchDataFromServer() async {<br>  // Perform an asynchronous HTTP request and return the response<br>  // as a Future&lt;String&gt;<br>  // ...<br>}<br><br>void main() {<br>  fetchDataFromServer().then((data) {<br>    // Use the fetched data<br>    print(data);<br>  }).catchError((error) {<br>    // Handle any errors that occurred during the request<br>    print(&#39;Error: $error&#39;);<br>  });<br>}</pre><p><strong>Querying data from a database:</strong></p><pre>Future&lt;List&lt;Map&lt;String, dynamic&gt;&gt;&gt; queryDatabase() async {<br>  // Perform an asynchronous database query and return the result<br>  // as a Future&lt;List&lt;Map&lt;String, dynamic&gt;&gt;&gt;<br>  // ...<br>}<br><br>void main() {<br>  queryDatabase().then((result) {<br>    // Process the queried data<br>    print(result);<br>  }).catchError((error) {<br>    // Handle any errors that occurred during the query<br>    print(&#39;Error: $error&#39;);<br>  });<br>}</pre><p><strong>Reading a file:</strong></p><pre>Future&lt;String&gt; readFile() async {<br>  // Perform an asynchronous file read and return the contents<br>  // as a Future&lt;String&gt;<br>  // ...<br>}<br><br>void main() {<br>  readFile().then((contents) {<br>    // Use the contents of the file<br>    print(contents);<br>  }).catchError((error) {<br>    // Handle any errors that occurred during the file read<br>    print(&#39;Error: $error&#39;);<br>  });<br>}</pre><p>Dart program that demonstrates the uses of futures in the Dart language. This program showcases how to fetch data from an API asynchronously using futures, handle errors, and wait for multiple futures to complete using <strong>Future.wait.</strong></p><pre>import &#39;dart:async&#39;;<br>import &#39;dart:convert&#39;;<br>import &#39;package:http/http.dart&#39; as http;<br><br>// Function to fetch data asynchronously from an API<br>Future&lt;List&lt;dynamic&gt;&gt; fetchData() async {<br>  final response = await http.get(Uri.parse(&#39;https://jsonplaceholder.typicode.com/posts&#39;));<br>  <br>  if (response.statusCode == 200) {<br>    return json.decode(response.body);<br>  } else {<br>    throw Exception(&#39;Failed to fetch data&#39;);<br>  }<br>}<br><br>void main() {<br>  print(&#39;Fetching data...&#39;);<br>  <br>  final future = fetchData(); // Call the function to get a future object<br>  <br>  future.then((data) {<br>    print(&#39;Data fetched successfully:&#39;);<br>    for (var item in data) {<br>      print(&#39;Title: ${item[&#39;title&#39;]}&#39;);<br>      print(&#39;Body: ${item[&#39;body&#39;]}&#39;);<br>      print(&#39;---&#39;);<br>    }<br>  }).catchError((error) {<br>    print(&#39;Error occurred: $error&#39;);<br>  }).whenComplete(() {<br>    print(&#39;Program completed&#39;);<br>  });<br>}</pre><p>In this example, we’re using the http package to make an asynchronous HTTP GET request to the <strong>JSONPlaceholder</strong> API, which returns a list of posts. Here’s a breakdown of the program:</p><p>Import the necessary packages: <strong>dart:async, dart:convert, and package:http/http.dart.</strong></p><p>Define the <strong>fetchData()</strong> function, which returns a Future&lt;List&lt;dynamic&gt;&gt;. This function makes an asynchronous HTTP GET request to the API using the http package. If the request is successful (status code 200), we decode the response body and return it as a List&lt;dynamic&gt;. Otherwise, we throw an exception.</p><p>In the main() function, we call <strong>fetchData() </strong>and assign the returned future to the future variable.</p><p>We use the then() method on the future to handle the successful completion of the future. Inside the then() callback, we print the fetched data by iterating over the returned list of posts and accessing the title and body properties of each post.</p><p>If an error occurs during the execution of the future, the <strong>catchError()</strong> method is invoked, and the error message is printed.</p><p>The <strong>whenComplete()</strong> method is used to print a completion message, which is executed regardless of whether the future completed successfully or encountered an error.</p><p>Output</p><pre>Fetching data...<br>Data fetched successfully:<br>Title: sunt aut facere repellat provident occaecati excepturi optio reprehenderit<br>Body: quia et suscipit<br>suscipit recusandae consequuntur expedita et cum<br>reprehenderit molestiae ut ut quas totam<br>nostrum rerum est autem sunt rem eveniet architecto<br>---<br>Title: temporibus sit alias delectus eligendi possimus magni<br>Body: quo deleniti praesentium dicta non quod<br>aut est molestias<br>molestias et officia quis nihil<br>itaque dolorem quia<br>---<br>Title: at nam consequatur ea labore ea harum<br>Body: cupiditate quo est a modi nesciunt soluta<br>ipsa voluptas error itaque dicta in<br>autem qui minus magnam et distinctio eum<br>accusamus ratione error aut<br>---<br>Program completed</pre><h3>Stream</h3><p><strong>Streams</strong> function in a similar way, but they deal with sequences of events instead of single events. So, streams are to future objects what iterators are to integers. Streams emit data events (or elements), error events, and “done” events to notify the end of the event flow.</p><p>A Dart program that demonstrates the uses of streams in the Dart language. This program showcases how to create a stream, listen for data events, handle errors, and close the stream.</p><pre>mport &#39;dart:async&#39;;<br><br>void main() {<br>  // Create a stream controller<br>  final streamController = StreamController&lt;int&gt;();<br><br>  // Add some data to the stream<br>  for (var i = 1; i &lt;= 5; i++) {<br>    streamController.sink.add(i);<br>  }<br><br>  // Listen to the stream<br>  final subscription = streamController.stream.listen(<br>    (data) {<br>      print(&#39;Received data: $data&#39;);<br>    },<br>    onError: (error) {<br>      print(&#39;Error occurred: $error&#39;);<br>    },<br>    onDone: () {<br>      print(&#39;Stream closed&#39;);<br>    },<br>  );<br><br>  // Add more data to the stream<br>  for (var i = 6; i &lt;= 10; i++) {<br>    streamController.sink.add(i);<br>  }<br><br>  // Handle errors in the stream<br>  streamController.sink.addError(&#39;Some error occurred&#39;);<br><br>  // Close the stream<br>  streamController.close();<br><br>  // Cancel the subscription<br>  subscription.cancel();<br>}</pre><p>In this example, we’re using a <strong>StreamController</strong> to create and control the stream.</p><p><strong>StreamController:</strong> A stream controller is a fundamental component in Dart for creating and managing streams. It acts as a source or origin of data that can be listened to by subscribers. It provides methods for adding data to the stream and managing subscriptions. Here’s a breakdown of the program:</p><p>Import the necessary package:<strong> dart:async.</strong></p><p>In the main() function, create a <strong>StreamController </strong>named streamController. The type parameter &lt;int&gt; indicates that the stream will emit integer values.</p><p>Use the sink property of the <strong>streamController</strong> to add data to the stream. In this case, we’re adding the numbers 1 to 10.</p><p>Call the stream getter on the <strong>streamController</strong> to get the stream associated with it.</p><p>Use the<strong> listen()</strong> method on the stream to start listening for data events. The <strong>listen() </strong>method takes three optional parameters.</p><p>(The first parameter is the callback function that will be called when new data is available in the stream. In this case, we print the received data.The onError parameter is a callback function that will be called if an error occurs in the stream. We print the error message in this case.The onDone parameter is a callback function that will be called when the stream is closed.)</p><p>After setting up the listener, we add more data to the stream. In this case, we add the numbers 6 to 10.</p><p>We simulate an error in the stream by calling<strong> sink.addError</strong>(‘Some error occurred’).</p><p>We close the stream by calling <strong>streamController.close()</strong>. After closing the stream, no more data can be added to it.</p><p>Finally, we cancel the subscription by calling<strong> subscription.cancel()</strong>. This stops listening to the stream.</p><p>Output</p><pre>Received data: 1<br>Received data: 2<br>Received data: 3<br>Received data: 4<br>Received data: 5<br>Received data: 6<br>Received data: 7<br>Received data: 8<br>Received data: 9<br>Received data: 10<br>Error occurred: Some error occurred<br>Stream closed</pre><p><strong>Single Subscription Stream:</strong></p><pre>import &#39;dart:async&#39;;<br><br>void main() {<br>  final stream = Stream&lt;int&gt;.periodic(Duration(seconds: 1), (count) =&gt; count).take(4);<br><br>  final subscription = stream.listen(<br>    (data) {<br>      String message;<br>      switch (data) {<br>        case 1:<br>          message = &#39;Hey&#39;;<br>          break;<br>        case 2:<br>          message = &#39;Hello&#39;;<br>          break;<br>        case 3:<br>          message = &quot;It&#39;s a sunny day&quot;;<br>          break;<br>        default:<br>          message = &#39;&#39;;<br>      }<br>      if (message.isNotEmpty) {<br>        print(&#39;Received data: $message&#39;);<br>      }<br>    },<br>    onError: (error) {<br>      print(&#39;Error occurred: $error&#39;);<br>    },<br>    onDone: () {<br>      print(&#39;Stream closed&#39;);<br>    },<br>  );<br><br>  Future.delayed(Duration(seconds: 10), () {<br>    subscription.cancel();<br>  });<br>}</pre><p>In this example, we’re creating a single-subscription stream using the <strong>Stream.periodic </strong>constructor, which emits an incrementing count every second (<strong>Duration(seconds: 1))</strong>. The stream is limited to five values using take(5).</p><p>We then listen to the stream using the l<strong>isten()</strong> method. The callback functions for <strong>onData, onError, and onDone</strong> are provided to handle received data, errors, and the stream closure, respectively.</p><p>After three seconds (<strong>Future.delayed)</strong>, we cancel the subscription using <strong>subscription.cancel()</strong> to stop listening to the stream.</p><p>Output</p><pre>Received data: Hey<br>Received data: Hello<br>Received data: It&#39;s a sunny day<br>Stream closed</pre><p><strong>Broadcast Stream:</strong></p><pre>import &#39;dart:async&#39;;<br><br>void main() {<br>  // Create a broadcast stream controller<br>  final streamController = StreamController&lt;int&gt;.broadcast();<br><br>  // Add some data to the stream<br>  for (var i = 1; i &lt;= 5; i++) {<br>    streamController.sink.add(i);<br>  }<br><br>  // Listen to the stream<br>  final subscription1 = streamController.stream.listen(<br>    (data) {<br>      print(&#39;Listener 1: Received data: $data&#39;);<br>    },<br>    onError: (error) {<br>      print(&#39;Listener 1: Error occurred: $error&#39;);<br>    },<br>    onDone: () {<br>      print(&#39;Listener 1: Stream closed&#39;);<br>    },<br>  );<br><br>  // Add another listener to the stream<br>  final subscription2 = streamController.stream.listen(<br>    (data) {<br>      print(&#39;Listener 2: Received data: $data&#39;);<br>    },<br>    onError: (error) {<br>      print(&#39;Listener 2: Error occurred: $error&#39;);<br>    },<br>    onDone: () {<br>      print(&#39;Listener 2: Stream closed&#39;);<br>    },<br>  );<br><br>  // Close the stream<br>  streamController.close();<br><br>  // Cancel the subscriptions<br>  subscription1.cancel();<br>  subscription2.cancel();<br>}</pre><p><strong>.broadcast():</strong> This method is called on the StreamController to create a broadcast stream. A broadcast stream allows multiple listeners to subscribe to it simultaneously and receive the emitted values independently.</p><p>In this example, we’re creating a broadcast stream using a S<strong>treamController</strong> with the<strong> .broadcast() </strong>constructor. This allows multiple listeners to subscribe to the stream and receive the same events.</p><p>We add data to the stream using the <strong>sink.add()</strong> method, and we set up two listeners using the listen() method-one for each subscription.</p><p>Both listeners will receive the same data events, and if an error occurs or the stream is closed, each listener’s respective error and done callbacks will be invoked.</p><p>Finally, we close the stream using <strong>streamController.close()</strong>, and we cancel both subscriptions using <strong>subscription1.cancel()</strong> and <strong>subscription2.cancel().</strong></p><p>Output</p><pre>Listener 1: Received data: 1<br>Listener 2: Received data: 1<br>Listener 1: Received data: 2<br>Listener 2: Received data: 2<br>Listener 1: Received data: 3<br>Listener 2: Received data: 3<br>Listener 1: Received data: 4<br>Listener 2: Received data: 4<br>Listener 1: Received data: 5<br>Listener 2: Received data: 5<br>Listener 1: Stream closed<br>Listener 2: Stream closed</pre><p>Lets Consider we have a messaging application that allows users to send and receive messages in real-time. We can use a broadcast stream to handle incoming messages and update multiple UI components simultaneously.</p><pre>import &#39;dart:async&#39;;<br><br>class Message {<br>  final String sender;<br>  final String content;<br><br>  Message(this.sender, this.content);<br>}<br><br>class MessagingService {<br>  final StreamController&lt;Message&gt; _messageController = StreamController&lt;Message&gt;.broadcast();<br><br>  Stream&lt;Message&gt; get messageStream =&gt; _messageController.stream;<br><br>  void sendMessage(String sender, String content) {<br>    final message = Message(sender, content);<br>    _messageController.sink.add(message);<br>  }<br><br>  void dispose() {<br>    _messageController.close();<br>  }<br>}<br><br>void main() {<br>  final messagingService = MessagingService();<br><br>  // User 1 listens to incoming messages<br>  final subscription1 = messagingService.messageStream.listen((message) {<br>    print(&#39;User received a message  from ${message.sender}: ${message.content}&#39;);<br>  });<br><br>  // User 2 listens to incoming messages<br>  final subscription2 = messagingService.messageStream.listen((message) {<br>    print(&#39;User received a message  from ${message.sender}:  ${message.content}&#39;);<br>  });<br><br>  // User 3 listens to incoming messages<br>  final subscription3 = messagingService.messageStream.listen((message) {<br>    print(&#39;User received a message  from ${message.sender}: ${message.content}&#39;);<br>  });<br><br>  // Simulating message sending<br>  messagingService.sendMessage(&#39;User 1&#39;, &#39;Hello!&#39;);<br>  messagingService.sendMessage(&#39;User 2&#39;, &#39;How are you doing?&#39;);<br>  messagingService.sendMessage(&#39;User 3&#39;, &#39;I have an important announcement!&#39;);<br><br>  // Clean up<br>  subscription1.cancel();<br>  subscription2.cancel();<br>  subscription3.cancel();<br>  messagingService.dispose();<br>}</pre><p>we have a <strong>MessagingService</strong> class that manages the messaging functionality. It has a <strong>StreamController</strong> called <strong>_messageController, </strong>which is a broadcast stream controller responsible for handling incoming messages.</p><p>The Message class represents a message with a sender and content.</p><p>The<strong> messageStream </strong>getter provides access to the broadcast stream of messages.</p><p>The sendMessage method allows sending a new message. It creates a Message object and adds it to the stream using the <strong>_messageController.sink.add()</strong> method.</p><p>In the <strong>main()</strong> function, we create an instance of the <strong>MessagingService.</strong></p><p>Three users (User 1, User 2, and User 3) subscribe to the <strong>messageStream</strong> using the listen() method. Whenever a new message arrives, each user’s callback function is triggered, and they print the received message.</p><p>We simulate sending three messages using the <strong>sendMessage() </strong>method of the <strong>MessagingService.</strong></p><p>Finally, we clean up by canceling the subscriptions and calling dispose() on the <strong>MessagingService</strong> to close the stream and release resources.</p><p>In this example, the broadcast stream allows multiple users to receive messages simultaneously without interfering with each other’s subscriptions. It enables real-time communication and ensures that every subscribed user receives the incoming messages.</p><p>Output</p><pre>User received a message from User 1: Hello!<br>User received a message from User 2: How are you doing?<br>User received a message from User 3: I have an important announcement!<br>User received a message from User 1: Hello!<br>User received a message from User 2: How are you doing?<br>User received a message from User 3: I have an important announcement!<br>User received a message from User 1: Hello!<br>User received a message from User 2: How are you doing?<br>User received a message from User 3: I have an important announcement!<br></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e2bd86ebbfd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Async coding in dart]]></title>
            <link>https://medium.com/@emanyaqoob/async-coding-in-dart-f4dda78072bd?source=rss-c74b278e156a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4dda78072bd</guid>
            <category><![CDATA[async-coding-in-dart]]></category>
            <dc:creator><![CDATA[Eman Yaqoob]]></dc:creator>
            <pubDate>Mon, 19 Jun 2023 12:51:13 GMT</pubDate>
            <atom:updated>2023-09-25T07:40:41.582Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*efVPmtFrQS2dIATZbCcPNQ.png" /></figure><p>Isolates and Event Loops in dart</p><p>In Dart, isolates and event loops are key concepts related to concurrent programming and handling asynchronous operations. Let’s explore each concept:</p><p><strong>Isolates: </strong>Isolates are independent units of concurrent execution in Dart. Each isolate has its own memory heap and runs in its own thread, allowing it to perform computations concurrently without sharing memory with other isolates. Isolates communicate by passing messages between them.</p><p>To create an isolate, you can use the Isolate.spawn function, which takes a callback function as an argument. The callback function runs in the newly created isolate.</p><pre>import &#39;dart:isolate&#39;;<br><br>void isolateEntry(SendPort sendPort) {<br>  // Perform computations or asynchronous operations in the isolate<br>  sendPort.send(&#39;Message from isolate&#39;);<br>}<br><br>void main() async {<br>  ReceivePort receivePort = ReceivePort();<br>  Isolate isolate = await Isolate.spawn(isolateEntry, receivePort.sendPort);<br><br>  receivePort.listen((message) {<br>    print(message);<br>  });<br><br>  // ...<br>}</pre><p><strong>Event Loops: </strong>An event loop is responsible for managing and processing events in Dart, including timers, IO operations, and message passing between isolates. It ensures that code runs asynchronously and efficiently.</p><p>Dart uses a single-threaded event loop model. The event loop continuously checks for pending events and executes the associated callbacks. It interleaves the execution of different events, allowing concurrent processing of asynchronous operations.</p><pre>import &#39;dart:async&#39;;<br><br>void main() {<br>  print(&#39;Start&#39;);<br><br>  Timer(Duration(seconds: 1), () {<br>    print(&#39;Timer callback&#39;);<br>  });<br><br>  Future.delayed(Duration(seconds: 2), () {<br>    print(&#39;Future callback&#39;);<br>  });<br><br>  print(&#39;End&#39;);<br>}</pre><p>It’s important to note that isolates and event loops work together to achieve concurrency and handle asynchronous operations in Dart. Isolates provide true concurrency by running in separate threads, while the event loop enables efficient scheduling and interleaving of asynchronous operations within a single isolate.</p><p><strong>Generator Functions</strong></p><p>In Dart, generator functions are special functions that can be used to create iterable sequences of values. They are defined using the sync* or async* keywords, depending on whether they produce synchronous or asynchronous sequences, respectively.</p><p>Here’s an explanation of generator functions in Dart along with code examples:</p><p><strong>Synchronous Generator Function (sync*):</strong> A synchronous generator function produces a sequence of values synchronously. It uses the yield keyword to emit values one at a time, allowing the caller to iterate over the generated values.</p><p>Example:</p><pre>Iterable&lt;int&gt; countUpTo(int n) sync* {<br>  for (int i = 1; i &lt;= n; i++) {<br>    yield i;<br>  }<br>}<br><br>void main() {<br>  var sequence = countUpTo(5);<br>  for (var number in sequence) {<br>    print(number);<br>  }<br>}</pre><p>In this example, the countUpTo function is a synchronous generator function defined with sync*. It generates a sequence of integers from 1 to n. The yield keyword is used to emit each value and wait for the caller for the next one. When countUpTo(5) is called, it returns an iterable sequence. We can iterate over this sequence using a for-in loop and print each number.</p><p>The output will be:</p><pre>1<br>2<br>3<br>4<br>5</pre><ul><li><strong>synchronous operation</strong>: A synchronous operation blocks other operations from executing until it completes.</li><li><strong>synchronous function</strong>: A synchronous function only performs synchronous operations.</li><li><strong>asynchronous operation</strong>: Once initiated, an asynchronous operation allows other operations to execute before it completes.</li><li><strong>asynchronous function</strong>: An asynchronous function performs at least one asynchronous operation and can also perform <em>synchronous</em> operations.</li></ul><p><strong>Asynchronous Generator Function (async*):</strong></p><p>An asynchronous generator function, defined using async* in Dart, allows you to create a stream of values asynchronously. It combines the behavior of asynchronous operations using await with the ability to emit values using yield.</p><p>Here’s an explanation of how to use an asynchronous generator function with async* and await in Dart:</p><pre>import &#39;dart:async&#39;;<br><br>Stream&lt;int&gt; generateRandomNumbers(int count) async* {<br>  for (int i = 0; i &lt; count; i++) {<br>    await Future.delayed(Duration(seconds: 1));<br>    yield i;<br>  }<br>}<br><br>void main() async {<br>  var stream = generateRandomNumbers(5);<br>  await for (var number in stream) {<br>    print(number);<br>  }<br>}</pre><p>In this example, we have an asynchronous generator function called generateRandomNumbers, defined with async*. It produces a stream of random numbers. Inside the loop, we use await to delay the emission of each value by one second using Future.delayed, and then we use yield to emit the current value of i.</p><p>In the main function, we create a stream using generateRandomNumbers(5). We use the await for loop to iterate over the stream asynchronously. The loop will pause execution and wait for each value emitted by the stream, and then we can perform operations on each value, such as printing it.</p><p>When executed, this code will print random numbers approximately one second apart, as generated by the generateRandomNumbers function.</p><p>The combination of async* and await allows you to create a sequence of asynchronous values using the power of streams and asynchronous operations.</p><p>Remember, when using an asynchronous generator function, the surrounding function must be marked as async, and you can consume the generated sequence using the await for loop or other stream-related operations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4dda78072bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>