<?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 Mahmoud Saleh on Medium]]></title>
        <description><![CDATA[Stories by Mahmoud Saleh on Medium]]></description>
        <link>https://medium.com/@mahmoudsaal7?source=rss-4a3570d9b749------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*kTRFKddGuH-C1cXsPue6cw.jpeg</url>
            <title>Stories by Mahmoud Saleh on Medium</title>
            <link>https://medium.com/@mahmoudsaal7?source=rss-4a3570d9b749------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 12:50:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mahmoudsaal7/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[Elevating Software Development: A Showcase of Automation in Action]]></title>
            <link>https://medium.com/@mahmoudsaal7/elevating-software-development-a-showcase-of-automation-in-action-fc764a7e15d4?source=rss-4a3570d9b749------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc764a7e15d4</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[script]]></category>
            <dc:creator><![CDATA[Mahmoud Saleh]]></dc:creator>
            <pubDate>Sun, 31 Dec 2023 07:57:30 GMT</pubDate>
            <atom:updated>2023-12-31T07:57:30.279Z</atom:updated>
            <content:encoded><![CDATA[<h4>Transforming Flutter Localization with Node.js Scripting</h4><figure><img alt="Abstract image combining elements of code, gears, and a light bulb, symbolizing innovation in software development." src="https://cdn-images-1.medium.com/max/1024/1*M6YK1hG9Lh5f2EQghz-8iA.png" /></figure><p>In the world of Flutter app development, handling multiple languages can be a daunting task. Localization, the process of adapting your app to different languages, requires meticulous handling of text strings. This article introduces a Node.js script that automates the extraction and management of these strings, turning a tedious task into a breeze.</p><h4>The Challenge in Flutter</h4><p>Typically, Flutter developers handle strings within the code, enclosed in either single or double quotes. When it comes to localizing these strings for different languages, manually extracting and managing them can be error-prone and time-consuming.</p><h4>A Node.js Script Solution</h4><p>Enter the world of automation with a Node.js script! This script simplifies the process by scanning Dart files in a Flutter project, extracting strings, generating localization keys in snake_case format, and replacing the original strings with these keys.</p><h4>Implementing the Script</h4><ol><li><strong>Environment Setup:</strong></li></ol><ul><li>Ensure Node.js is installed.</li><li>Install the glob package via npm for file pattern matching</li></ul><p>2. <strong>Understanding the Script:</strong></p><p>We need the following methods in out script:</p><ul><li><strong>toSnakeCase </strong>Function: Converts strings to snake_case for uniform key formatting.</li><li><strong>capitalizeFirstChar </strong>Function: Ensures the first character of each string is capitalized, maintaining a consistent style.</li><li><strong>processFile </strong>Function: Extracts strings from Dart files, focusing on those that contain alphabetic characters and spaces.</li><li><strong>processAndReplaceFile </strong>Function: Replaces the original strings in Dart files with their new localization keys.</li><li><strong>main </strong>Function: The core of the script, coordinating the extraction, key generation, and replacement process.</li></ul><p>3. Full Script:</p><pre>const fs = require(&#39;fs&#39;);<br>const path = require(&#39;path&#39;);<br>const glob = require(&#39;glob&#39;);<br><br>// Directory containing your features<br>const FEATURES_DIR = path.join(__dirname, &#39;lib/core&#39;);<br><br>// Output file for the key-value pairs<br>const OUTPUT_FILE = path.join(__dirname, &#39;localization.dart&#39;);<br><br>// Function to convert a string to snake_case<br>const toSnakeCase = (str) =&gt; str.toLowerCase().replace(/[\W_]+/g, &quot;_&quot;).replace(/^_+|_+$/g, &quot;&quot;);<br><br>// Function to capitalize the first character of a string<br>const capitalizeFirstChar = (str) =&gt; str.charAt(0).toUpperCase() + str.slice(1);<br><br>// Function to process a Dart file and match strings<br>const processFile = (filePath) =&gt; {<br>    const content = fs.readFileSync(filePath, &#39;utf8&#39;);<br>    const matches = content.match(/(?&lt;=[&#39;&quot;])[a-zA-Z&amp;_: ]+(?=[&#39;&quot;])/g) || [];<br>    return matches.filter(str =&gt; !str.includes(&#39;Identifier&#39;) &amp;&amp; !str.includes(&#39;route&#39;))<br>                  .map(capitalizeFirstChar);<br>};<br><br>// Function to process and replace strings in a Dart file<br>const processAndReplaceFile = (filePath, keyValueMap) =&gt; {<br>    let content = fs.readFileSync(filePath, &#39;utf8&#39;);<br>    let modified = false;<br><br>    keyValueMap.forEach((value, key) =&gt; {<br>        const regex = new RegExp(`([&#39;&quot;])${value}\\1`, &#39;g&#39;);<br>        if (content.match(regex)) {<br>            modified = true;<br>            content = content.replace(regex, `&#39;${key}&#39;`);<br>        }<br>    });<br><br>    if (modified) {<br>        fs.writeFileSync(filePath, content, &#39;utf8&#39;);<br>        console.log(`Updated file: ${filePath}`);<br>    } else {<br>        console.log(`No changes made to file: ${filePath}`);<br>    }<br>};<br><br>// Main function to extract strings, generate key-value pairs, and replace strings<br>const main = () =&gt; {<br>    const allStrings = new Set();<br>    const keyValueMap = new Map();<br><br>    const files = glob.sync(`${FEATURES_DIR}/**/presentation/**/*.dart`);<br>    console.log(`Found ${files.length} files to process.`);<br><br>    files.forEach((file) =&gt; {<br>        const extractedStrings = processFile(file);<br>        console.log(`Extracted ${extractedStrings.length} strings from ${file}`);<br><br>        extractedStrings.forEach((str) =&gt; {<br>            if (!allStrings.has(str)) {<br>                const key = `${toSnakeCase(str)}`;<br>                keyValueMap.set(key, str);<br>                allStrings.add(str);<br>            }<br>        });<br>    });<br><br>    const keyValuePairs = Array.from(keyValueMap).map(([key, value]) =&gt;<br>        `  &#39;${key}&#39;: &#39;${value.replace(/&#39;/g, &quot;\\&#39;&quot;)}&#39;,`<br>    );<br>    fs.writeFileSync(OUTPUT_FILE, `final Map&lt;String, String&gt; localizedStrings = {\n${keyValuePairs.join(&#39;\n&#39;)}\n};\n`);<br>    console.log(`Localization file created at ${OUTPUT_FILE}`);<br><br>    files.forEach((file) =&gt; {<br>        processAndReplaceFile(file, keyValueMap);<br>    });<br>};<br><br>main();</pre><p>3. <strong>Handling Special Cases</strong>:</p><p>The script is tailored to ignore strings containing non-alphabetic characters, But in my case I had to include specific characters such as ‘&amp;’, ‘:’, and ‘_’, and exclude specific keywords like ‘Identifier’ and ‘route’, to ensure only relevant text is localized.</p><blockquote>So, feel free to edit the regex to apply what ever you want.</blockquote><h4>Running the Script</h4><ul><li>Place the script at the root of your Flutter project.</li><li>Modify the script paths to point to your Dart files and where you want the localization file created.</li><li>Run the script with Node.js, and watch as it automates the localization process!</li></ul><h4>Conclusion</h4><p>Automating the localization process in Flutter not only saves time but also reduces the likelihood of errors. This Node.js script is a testament to how automation can significantly streamline development workflows in Flutter app development.</p><h4>Important Notes:</h4><ul><li>Back-Up Your Files! Always back up your files before running scripts that modify code.</li><li>Customize As Needed: Feel free to adjust the script to fit the specific needs of your project.</li></ul><p><a href="https://www.linkedin.com/in/mahmoudsalehm979/"><strong>Follow me for updates</strong></a> on new articles and discussions. Your support and feedback are what drive these conversations forward!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc764a7e15d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Flutter’s Architecture: Under the Hood of a Flutter App]]></title>
            <link>https://medium.com/@mahmoudsaal7/demystifying-flutters-architecture-under-the-hood-of-a-flutter-app-6126e1800f66?source=rss-4a3570d9b749------2</link>
            <guid isPermaLink="false">https://medium.com/p/6126e1800f66</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Mahmoud Saleh]]></dc:creator>
            <pubDate>Sat, 09 Dec 2023 15:07:16 GMT</pubDate>
            <atom:updated>2023-12-09T15:07:16.381Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nPHg0l-NoidVIQYR_kbJ7A.png" /></figure><p>Flutter, Google’s UI toolkit for building natively compiled applications for mobile, web, and desktop from a single codebase, has been a game-changer in the world of cross-platform app development. Its unique approach to rendering and its use of the Dart programming language set it apart. In this article, we’ll delve deep into the architecture of Flutter, understanding the elements that make it both powerful and unique.</p><h3>Understanding the Core of Flutter: The Engine and the Framework</h3><p>At the heart of Flutter’s architecture are two key components: the Engine and the Framework. The Engine, written primarily in C++, provides low-level rendering support using Google’s Skia graphics library. It also includes platform-specific SDKs that bridge with the host operating system. The Framework, written in Dart, offers a rich set of libraries that are used to develop the app’s UI.</p><h3>The Engine: Powering Performance</h3><p>The Flutter Engine is responsible for core primitives such as graphics (via Skia), text layout, and I/O. This engine is what makes Flutter apps so performant, as it compiles to native code.</p><h3>The Framework: A Rich Set of Libraries</h3><p>The Framework layer, which is much more extensive, includes everything from basic widgets to higher-level tools like animations and gestures. This is where the developer spends most of their time, building and styling their app using the rich set of widgets Flutter provides.</p><h3>The Dart Platform: The Backbone of Flutter</h3><p>Flutter uses Dart, a language optimized for fast apps on any platform. Dart allows Flutter to avoid the need for a separate declarative layout language like XML or separate visual interface builders because Dart’s declarative, programmatic layout is easy to read and visualize. It also means less context-switching for developers.</p><h3>Hot Reload: A Developer’s Delight</h3><p>One of the most celebrated features of Dart within Flutter is Hot Reload, which allows developers to see the effects of their changes almost instantly, without losing the current application state.</p><h3>Widgets: The Building Blocks of Flutter Apps</h3><p>In Flutter, everything is a widget. Widgets are the basic building blocks of a Flutter app’s user interface. Each widget is an immutable declaration of part of the user interface. Flutter combines these widgets to create complex layouts. Widgets can be of two types: Stateless, which are static, and Stateful, which hold state.</p><h3>The Widget Tree: Organizing UI Components</h3><p>Flutter apps are organized in a tree of widgets. This tree structure enables the efficient rendering of UIs. When the state of a widget changes, only that widget is redrawn, not the entire UI.</p><h3>The Rendering Process: How Flutter Draws Your App</h3><p>Flutter’s rendering process is what sets it apart. It uses its own high-performance rendering engine to draw widgets. Here’s how it works:</p><ol><li><strong>Layout</strong>: Each widget on the screen is visited and its dimensions are calculated.</li><li><strong>Painting</strong>: Each widget is then painted on the screen in the order it appears in the widget tree.</li><li><strong>Compositing</strong>: Finally, the rendered frames are sent to the device’s screen.</li></ol><h3>Conclusion</h3><p>Flutter’s architecture is a blend of simplicity and power. By understanding the engine and framework, the role of Dart, the concept of widgets, and the rendering process, developers can better leverage Flutter’s capabilities to create efficient, beautiful applications. Whether you’re a seasoned developer or just starting out, Flutter’s cohesive ecosystem and robust architecture make it an excellent choice for app development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6126e1800f66" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Repository Pattern in Flutter: Enhancing Your App’s Architecture]]></title>
            <link>https://medium.com/@mahmoudsaal7/repository-pattern-in-flutter-enhancing-your-apps-architecture-56579831c498?source=rss-4a3570d9b749------2</link>
            <guid isPermaLink="false">https://medium.com/p/56579831c498</guid>
            <category><![CDATA[repository-pattern]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[repositories]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <dc:creator><![CDATA[Mahmoud Saleh]]></dc:creator>
            <pubDate>Sun, 12 Nov 2023 17:12:03 GMT</pubDate>
            <atom:updated>2023-11-12T17:12:03.088Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*webDwzGsppg09Cr8BEyL5A.png" /></figure><h3>Introduction</h3><p>Flutter, the UI toolkit from Google, has gained immense popularity for building beautiful and natively compiled applications. However, as Flutter applications grow in complexity, managing data efficiently becomes crucial. Enter the repository pattern — a strategic solution for effective data management. This article delves into what the repository pattern is, its significance in Flutter, and when it’s most advantageous to use.</p><h3>Understanding the Repository Pattern</h3><p>At its core, the repository pattern is a design principle used to manage data flow between the application and data sources (like databases or network requests). It acts as a middle layer, a bridge if you will, between the business logic and data fetching mechanisms. This abstraction ensures that your business logic doesn’t need to know where or how data is stored or retrieved.</p><h3>Advantages of the Repository Pattern in Flutter</h3><p>Implementing the repository pattern in Flutter brings numerous benefits:</p><ol><li>Separation of Concerns: It keeps the UI and logic separate from data source operations, resulting in a cleaner and more organized codebase.</li><li>Simplification of Data Handling: With a centralized repository, data management becomes more straightforward and consistent.</li><li>Enhanced Testability: Testing becomes easier as you can mock the repositories instead of real data sources.</li></ol><h3>Implementing the Repository Pattern in Flutter</h3><p><strong>Step 1</strong>: Define Data Sources: The first step is to define your data sources. These are the classes responsible for fetching data from different sources like APIs, local databases, or even mock sources for testing.</p><pre>class ApiDataSource {<br>  Future&lt;Data&gt; fetchData() {<br>    // Implementation for fetching data from an API<br>  }<br>}<br><br>class LocalDataSource {<br>  Future&lt;Data&gt; fetchData() {<br>    // Implementation for fetching data from local database<br>  }<br>}</pre><p><strong>Step 2:</strong> Define a Repository Interface: This interface outlines the data operations without being dependent on their concrete implementations.</p><p><strong>Step 3:</strong> Create Repository Implementations: The repository implementations will use the data source objects to fetch data. This way, the repository acts as a mediator between the business logic and data fetching mechanisms.</p><pre>class DataRepository implements Repository {<br>  final ApiDataSource apiDataSource;<br>  final LocalDataSource localDataSource;<br><br>  DataRepository(this.apiDataSource, this.localDataSource);<br><br>  Future&lt;Data&gt; fetchData() {<br>    // Use data sources to fetch data<br>  }<br>}</pre><p>Step 4: Use the Repository in Business Logic: Access data through the repository interface, making your business logic agnostic of data source details.</p><h3>When to Use the Repository Pattern</h3><p>This pattern is particularly useful when:</p><ul><li>There are multiple sources of data.</li><li>You need to abstract the data-fetching mechanism from the rest of your application.</li><li>Your application requires a clear separation of concerns for maintainability and scalability.</li></ul><h3>Common Pitfalls and Best Practices</h3><p>Pitfalls:</p><ul><li>Creating too many layers that can overcomplicate simple data fetch operations.</li><li>Tight coupling between data sources and repositories, reducing flexibility.</li></ul><p>Best Practices:</p><ul><li>Keep data sources simple and focused on fetching data.</li><li>Use dependency injection to manage data sources and repository instances, enhancing testability.</li></ul><h3>Conclusion</h3><p>Incorporating data sources in the repository pattern in Flutter adds an extra layer of abstraction, making your application more scalable and maintainable. It allows for a clean separation between how data is fetched and how it’s consumed in your business logic. This pattern is highly effective for complex applications with diverse data management needs.</p><h3>Additional Resources</h3><ul><li><a href="https://resocoder.com/flutter-clean-architecture">Clean Architecture Guidelines</a></li><li><a href="https://medium.com/flutter-community">Flutter Community Medium Publications</a></li></ul><p>I hope you found this guide on the repository pattern in Flutter helpful. For more insights and updates, feel free to follow me on Medium and connect with me on <a href="https://www.linkedin.com/in/mahmoudsalehm979/">LinkedIn</a>, and <a href="https://www.instagram.com/mahmoud.saleh.m98/">Instagram</a>. Let’s keep the conversation going!”</p><p>#Flutter #Repository</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56579831c498" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Outstanding Fake API Providers for Mobile Developers to Streamline Testing]]></title>
            <link>https://medium.com/@mahmoudsaal7/4-outstanding-fake-api-providers-for-mobile-developers-to-streamline-testing-fc61fa4c847c?source=rss-4a3570d9b749------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc61fa4c847c</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[fake-api]]></category>
            <category><![CDATA[mock-api]]></category>
            <dc:creator><![CDATA[Mahmoud Saleh]]></dc:creator>
            <pubDate>Sun, 05 Nov 2023 11:15:08 GMT</pubDate>
            <atom:updated>2023-11-05T11:16:15.606Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*rsehca5AizlSs9FxPRt0zg.png" /></figure><p>If you’re looking for pre-built APIs to use for development and testing purposes, there are several excellent options that provide ready-to-use mock APIs. These APIs come with predefined endpoints and data, allowing you to focus on front-end development without having to configure the back-end. Here are four platforms that offer pre-built APIs:</p><h3>1. Typicode’s JSONPlaceholder</h3><p>JSONPlaceholder is a free online REST service that you can use to fetch fake data in JSON format, making it incredibly useful for testing and prototyping mobile applications.</p><p>Pre-built APIs:</p><ul><li>Users, Posts, Comments, Albums, Photos, Todos, and Users</li><li>URL: <a href="https://jsonplaceholder.typicode.com/">https://jsonplaceholder.typicode.com/</a></li></ul><h3>2. Reqres</h3><p>Reqres simulates real application scenarios with a wide array of pre-built APIs for testing common operations like authentication, CRUD operations, and more.</p><p>Pre-built APIs:</p><ul><li>List Users, Single user, List resource, Single resource, Create, Update, Register, Login, and more</li><li>URL: <a href="https://reqres.in/">https://reqres.in/</a></li></ul><h3>3. Mockaroo</h3><p>Mockaroo allows you to download mock data in various formats or access data through pre-built APIs. It’s a tool that is designed to make it easy to generate large datasets for testing and development.</p><p>Pre-built APIs:</p><ul><li>You can define your own schema and then use the API to generate data</li><li>URL: <a href="https://www.mockaroo.com/">https://www.mockaroo.com/</a></li></ul><h3>4. Fake Store API</h3><p>Fake Store API is a free online REST API that developers can use to make test orders, eCommerce, and cart integrations.</p><p>Pre-built APIs:</p><ul><li>Products, Cart, Users, and more</li><li>URL: <a href="https://fakestoreapi.com/">https://fakestoreapi.com/</a></li></ul><h3>5. DummyJson API</h3><p><a href="https://dummyjson.com/">DummyJson</a> is another API service that provides fake data for testing and prototyping, similar to the other services we have discussed. It’s useful for simulating back-end data in your mobile or web applications when you’re in the design and development phase.</p><p><strong>Pre-built APIs:</strong></p><ul><li>Authentication, Products, Cart, Orders, Users, and more.</li></ul><h3>Utilizing Pre-built APIs:</h3><p>These pre-built APIs can be used in various stages of your mobile app development:</p><ul><li>Prototyping: Quickly wire up the frontend without waiting for the backend services to be implemented.</li><li>Testing: Use the APIs to test error handling, loading states, and response parsing.</li><li>Continuous Integration/Continuous Deployment (CI/CD): Incorporate these APIs into your CI/CD pipelines to test your application automatically during the deployment process.</li></ul><h3>Tips for Using Pre-built APIs:</h3><ul><li>Read the Documentation: Before you start, it’s crucial to read the API documentation to understand the endpoints available, the data structure, and any limitations.</li><li>Respect Rate Limits: Some free services may have rate limits. Ensure you’re not hitting these limits as it may temporarily block your access.</li><li>Handle Data Responsibly: Even though these are fake APIs, practice handling data responsibly as if it were real user data.</li></ul><p>Remember that while these pre-built APIs are great for development and testing, they should not be used for production. They are intended to mimic backend behavior and should be replaced with actual APIs once your backend is ready.</p><p>In conclusion, fake APIs like JSONPlaceholder, Reqres, Mockaroo, Fake Store API, and DummyJson are invaluable tools for mobile developers. They allow for the seamless progression of front-end development and testing without the immediate need for a working back-end.</p><ul><li>Facebook:<a href="https://www.facebook.com/mahmoud.saleh.m98/"> My Facebook Page</a></li><li>LinkedIn: <a href="https://www.linkedin.com/in/mahmoudsalehm979/">GO!</a></li><li>Instagram: <a href="https://www.instagram.com/mahmoud.saleh.m98/">GO!</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc61fa4c847c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding SOLID Principles: Making Code Stronger]]></title>
            <link>https://medium.com/@mahmoudsaal7/understanding-solid-principles-making-code-stronger-65eb61095fcf?source=rss-4a3570d9b749------2</link>
            <guid isPermaLink="false">https://medium.com/p/65eb61095fcf</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Mahmoud Saleh]]></dc:creator>
            <pubDate>Sun, 17 Sep 2023 11:30:54 GMT</pubDate>
            <atom:updated>2023-09-17T11:30:54.377Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*IJcog1cXdkb9zja6LNLbmQ.png" /></figure><p>As software complexity grows, maintaining codebase health becomes crucial. A key tenet of software design, especially in the object-oriented paradigm, is the SOLID principles. These principles ensure that a system is modular, maintainable, and scalable.</p><h4>1. Single Responsibility Principle (SRP): One Job, One Class</h4><ul><li><strong>Imagine: </strong>Think of a kitchen knife. Its main job is to cut. If you tried using it as a spoon or fork, it’d be awkward and inefficient.</li><li><strong>In Code:</strong> Like the kitchen knife, each part of your code should have one primary job. If a class manages both user information and also file storage, it’s time to split them. Why? Because changes to file storage shouldn’t risk breaking user information handling.</li><li>Showcase:</li></ul><p>Before:</p><pre>class User {<br>  String name;<br><br>  User(this.name);<br><br>  void saveUser() {<br>    // Code to save user<br>  }<br>}<br></pre><p>After:</p><pre>class User {<br>  String name;<br><br>  User(this.name);<br>}<br><br>class UserDatabase {<br>  void saveUser(User user) {<br>    // Code to save user<br>  }<br>}</pre><h4>2. Open/Closed Principle (OCP): Expand, Don’t Modify</h4><ul><li><strong>Imagine: </strong>Consider a backpack with pockets. If you need more storage, you’d ideally want to add more pockets rather than taking the backpack apart.</li><li><strong>In Code:</strong> You should be able to add new functions to your software without altering what’s already working. This makes sure that as your software grows, older parts remain reliable.</li><li><strong>Showcase:</strong></li></ul><p>Before:</p><pre>class Rectangle {<br>  double width, height;<br><br>  Rectangle(this.width, this.height);<br>}<br><br>void printArea(Rectangle rect) {<br>  print(rect.width * rect.height);<br>}</pre><p>After:</p><pre>abstract class Shape {<br>  double getArea();<br>}<br><br>class Rectangle extends Shape {<br>  double width, height;<br><br>  Rectangle(this.width, this.height);<br><br>  @override<br>  double getArea() =&gt; width * height;<br>}<br><br>void printArea(Shape shape) {<br>  print(shape.getArea());<br>}</pre><h4>3. Liskov Substitution Principle (LSP): Substitutable Parts</h4><ul><li><strong>Imagine:</strong> Ever bought a product that claimed to be “compatible” with another but didn’t quite fit? Frustrating, right?</li><li><strong>In Code:</strong> If you’ve got a category (like “Vehicles”) and a sub-category (like “Cars”), any car you create should fit smoothly into the vehicle group without causing unexpected behaviors.</li><li><strong>Showcases:</strong></li></ul><p>Before:</p><pre>class Bird {<br>  void fly() {<br>    // Code to fly<br>  }<br>}<br><br>class Ostrich extends Bird {}</pre><p>After:</p><pre>class Bird {}<br><br>class FlyingBird extends Bird {<br>  void fly() {<br>    // Code to fly<br>  }<br>}<br><br>class Ostrich extends Bird {}<br>// Ostrich can&#39;t fly, so it doesn&#39;t have to override fly()</pre><h4>4. Interface Segregation Principle (ISP): Only What’s Needed</h4><ul><li><strong>Imagine: </strong>Buying a TV remote with 100 buttons, but you only use 10. The other 90 are just in the way.</li><li><strong>In Code:</strong> A section of your software shouldn’t have to deal with functions or buttons it doesn’t use. By ensuring each part only interacts with what it needs, you make the code clearer and less prone to errors.</li><li><strong>Showcase:</strong></li></ul><p>Before:</p><pre>abstract class Worker {<br>  void work();<br>  void eat();<br>}<br><br>class Humanimplements Worker {<br>  @override<br>  void work() {<br>    // Code to work<br>  }<br><br>  @override<br>  void eat() {<br>    // Code to eat!<br>  }<br>}<br><br>class Robot implements Worker {<br>  @override<br>  void work() {<br>    // Code to work<br>  }<br><br>  @override<br>  void eat() {<br>    // Robots don&#39;t eat!<br>  }<br>}</pre><p>After:</p><pre>abstract class Worker {<br>  void work();<br>}<br><br>abstract class Eater {<br>  void eat();<br>}<br><br>class Robot implements Worker, Eater{<br>  @override<br>  void work() {<br>    // Code to work<br>  }<br><br>  @override<br>  void eat() {<br>    // Code to eat!<br>  }<br>}<br><br>class Robot implements Worker {<br>  @override<br>  void work() {<br>    // Code to work<br>  }<br>}</pre><h4>5. Dependency Inversion Principle (DIP): Middle Ground Connections</h4><ul><li><strong>Imagine:</strong> Toys that can connect with parts from different sets are more versatile. They don’t depend solely on their original parts.</li><li><strong>In Code:</strong> The main sections of your software shouldn’t be too closely tied to specific smaller parts. Both should ideally connect through general rules or interfaces, promoting flexibility.</li><li><strong>Showcase:</strong></li></ul><p><strong>Before:</strong></p><pre>class LightBulb {<br>  void turnOn() {<br>    // Turn on logic<br>  }<br><br>  void turnOff() {<br>    // Turn off logic<br>  }<br>}<br><br>class Switch {<br>  final LightBulb lightBulb;<br><br>  Switch(this.lightBulb);<br>}</pre><p><strong>After:</strong></p><pre>abstract class SwitchableDevice {<br>  void turnOn();<br>  void turnOff();<br>}<br><br>class LightBulb implements SwitchableDevice {<br>  @override<br>  void turnOn() {<br>    // Turn on logic<br>  }<br><br>  @override<br>  void turnOff() {<br>    // Turn off logic<br>  }<br>}<br><br>class Switch {<br>  final SwitchableDevice device;<br><br>  Switch(this.device);<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65eb61095fcf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Local Storage Solutions for Flutter: Summary Guide]]></title>
            <link>https://medium.com/@mahmoudsaal7/local-storage-solutions-for-flutter-summary-guide-83efd16c27bf?source=rss-4a3570d9b749------2</link>
            <guid isPermaLink="false">https://medium.com/p/83efd16c27bf</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[localstorage]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[sharedpreferences]]></category>
            <category><![CDATA[room]]></category>
            <dc:creator><![CDATA[Mahmoud Saleh]]></dc:creator>
            <pubDate>Sun, 10 Sep 2023 18:29:18 GMT</pubDate>
            <atom:updated>2023-11-14T16:34:00.417Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ldpc328gxoysTAtq3wJwg.jpeg" /></figure><p>In the world of mobile applications, data persistence is crucial. Flutter, as one of the leading frameworks, offers a variety of solutions for storing data locally. In this article, we’ll explore some of the most popular methods, their benefits, and their drawbacks.</p><h4>1. SharedPreferences</h4><p><strong>When to use:</strong></p><ul><li>Storing simple key-value pairs.</li><li>Saving user preferences or settings.</li><li>Quick access to small amounts of data.</li></ul><p><strong>Benefits:</strong></p><ul><li>Easy to implement and use.</li><li>Supports both Android and iOS.</li></ul><p><strong>Disadvantages:</strong></p><ul><li>Not suitable for structured or large-scale data.</li><li>Data is not encrypted.</li></ul><h4><strong>2. SQLite (via the </strong><strong>sqflite plugin)</strong></h4><p><strong>When to use:</strong></p><ul><li>Storing structured data.</li><li>When you need the capabilities of a relational database.</li><li>Complex queries and operations.</li></ul><p><strong>Benefits:</strong></p><ul><li>Provides SQL-like operations for data manipulation.</li><li>Scalable for more extensive datasets.</li><li>ACID compliant (Atomicity, Consistency, Isolation, Durability).</li></ul><p><strong>Disadvantages:</strong></p><ul><li>Slightly higher learning curve than SharedPreferences.</li><li>Overkill for small, simple data needs.</li></ul><h4>3. Hive</h4><p><strong>When to use:</strong></p><ul><li>Need for a lightweight and fast NoSQL database.</li><li>Storing structured and unstructured data.</li></ul><p><strong>Benefits:</strong></p><ul><li>Faster I/O operations compared to other solutions.</li><li>No need to serialize/deserialize as it uses binary format.</li><li>Offers an intuitive API.</li></ul><p><strong>Disadvantages:</strong></p><ul><li>Being a NoSQL database, it might not be suitable for apps requiring complex queries.</li><li>The community around Hive is smaller than SQLite, so there might be fewer resources and solutions to uncommon issues.</li></ul><h4>4. Moor</h4><p><strong>When to use:</strong></p><ul><li>Storing structured data.</li><li>When you need type safety and a reactive persistence layer.</li></ul><p><strong>Benefits:</strong></p><ul><li>Offers fluent, Dart-centric API.</li><li>Reactive out of the box: Stream support for real-time updates.</li><li>Type-safe: reduces the chances of runtime errors.</li></ul><p><strong>Disadvantages:</strong></p><ul><li>Learning curve due to its unique way of defining database schema.</li><li>Might be an overkill for simpler projects.</li></ul><h4>Summary</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*Fwo6Qzc0wekM1djqXFyPUw.png" /></figure><h3>Conclusion:</h3><p>Selecting the right local storage solution for your Flutter app depends on your specific needs. If you require quick and straightforward storage, SharedPreferences might be your go-to. For more structured and extensive data, SQLite and Moor offer robust SQL-like operations. On the other hand, Hive offers speed and flexibility in a NoSQL format. Lastly, if you’re looking for real-time synchronization capabilities, Realm might be worth considering.</p><p>Each solution has its unique strengths and weaknesses. It’s essential to evaluate the specific needs of your project and the trade-offs you’re willing to make before settling on a storage option.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83efd16c27bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Physics of Scroll Views in Flutter: Overview Guide]]></title>
            <link>https://medium.com/@mahmoudsaal7/the-physics-of-scroll-views-in-flutter-a-comprehensive-guide-9abd6d792bbb?source=rss-4a3570d9b749------2</link>
            <guid isPermaLink="false">https://medium.com/p/9abd6d792bbb</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[scrollview]]></category>
            <category><![CDATA[physics]]></category>
            <dc:creator><![CDATA[Mahmoud Saleh]]></dc:creator>
            <pubDate>Mon, 28 Aug 2023 16:55:38 GMT</pubDate>
            <atom:updated>2023-08-28T18:22:51.183Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Mza4H3XlZcCQs00BkKJqA.png" /></figure><p>Flutter, a beloved framework for creating beautiful cross-platform apps, offers a range of widgets that make UI creation both fun and expressive. One such widget is the ScrollView, and if you&#39;ve worked with it, you&#39;ll notice that it comes with various physics properties that can dictate its behavior. This article will delve into the different types of scroll physics available in Flutter.’</p><h4>1. ClampingScrollPhysics:</h4><p>This is the default physics for most scroll views on Android. It allows scrolling beyond the edge of the content but then clamps (or stops) the scroll attempt, showing a glow indication at the edge to signal the user they’ve reached the end.</p><p><strong><em>When to use:</em></strong> Primarily when developing for Android to give users a familiar scrolling experience.</p><pre>ListView(<br>  physics: ClampingScrollPhysics(),<br>  children: /* Your children here */,<br>)</pre><h4>2. BouncingScrollPhysics:</h4><p>Typical for iOS, this physics type allows the content to scroll beyond the edge and then bounces back. It gives that characteristic “rubber band” effect you often see on Apple devices.</p><p><em>When to use:</em> For an iOS-like scrolling experience or when you want your content to bounce back upon over scrolling.</p><pre>ListView(<br>  physics: BouncingScrollPhysics(),<br>  children: /* Your children here */,<br>)</pre><h4>3. NeverScrollableScrollPhysics:</h4><p>As the name suggests, this physics type will prevent the content from being scrolled. It’s useful in situations where you might embed a scroll view within another or when you want the content to be static.</p><p><em>When to use:</em> In nested scrolling scenarios where you want to disable scrolling for an inner scroll view, or when displaying content that should remain static.</p><pre>ListView(<br>  physics: NeverScrollableScrollPhysics(),<br>  children: /* Your children here */,<br>)</pre><h4>4. AlwaysScrollableScrollPhysics:</h4><p>Even if the content inside your scroll view is not large enough to scroll, this physics type will always display the over scroll indication when the user tries to scroll.</p><p><em>When to use:</em> If you want to show an over scroll indicator even when the content isn’t large enough to scroll.</p><pre>ListView(<br>  physics: AlwaysScrollableScrollPhysics(),<br>  children: /* Your children here */,<br>)</pre><h4>5. FixedExtentScrollPhysics:</h4><p>This is typically used with the ListWheelScrollView, which lets users scroll through a list of items where each item snaps into place. It provides a &quot;picker&quot; or &quot;wheel&quot; feel when scrolling.</p><p><em>When to use:</em> When you have a list of items and you want each item to snap into place during scrolling. Commonly used with ListWheelScrollView.</p><pre>ListWheelScrollView(<br>  physics: FixedExtentScrollPhysics(),<br>  children: /* Your children here */,<br>)</pre><h4>6. PageScrollPhysics:</h4><p>Used with the PageView widget, it gives a paging effect, where each child of the scroll view becomes a &quot;page&quot; that snaps into place, ensuring only one child is central and fully visible at a time.</p><p><em>When to use:</em> In situations where you want to display content as pages, especially with PageView. Each child snaps into place and ensures a single page view at a time.</p><pre>PageView(<br>  physics: PageScrollPhysics(),<br>  children: /* Your children here */,<br>)</pre><h4>Mixing and Customizing Scroll Physics:</h4><p>What’s fantastic about Flutter’s design is that you can combine multiple physics types to create custom behaviors. For instance, if you want the clamping behavior of Android but with a touch of iOS’s bounce, you can combine ClampingScrollPhysics with BouncingScrollPhysics.</p><pre>ListView(<br>  physics: BouncingScrollPhysics(parent: ClampingScrollPhysics()),<br>  children: /* Your children here */,<br>)</pre><p>This custom combination gives a unique experience of both clamping and bouncing.</p><h4>Conclusion:</h4><p>Scroll physics in Flutter provides an intuitive way to customize the scroll behavior of widgets, making user interactions feel natural, smooth, and tailored to specific platform conventions. Whether you’re aiming for the familiar bounce of iOS, the clamping of Android, or even a combination, Flutter has you covered. Experiment with these physics types to discover the best user experience for your app!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9abd6d792bbb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Builder Widgets in Flutter]]></title>
            <link>https://medium.com/@mahmoudsaal7/understanding-builder-widgets-in-flutter-79e71839a7cb?source=rss-4a3570d9b749------2</link>
            <guid isPermaLink="false">https://medium.com/p/79e71839a7cb</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[builders]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[mahmoudsalehm97]]></category>
            <dc:creator><![CDATA[Mahmoud Saleh]]></dc:creator>
            <pubDate>Sat, 26 Aug 2023 17:39:09 GMT</pubDate>
            <atom:updated>2023-08-27T05:21:31.357Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o1pfx3oAke-i5WcY0BLU3Q.jpeg" /></figure><p>Flutter’s UI design principle is beautifully encapsulated in widgets, the atomic building blocks that form the entire UI. Among these, builder widgets stand out for their dynamic and context-driven nature. If you’re looking to deepen your understanding of these versatile widgets, you’ve come to the right place.</p><h3>What are Builder Widgets?</h3><p>At their core, builder widgets are tools that offer a callback function, returning another widget. They prove essential for conditional rendering, offering a fresh approach to creating more dynamic interfaces.</p><h3>Diving Into Popular Builder Widgets</h3><h3>1. Builder</h3><p>Intended for acquiring a new BuildContext descended from a parent. It&#39;s your best ally when working with MediaQuery, Theme, or Scaffold.</p><h4>When to Use:</h4><ul><li>When you need to introduce a new BuildContext below an existing widget.</li><li>When working with widgets like MediaQuery, Theme, or Scaffold, especially if you have recently introduced them in the widget tree and need to access them further down.</li></ul><h4>Example:</h4><p>If you have a Scaffold and you immediately need to access it using a ScaffoldMessenger (to show a SnackBar, for instance), you&#39;ll need a Builder to generate the appropriate context.</p><pre>Builder(<br>  builder: (BuildContext context) {<br>    var theme = Theme.of(context);<br>    return FloatingActionButton(<br>      backgroundColor: theme.primaryColor,<br>      onPressed: () {},<br>      child: Icon(Icons.add),<br>    );<br>  },<br>)</pre><h3>2. FutureBuilder</h3><p>Working with futures becomes a breeze. Display different UI elements depending on the future’s state.</p><h4>When to Use:</h4><ul><li>When dealing with futures, e.g., making HTTP requests.</li><li>When you need to display different widgets based on the result of a Future, such as showing a loading spinner while waiting for data and then displaying the data or an error message.</li></ul><h4>Example:</h4><p>Fetching a user’s profile from an API and displaying a loader until the data arrives.</p><pre>Future&lt;String&gt; fetchData() async {<br>  await Future.delayed(Duration(seconds: 2));<br>  return &quot;Data fetched!&quot;;<br>}<br><br>FutureBuilder&lt;String&gt;(<br>  future: fetchData(),<br>  builder: (BuildContext context, AsyncSnapshot&lt;String&gt; snapshot) {<br>    if (snapshot.connectionState == ConnectionState.waiting) {<br>      return CircularProgressIndicator();<br>    } else if (snapshot.hasError) {<br>      return Text(&#39;Error: ${snapshot.error}&#39;);<br>    } else {<br>      return Text(&#39;Result: ${snapshot.data}&#39;);<br>    }<br>  },<br>)</pre><h3>3. StreamBuilder</h3><p>Listen to streams and re-render UI dynamically based on stream events.</p><h4>When to Use:</h4><ul><li>When your UI needs to rebuild in response to a stream of data.</li><li>Useful for real-time data updates, like chat messages or live feeds.</li></ul><h4>Example:</h4><p>A chat app where new messages from a Stream trigger UI updates.</p><pre>Stream&lt;int&gt; counterStream() {<br>  return Stream&lt;int&gt;.periodic(Duration(seconds: 1), (x) =&gt; x).take(10);<br>}<br><br>StreamBuilder&lt;int&gt;(<br>  stream: counterStream(),<br>  builder: (BuildContext context, AsyncSnapshot&lt;int&gt; snapshot) {<br>    if (snapshot.connectionState == ConnectionState.waiting) {<br>      return Text(&#39;Waiting...&#39;);<br>    } else if (snapshot.hasError) {<br>      return Text(&#39;Error: ${snapshot.error}&#39;);<br>    } else if (!snapshot.hasData) {<br>      return Text(&#39;Stream completed!&#39;);<br>    } else {<br>      return Text(&#39;Counter: ${snapshot.data}&#39;);<br>    }<br>  },<br>)</pre><h3>4. LayoutBuilder</h3><p>Get constraints to adaptively display content.</p><h4>When to Use:</h4><ul><li>When you want to make decisions based on the parent widget’s constraints.</li><li>For creating responsive designs that adapt to different screen sizes or parent widget sizes.</li></ul><h4>Example:</h4><p>Switching between a column and row layout based on available width.</p><pre>LayoutBuilder(<br>  builder: (BuildContext context, BoxConstraints constraints) {<br>    if (constraints.maxWidth &gt; 600) {<br>      return Text(&#39;Wide layout&#39;);<br>    } else {<br>      return Text(&#39;Narrow layout&#39;);<br>    }<br>  },<br>)</pre><h3>5. AnimatedBuilder</h3><p>Craft beautiful animations by utilizing this widget which provides an Animation object for dynamic UI rendering.</p><h4>When to Use:</h4><ul><li>When you’re working with animations that require rebuilding a widget tree.</li><li>It’s useful for optimizing animations by isolating widgets that need to be rebuilt.</li></ul><h4>Example:</h4><p>Rotating an icon. The rotation changes trigger a rebuild, but the icon itself remains unchanged.</p><pre>AnimationController _controller = AnimationController(<br>  duration: const Duration(seconds: 2),<br>  vsync: this,<br>);<br><br>AnimatedBuilder(<br>  animation: _controller,<br>  builder: (BuildContext context, Widget? child) {<br>    return Transform.rotate(<br>      angle: _controller.value * 2.0 * pi,<br>      child: child,<br>    );<br>  },<br>  child: Icon(Icons.rotate_right),<br>)</pre><h3>6. ValueListenableBuilder</h3><p>Monitor ValueListenable and refresh the UI upon value alterations.</p><h4>When to Use:</h4><ul><li>When listening to changes in a ValueListenable object, such as a ValueNotifier.</li><li>It’s useful for optimizing performance by only rebuilding widgets when the value they depend on changes.</li></ul><h4>Example:</h4><p>A counter app where the count is stored in a ValueNotifier. The UI should update only when the count changes.</p><pre>ValueNotifier&lt;int&gt; _counter = ValueNotifier&lt;int&gt;(0);<br><br>ValueListenableBuilder&lt;int&gt;(<br>  valueListenable: _counter,<br>  builder: (BuildContext context, int value, Widget? child) {<br>    return Column(<br>      children: [<br>        ElevatedButton(<br>          onPressed: () =&gt; _counter.value++,<br>          child: Text(&quot;Increment&quot;),<br>        ),<br>        Text(&#39;Counter: $value&#39;),<br>      ],<br>    );<br>  },<br>)</pre><h3>7. ListenableBuilder</h3><p>Flutter has a variety of tools to help developers handle state and UI changes. One such widget is the ListenableBuilder, designed to rebuild its UI at any time the Listenable It&#39;s connected to changes.</p><h4>👉 When to Use:</h4><ul><li>When you have a custom Listenable (or any of its subclasses) and you want the UI to rebuild whenever the Listenable updates.</li><li>Great for cases when you want more control than what ValueListenableBuilder offers but don&#39;t want to dive deep into the complexities of a full-blown state management solution.</li></ul><h4>🌟 Use Case:</h4><p>Suppose you have a custom animation controller (which is a Listenable) and you want to rebuild a widget whenever the animation updates. Instead of manually adding listeners and calling, just wrap the widget in a ListenableBuilder.</p><pre>AnimationController _controller = AnimationController(<br>  duration: const Duration(seconds: 2),<br>  vsync: this,<br>);<br><br>ListenableBuilder(<br>  listenable: _controller,<br>  builder: (BuildContext context, Widget? child) {<br>    return Opacity(<br>      opacity: _controller.value,<br>      child: child,<br>    );<br>  },<br>  child: Text(&quot;Fade me in and out!&quot;),<br>)</pre><h3>Exploring Additional Builder Widgets</h3><p>Flutter’s vastness presents even more builder widgets. Some noteworthy ones include:</p><ul><li><strong>SliverChildBuilderDelegate</strong>: Optimizes performance in scrollable regions by creating children on-demand.</li><li><strong>SliverList and SliverGrid</strong>: Dynamically render sliver children.</li><li><strong>DraggableBuilder</strong>: Make any widget draggable.</li><li><strong>TweenAnimationBuilder</strong>: Seamlessly animate between two values.</li></ul><h3>Conclusion</h3><p>Builder widgets in Flutter allow developers to craft responsive, dynamic, and efficient user interfaces. With the evolving landscape of Flutter, there’s always more to learn and explore. Dive in, experiment, and elevate your Flutter UI game!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79e71839a7cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Material Design Colors and Theming in a Flutter Project]]></title>
            <link>https://medium.com/@mahmoudsaal7/using-material-design-colors-and-theming-in-a-flutter-project-a3b58b269ef5?source=rss-4a3570d9b749------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3b58b269ef5</guid>
            <category><![CDATA[material-design]]></category>
            <category><![CDATA[colors]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Mahmoud Saleh]]></dc:creator>
            <pubDate>Wed, 23 Aug 2023 18:15:21 GMT</pubDate>
            <atom:updated>2023-08-23T18:15:21.796Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*Bb6-Y7oHs4W0t4VL9Q-bng.png" /></figure><p>Material Design is a design system developed by Google, aimed at creating visual, motion, and interaction design consistency across platforms and devices. One of its foundational aspects is its color system. In this article, we’ll delve into how to integrate Material Design’s color system and theming into your Flutter projects.</p><h3>1. Understanding Material Design Color System</h3><p>Material Design emphasizes using bold, graphical, and intentional colors. Its color system is designed to:</p><ul><li>Reflect brand personality.</li><li>Ensure user-interface legibility and hierarchy.</li><li>Direct attention and highlight key information.</li></ul><p>Colors are categorized as:</p><ul><li><strong>Primary</strong>: The most widely used color across your app.</li><li><strong>Primary variant</strong>: A variation of the primary color, often used for hover or pressed states.</li><li><strong>Secondary</strong>: A contrasting color to the primary, used for FABs, selection controls, etc.</li><li><strong>Secondary variant</strong>: A variation of the secondary color.</li><li><strong>Background</strong>: Color for the main content and containers.</li><li><strong>Surface</strong>: Color of components like cards, sheets, and menus.</li><li><strong>Error</strong>: Indicates errors.</li><li><strong>On-Primary, On-Secondary, On-Background, On-Surface, On-Error</strong>: Colors used on top of the primary, secondary, background, surface, and error colors, respectively (usually text or icons).</li></ul><h3>2. Setting Up Material Theme in Flutter</h3><p>To utilize Material colors in Flutter, you use the ThemeData class. Here&#39;s a basic example:</p><pre>ThemeData(<br>  brightness: Brightness.light,   // Determines if the theme is light or dark<br>  primaryColor: Colors.blue,      // Primary color for major parts of the app (toolbars, tab bars, etc.)<br>  primaryColorDark: Colors.blue[700], // Darker variant of the primary color<br>  primaryColorLight: Colors.blue[100], // Lighter variant of the primary color<br>  accentColor: Colors.amber,      // Secondary color, also known as the accent color<br>  canvasColor: Colors.grey[50],   // Background color for larger parts of the app<br>  scaffoldBackgroundColor: Colors.white, // Background color for Scaffolds<br>  bottomAppBarColor: Colors.grey[300],  // Bottom app bar&#39;s color<br>  cardColor: Colors.white,        // Background color of cards<br>  dividerColor: Colors.grey,      // Color of dividers<br>  highlightColor: Colors.amber[700], // Color of ink splash when tapped<br>  splashColor: Colors.amber[200],    // Color of ink splash during a ripple effect<br>  selectedRowColor: Colors.grey[100], // Color for selected rows<br>  unselectedWidgetColor: Colors.grey[400], // Color for widgets like unchecked checkboxes, radio buttons, etc.<br>  disabledColor: Colors.grey[200], // Color to indicate disabled widgets<br>  buttonColor: Colors.blue[600],   // Default button color<br>  secondaryHeaderColor: Colors.blue[50],  // Background color for sticky headers<br>  textSelectionColor: Colors.blue[200],   // Background color for text selection<br>  cursorColor: Colors.blue[700],   // Color of the cursor in text fields<br>  textSelectionHandleColor: Colors.blue[400], // Color of the handlers for text selection<br>  backgroundColor: Colors.white,  // Default background color<br>  errorColor: Colors.red,         // Default color for error messages and icons<br>  toggleableActiveColor: Colors.blue[600], // Color for toggleable widgets when active (e.g., switch)<br>  <br>  // Typography (A few examples)<br>  textTheme: TextTheme(<br>    headline1: TextStyle(color: Colors.blue[900]),<br>    bodyText1: TextStyle(color: Colors.black),<br>    // ... and so on for other text styles<br>  ),<br>  <br>  // Input Decoration themes<br>  inputDecorationTheme: InputDecorationTheme(<br>    focusColor: Colors.blue[100],<br>    // ... and more properties here<br>  ),<br><br>  // Icon themes<br>  iconTheme: IconThemeData(<br>    color: Colors.blue[600],<br>    // ... other properties<br>  ),<br><br>  // ... and there are many more properties you can set!<br>)</pre><h3>3. Customizing the Color Palette</h3><p>While Flutter provides a range of predefined colors in the Colors class (e.g., Colors.blue), you might want to define your own:</p><pre>const Color primaryColor = Color(0xFF0A74DA); // Custom blue color<br>const Color primaryVariantColor = Color(0xFF075BB5); // A darker shade</pre><h3>4. Implementing Theming</h3><p>After defining your colors, incorporate them into your app’s theme:</p><pre>final appTheme = ThemeData(<br>  primaryColor: primaryColor,<br>  primaryColorDark: primaryVariantColor,<br>  // ... and so on for other color categories<br>);</pre><p>In the main app widget:</p><pre>MaterialApp(<br>  theme: appTheme,<br>  home: YourHomeWidget(),<br>)</pre><h3>5. Using the Colors in Your App</h3><p>Once you’ve set up the theme, you can use the colors easily:</p><pre>Text(<br>  &#39;Hello, Flutter!&#39;,<br>  style: TextStyle(color: Theme.of(context).primaryColor),<br>)</pre><h3>6. Dark and Light Themes</h3><p>To better support both dark and light modes, define separate themes:</p><pre>final lightTheme = ThemeData.light().copyWith(<br>  primaryColor: primaryColor,<br>  // ...<br>);<br><br>final darkTheme = ThemeData.dark().copyWith(<br>  primaryColor: primaryColor,<br>  // ...<br>);<br><br>MaterialApp(<br>  theme: lightTheme,<br>  darkTheme: darkTheme,<br>  themeMode: ThemeMode.system, // Adapts to systems theme<br>  home: YourHomeWidget(),<br>)</pre><h3>7. Beyond Colors: Material Theming</h3><p>Remember, Material Design is more than just colors. Theming extends to typography, shape, elevation, and more. Flutter’s ThemeData class provides options to customize all these aspects.</p><h3>Conclusion</h3><p>Material Design’s color system provides a robust and flexible foundation for creating coherent and appealing user interfaces. With Flutter’s comprehensive theming support, developers can effortlessly implement consistent color schemes and adapt designs for both light and dark modes. As you build your apps, keep in mind the importance of testing your color choices on various devices and under different lighting conditions to ensure accessibility and user comfort.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3b58b269ef5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding GestureDetector and InkWell in Flutter: A Comprehensive Comparison]]></title>
            <link>https://medium.com/@mahmoudsaal7/understanding-gesturedetector-and-inkwell-in-flutter-a-comprehensive-comparison-ffea0e16490e?source=rss-4a3570d9b749------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffea0e16490e</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[gesturedetector]]></category>
            <category><![CDATA[touch]]></category>
            <dc:creator><![CDATA[Mahmoud Saleh]]></dc:creator>
            <pubDate>Sun, 11 Jun 2023 16:27:08 GMT</pubDate>
            <atom:updated>2023-06-11T16:27:08.294Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*6MzLc619ae95YPCVpEyxaQ.jpeg" /></figure><h3>Introduction</h3><p>Flutter, being a versatile framework for building cross-platform applications, provides various widgets for handling touch gestures and providing visual feedback to users. Two such widgets are GestureDetector and InkWell. In this article, we’ll explore the features, use cases, and performance considerations of GestureDetector and InkWell, helping you make an informed decision when choosing between them.</p><h3>Understanding GestureDetector</h3><p>GestureDetector is a GestureRecognizer in Flutter, allowing you to recognize various touch gestures such as tap, double tap, long press, drag, and scale. It serves as a powerful tool for custom gesture recognition in your application. One of its key advantages is its flexibility to be used with any widget that supports gestures, making it a versatile option for implementing touch interactions.</p><p>However, it’s important to note that GestureDetector does not provide built-in visual feedback to indicate user interaction. If adhering to Material Design guidelines or providing visual effects like ripples is a requirement, InkWell might be a better choice.</p><h3>Exploring InkWell</h3><p>InkWell, on the other hand, is a widget that wraps around another widget, providing both gesture recognition and visual feedback. It adheres to the Material Design guidelines for touch feedback, allowing you to create a consistent user experience across your application.</p><p>When a user interacts with an InkWell-wrapped widget, it renders the ink splash effect and ripple animation, which are essential components of Material Design. InkWell supports common gestures such as tap, double tap, and long press, and also provides callbacks for handling specific gesture events.</p><h3>Feature Comparison</h3><p>Let’s compare the features of GestureDetector and InkWell to understand their differences more clearly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*bQhDSVkSAnxIDNJrHDI8aw.png" /></figure><h3>Use Cases for GestureDetector</h3><p>There are several scenarios where GestureDetector shines:</p><ol><li>Custom Gesture Recognition: When you need to recognize custom or complex touch gestures that are not covered by the built-in gestures provided by other widgets, GestureDetector offers the flexibility to implement your own gesture recognition logic.</li><li>Non-Material Design Interface: If you want to create a custom touch interaction that doesn’t necessarily follow the Material Design guidelines and visual feedback like ripples is not required, GestureDetector can be used to implement your desired touch interactions.</li><li>Combining with Non-Tappable Widgets: There might be cases where you need to add touch gesture recognition to a widget that doesn’t natively support gestures, such as an image or a custom-drawn widget. GestureDetector can be used in such scenarios to capture touch gestures.</li></ol><h3>Use Cases for InkWell</h3><p>InkWell is well-suited for the following use cases:</p><ol><li>Material Design Compliance: If you aim to adhere to the Material Design guidelines for touch feedback and provide a consistent user experience across your app, InkWell becomes a natural choice. It automatically handles the ink splash effect and ripple animation, ensuring your app’s touch interactions align with Material Design principles.</li><li>Tap Interactions: When you want to provide visual feedback through the ink splash effect and ripple animation for tap interactions on specific widgets like buttons, list items, or tiles, InkWell simplifies the process. By wrapping these widgets with InkWell, you can effortlessly achieve the desired touch feedback.</li><li>Gesture-Specific Callbacks: InkWell provides convenient callback functions such as onTap, onDoubleTap, onLongPress, and onHighlightChanged. This allows you to easily handle specific gesture events and perform custom actions accordingly.</li></ol><h3>Performance Considerations</h3><p>When it comes to performance, GestureDetector and InkWell have some differences due to their implementation.</p><p>GestureDetector is generally more lightweight in terms of performance because it doesn’t have the additional overhead of rendering the ink splash effect and ripple animation. It provides flexibility in terms of customization but doesn’t offer built-in visual feedback.</p><p>On the other hand, InkWell introduces additional overhead in terms of performance due to the visual effects it renders. This can impact performance when there are multiple InkWells or when the widget tree is complex. However, if adhering to Material Design guidelines and providing standard touch feedback is a priority, InkWell’s performance impact might be an acceptable trade-off.</p><p>It’s crucial to consider the specific requirements and performance implications when choosing between GestureDetector and InkWell.</p><h3>Conclusion</h3><p>In this article, we explored the similarities and differences between GestureDetector and InkWell in Flutter. We discussed their features, use cases, and performance considerations, helping you make an informed decision when deciding which widget to use in your Flutter application.</p><p>Remember that GestureDetector provides flexibility and customization options for recognizing custom gestures and non-Material Design interfaces. On the other hand, InkWell simplifies the process of adhering to Material Design guidelines, providing touch feedback and visual effects.</p><p>Consider your specific requirements, design guidelines, and performance constraints to choose the most suitable widget for your application. With the knowledge gained from this comparison, you can confidently implement gesture recognition and touch feedback in your Flutter app.</p><blockquote>Thank you for reading, and happy coding!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffea0e16490e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>