<?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 Ahmed Taha ElElemy on Medium]]></title>
        <description><![CDATA[Stories by Ahmed Taha ElElemy on Medium]]></description>
        <link>https://medium.com/@ahmedtahaelelemy?source=rss-1a144ef4afe8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*AKzLKQpQnfqk45Fs94xk0w.jpeg</url>
            <title>Stories by Ahmed Taha ElElemy on Medium</title>
            <link>https://medium.com/@ahmedtahaelelemy?source=rss-1a144ef4afe8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 04:57:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ahmedtahaelelemy/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[Remove Splash Screen Flutter]]></title>
            <link>https://medium.com/@ahmedtahaelelemy/remove-splash-screen-flutter-6287ee020d8c?source=rss-1a144ef4afe8------2</link>
            <guid isPermaLink="false">https://medium.com/p/6287ee020d8c</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Ahmed Taha ElElemy]]></dc:creator>
            <pubDate>Sun, 06 Apr 2025 09:12:51 GMT</pubDate>
            <atom:updated>2025-04-06T09:12:51.579Z</atom:updated>
            <content:encoded><![CDATA[<p>Creating a Flutter application is an exciting journey, and understanding how to manage its initial screens can significantly enhance the user experience. One of the first elements users encounter is the <strong>splash screen</strong> — a brief introductory screen displayed while the app initializes. Flutter provides a default splash screen, but there might be instances where you wish to remove or customize it to better align with your app’s branding. This guide will walk you through the steps to remove the default splash screen from your Flutter app for both <strong>Android</strong> and <strong>iOS</strong> platforms.</p><h3>Understanding the Default Splash Screen</h3><p>Before diving into the removal process, it’s essential to understand the purpose of the default splash screen. When a Flutter app launches, there’s a brief period during which the native platform initializes the Flutter framework. During this time, a default white screen (splash screen) is displayed. While this provides a smooth transition, developers often prefer to customize or remove this screen to better reflect their app’s identity.​</p><h3>Removing the Default Splash Screen in Android</h3><p>To remove the default splash screen on <strong>Android</strong>, follow these steps:​<a href="https://blog.hubspot.com/website/how-to-bold-in-html?utm_source=chatgpt.com">Meta Stack Exchange+5HubSpot Blog+5Wikipedia+5</a></p><h3>1. Modify the AndroidManifest.xml File</h3><ul><li><strong>Navigate to</strong>: android/app/src/main/AndroidManifest.xml​</li><li><strong>Locate the </strong><strong>&lt;activity&gt; tag</strong> for your main activity, typically .MainActivity.</li><li><strong>Ensure the </strong><strong>android:theme attribute</strong> is set to your app&#39;s normal theme. For example:​</li></ul><pre>&lt;activity<br>      android:name=&quot;.MainActivity&quot;<br>      android:launchMode=&quot;singleTop&quot;<br>      android:theme=&quot;@style/NormalTheme&quot;<br>      android:configChanges=&quot;orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode&quot;<br>      android:hardwareAccelerated=&quot;true&quot;<br>      android:windowSoftInputMode=&quot;adjustResize&quot;&gt;<br>      &lt;intent-filter&gt;<br>          &lt;action android:name=&quot;android.intent.action.MAIN&quot;/&gt;<br>          &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot;/&gt;<br>      &lt;/intent-filter&gt;<br>  &lt;/activity&gt;</pre><h3>2. Update the styles.xml File</h3><ul><li><strong>Open</strong>: android/app/src/main/res/values/styles.xml​</li><li><strong>Define your app’s normal theme</strong> without referencing the splash screen drawable:</li></ul><pre>&lt;resources&gt;<br>      &lt;!-- Normal app theme --&gt;<br>      &lt;style name=&quot;NormalTheme&quot; parent=&quot;Theme.AppCompat.Light.NoActionBar&quot;&gt;<br>          &lt;!-- Customize your theme here --&gt;<br>          &lt;item name=&quot;android:windowBackground&quot;&gt;@android:color/white&lt;/item&gt;<br>      &lt;/style&gt;<br>  &lt;/resources&gt;</pre><ul><li><strong>Ensure there’s no reference</strong> to a LaunchTheme or splash screen drawable in this file.</li></ul><h3>3. Remove the launch_background.xml File</h3><ul><li><strong>Navigate to</strong>: android/app/src/main/res/drawable/​</li><li><strong>If a file named</strong> launch_background.xml exists:</li><li><strong>Delete it</strong> or <strong>Modify its content</strong> to have a plain background:</li></ul><p>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;layer-list xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt; &lt;item android:drawable=&quot;@android:color/white&quot; /&gt; &lt;/layer-list&gt;</p><h3>Removing the Default Splash Screen in iOS</h3><p>For <strong>iOS</strong>, the splash screen is managed using a storyboard. To remove it:​</p><h3>1. Modify the Info.plist File</h3><ul><li><strong>Open</strong>: ios/Runner/Info.plist​</li><li><strong>Find the key</strong> UILaunchStoryboardName.</li><li><strong>Set its value</strong> to an empty string or remove the key entirely:</li></ul><pre>&lt;key&gt;UILaunchStoryboardName&lt;/key&gt;<br>  &lt;string&gt;&lt;/string&gt;</pre><h3>2. Remove the Launch Screen Storyboard</h3><ul><li><strong>Navigate to</strong>: ios/Runner/Base.lproj/LaunchScreen.storyboard​</li><li><strong>You can choose to</strong> delete this file or leave it blank.</li></ul><h3>Important Considerations</h3><ul><li><strong>App Store Guidelines</strong>: Ensure that removing the splash screen doesn’t violate any platform-specific guidelines. Both Apple and Google have recommendations regarding launch screens.​</li><li><strong>User Experience</strong>: While removing the splash screen can lead to a faster app launch experience, consider whether a brief, branded splash screen might enhance user engagement.​</li><li><strong>Testing</strong>: After making these changes, thoroughly test your app on different devices and OS versions to ensure a smooth launch experience without any visual glitches.​</li></ul><p>By following these steps, you can effectively remove the default splash screen from your Flutter application, providing a more streamlined startup experience for your users.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6287ee020d8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOLID Principles for Kids: Flutter Edition?]]></title>
            <link>https://medium.com/@ahmedtahaelelemy/solid-principles-for-kids-flutter-edition-5a3e20b52dac?source=rss-1a144ef4afe8------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a3e20b52dac</guid>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Ahmed Taha ElElemy]]></dc:creator>
            <pubDate>Mon, 28 Aug 2023 17:16:26 GMT</pubDate>
            <atom:updated>2023-08-28T17:16:26.841Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello, young coders! Today we’re going to learn about a big idea in programming called the SOLID principles. Don’t worry, it’s not as hard as it sounds! Imagine you’re building a LEGO castle. There are certain rules you follow, right? The same goes for coding. The SOLID principles are like our LEGO building rules for making our code neat, strong, and flexible.</p><p>There are five parts to SOLID, but today we’re going to focus on the last one, the ‘D’ which stands for Dependency Inversion Principle (DIP).</p><h3>What is Dependency Inversion Principle?</h3><p>Let’s imagine you have two LEGO blocks, a red one and a blue one. The red one always needs the blue one to do its job. This is called ‘dependency’. Now, if we change the blue block, we might affect the red block, right? That’s a problem! DIP helps us avoid this problem.</p><h3>Understanding DIP with an example</h3><p>Let’s think of a Flutter app as a big LEGO castle.</p><p>Imagine we have a part of our app that shows a list of your favorite toys. We have a ToyList class that fetches data from a ToyDatabase.</p><pre>class ToyDatabase {<br>  List&lt;String&gt; getToys() {<br>    // Fetches the toy data...<br>    return [&#39;Teddy Bear&#39;, &#39;Doll&#39;, &#39;Car&#39;, &#39;Dinosaur&#39;];<br>  }<br>}</pre><pre>class ToyList {<br>  final ToyDatabase database;</pre><pre>  ToyList(this.database);</pre><pre>  void displayToys() {<br>    final toys = database.getToys();<br>    toys.forEach((toy) =&gt; print(&#39;Toy: $toy&#39;));<br>  }<br>}</pre><p>Here, ToyList is like the red LEGO block and ToyDatabase is the blue one. ToyList depends on ToyDatabase. But, what if we want to change our database or get our toys from the Internet instead? We&#39;d have to change ToyList and that could lead to bugs!</p><h3>Using DIP to solve our problem</h3><p>To use DIP, we make an ‘agreement’ or ‘contract’ that both ToyList and ToyDatabase can follow. This contract is an interface.</p><pre>abstract class ToyProvider {<br>  List&lt;String&gt; getToys();<br>}</pre><p>Now, ToyDatabase can promise to follow this contract:</p><pre>class ToyDatabase implements ToyProvider {<br>  @override<br>  List&lt;String&gt; getToys() {<br>    // Fetches the toy data...<br>    return [&#39;Teddy Bear&#39;, &#39;Doll&#39;, &#39;Car&#39;, &#39;Dinosaur&#39;];<br>  }<br>}</pre><p>And ToyList can depend on the contract instead of depending directly on ToyDatabase.</p><pre>class ToyList {<br>  final ToyProvider provider;</pre><pre>  ToyList(this.provider);</pre><pre>  void displayToys() {<br>    final toys = provider.getToys();<br>    toys.forEach((toy) =&gt; print(&#39;Toy: $toy&#39;));<br>  }<br>}</pre><p>Now, if we want to change where we get our toys from, we can create a new class that follows the ToyProvider contract and ToyList won&#39;t be affected!</p><p>DIP is like saying, “Hey, I don’t need to know where you get the toys from, just promise me you’ll give me a list of toys when I ask for it!”</p><h3>Wrapping Up</h3><p>Just like building a LEGO castle, coding is all about creating something amazing step by step. The SOLID principles, including DIP, are our building rules that help us create code that is strong and easy to change, just like a well-built LEGO castle.</p><p>Keep building, little coders!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a3e20b52dac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding SOLID Principles: Interface Segregation Principle in Dart]]></title>
            <link>https://medium.com/@ahmedtahaelelemy/understanding-solid-principles-interface-segregation-principle-in-flutter-f7548e54ffb?source=rss-1a144ef4afe8------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7548e54ffb</guid>
            <category><![CDATA[google]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Ahmed Taha ElElemy]]></dc:creator>
            <pubDate>Wed, 23 Aug 2023 12:30:52 GMT</pubDate>
            <atom:updated>2023-08-23T23:48:00.780Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello, coders! Today, let’s learn about a very important concept in coding known as SOLID principles. Don’t worry, it’s not as hard as it sounds. Just think of it as a set of rules that help us write better and cleaner code.</p><p>Today, we’re going to focus on one of these principles. It’s called the Interface Segregation Principle, or ISP for short. It sounds fancy, but it’s quite simple. ISP says that no one should be forced to depend on interfaces they do not use.</p><h3>What is an Interface?</h3><p>Imagine you have a toy robot. To control this robot, you have a remote with buttons like ‘move forward’, ‘turn right’, ‘turn left’, ‘beep’ and ‘flash lights’. Each of these buttons is like an interface. When you press ‘move forward’, the robot knows it should move forward.</p><h3>What Does the Interface Segregation Principle Say?</h3><p>Now, suppose you have a teddy bear. And, for some reason, we use the same remote to control the teddy bear. But teddy bears can’t move or flash lights. So, those buttons are useless for the teddy bear. This is what ISP wants to avoid. It says that we should not have to worry about the buttons that we do not use.</p><h3>Case Study: A Flutter Example</h3><p>Now let’s learn how to apply this principle in Flutter with a simple example.</p><pre>abstract class Toy {<br>  void play();<br>  void move();<br>  void makeSound();<br>  void flashLights();<br>}</pre><pre>class Robot implements Toy {<br>  @override<br>  void play() {<br>    print(&#39;Robot: Playing...&#39;);<br>  }</pre><pre>  @override<br>  void move() {<br>    print(&#39;Robot: Moving...&#39;);<br>  }</pre><pre>  @override<br>  void makeSound() {<br>    print(&#39;Robot: Beeping...&#39;);<br>  }</pre><pre>  @override<br>  void flashLights() {<br>    print(&#39;Robot: Flashing lights...&#39;);<br>  }<br>}</pre><pre>class TeddyBear implements Toy {<br>  @override<br>  void play() {<br>    print(&#39;Teddy Bear: Playing...&#39;);<br>  }</pre><pre>  @override<br>  void move() {<br>    throw UnimplementedError();<br>  }</pre><pre>  @override<br>  void makeSound() {<br>    throw UnimplementedError();<br>  }</pre><pre>  @override<br>  void flashLights() {<br>    throw UnimplementedError();<br>  }<br>}</pre><p><strong>In this example,</strong> both Robot and TeddyBear are implementing the Toy interface. But, the TeddyBear doesn’t need the move(), makeSound(), and flashLights() methods. This violates the ISP because TeddyBear is forced to depend on interfaces that it does not use.</p><p>We can fix this by segregating the Toy interface into smaller interfaces.</p><pre>abstract class Toy {<br>  void play();<br>}</pre><pre>abstract class Movable {<br>  void move();<br>}</pre><pre>abstract class Soundable {<br>  void makeSound();<br>}</pre><pre>abstract class Lightable {<br>  void flashLights();<br>}</pre><pre>class Robot implements Toy, Movable, Soundable, Lightable {<br>  @override<br>  void play() {<br>    print(&#39;Robot: Playing...&#39;);<br>  }</pre><pre>  @override<br>  void move() {<br>    print(&#39;Robot: Moving...&#39;);<br>  }</pre><pre>  @override<br>  void makeSound() {<br>    print(&#39;Robot: Beeping...&#39;);<br>  }</pre><pre>  @override<br>  void flashLights() {<br>    print(&#39;Robot: Flashing lights...&#39;);<br>  }<br>}</pre><pre>class TeddyBear implements Toy {<br>  @override<br>  void play() {<br>    print(&#39;Teddy Bear: Playing...&#39;);<br>  }<br>}</pre><p>Now, TeddyBear only implements the Toy interface, and it doesn&#39;t have to worry about move(), makeSound(), and flashLights() anymore. And Robot can still implement all of these interfaces because it needs all of them.</p><p>So, that’s the Interface Segregation Principle. It helps our code be more flexible and easier to manage. Remember, it’s like saying, “Don’t force me to use the buttons I don’t need!” And that’s a good rule for coding and for life, isn’t it?</p><p>Keep coding and keep having fun! Next time, we’ll learn about another SOLID principle. See you then!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7548e54ffb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Liskov Substitution Principle: A Deep Dive into SOLID Principles]]></title>
            <link>https://medium.com/@ahmedtahaelelemy/understanding-the-liskov-substitution-principle-a-deep-dive-into-solid-principles-b02ac6a18ee3?source=rss-1a144ef4afe8------2</link>
            <guid isPermaLink="false">https://medium.com/p/b02ac6a18ee3</guid>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[google]]></category>
            <dc:creator><![CDATA[Ahmed Taha ElElemy]]></dc:creator>
            <pubDate>Thu, 10 Aug 2023 19:07:45 GMT</pubDate>
            <atom:updated>2023-08-10T19:07:45.018Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Note: This is the third in a series of articles that explore each of the five SOLID principles of object-oriented programming.</em></p><p>In the world of software engineering, SOLID principles play a pivotal role in building maintainable and scalable systems. Among these principles, the Liskov Substitution Principle (LSP) is perhaps one of the most misunderstood. Named after Barbara Liskov, who introduced it in a 1987 conference keynote, LSP is integral to ensuring that a system remains easy to manage and control.</p><h3>What is the Liskov Substitution Principle?</h3><p>The Liskov Substitution Principle states: “If S is a subtype of T, then objects of type T may be replaced with objects of type S without altering any of the desirable properties of the program (correctness, task performed, etc.).”</p><p>In simpler terms, any implementation of an abstraction (interface) should be substitutable anywhere that abstraction is accepted.</p><h3>Why is LSP Important?</h3><p>LSP is crucial to the maintainability of your code. When LSP is violated, it often leads to strange, hard-to-find bugs. If your code relies on a specific subclass behavior, but you’re using a base class reference, things can go awry. Adhering to LSP helps avoid these bugs and makes your code more robust and flexible.</p><h3>Liskov Substitution Principle in Action</h3><p>Let’s delve into a practical example to understand LSP better. We’ll use a popular example involving shapes.</p><pre>class Rectangle {<br>    protected int width, height;</pre><pre>    public void setWidth(int width) {<br>        this.width = width;<br>    }</pre><pre>    public void setHeight(int height) {<br>        this.height = height;<br>    }</pre><pre>    public int getWidth() {<br>        return width;<br>    }</pre><pre>    public int getHeight() {<br>        return height;<br>    }</pre><pre>    public int getArea() {<br>        return width * height;<br>    }<br>}</pre><pre>class Square extends Rectangle {<br>    @Override<br>    public void setWidth(int width) {<br>        super.setWidth(width);<br>        super.setHeight(width);<br>    }</pre><pre>    @Override<br>    public void setHeight(int height) {<br>        super.setWidth(height);<br>        super.setHeight(height);<br>    }<br>}</pre><p><strong>In this example,</strong> a Square is a subtype of Rectangle and overrides setWidth and setHeight methods. On the surface, this seems okay because a square is a rectangle. But let&#39;s see what happens when we write a function that uses these classes.</p><pre>void printArea(Rectangle r) {<br>    r.setWidth(5);<br>    r.setHeight(4);<br>    System.out.println(&quot;Expected area of 20, got &quot; + r.getArea());<br>}</pre><pre>void main() {<br>    Rectangle r = new Rectangle();<br>    printArea(r); // Expected area of 20, got 20</pre><pre>    Square s = new Square();<br>    printArea(s); // Expected area of 20, got 16<br>}</pre><p>This example violates LSP as the Square cannot be substituted for a Rectangle without altering the behavior of the printArea function. When we replaced the Rectangle with a Square in the printArea method, the result was different from what we expected.</p><h3>Case Study: Refactoring Code to Respect LSP</h3><p>So, how can we refactor the above code to adhere to LSP?</p><p>One potential solution might be to eliminate the Square subclass altogether and create a separate interface for shapes with areas. This solution would respect the LSP as there would be no inheritance relationship between different shape types. Here&#39;s what that might look like:</p><pre>interface ShapeWithArea {<br>    int getArea();<br>}</pre><pre>class Rectangle implements ShapeWithArea {<br>    protected int width, height;</pre><pre>    // ... existing Rectangle methods ...</pre><pre>    @Override<br>    public int getArea() {<br>        return width * height;<br>    }<br>}</pre><pre>class Square implements ShapeWithArea {<br>    private int side;</pre><pre>    public Square(int side) {<br>        this.side = side;<br>    }</pre><pre>    @Override<br>    public int getArea() {<br>        return side * side;<br>    }<br>}</pre><p><strong>In this refactored code,</strong> a Rectangle and a Square are both ShapeWithArea types, and they can be used interchangeably without changing the program&#39;s behavior.</p><h3>Conclusion</h3><p>The Liskov Substitution Principle is a powerful concept that enables developers to write more maintainable and scalable code. While it may seem complex initially, understanding and applying it in your projects will greatly increase the quality of your code. Remember, SOLID principles are not rules, but guidelines to help you design better systems. Keep exploring, and stay tuned for the next article in this series on the Interface Segregation Principle.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b02ac6a18ee3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Open/Closed Principle (OCP): A Deep Dive with Case Studies and Code Examples]]></title>
            <link>https://medium.com/@ahmedtahaelelemy/the-open-closed-principle-ocp-a-deep-dive-with-case-studies-and-code-examples-44485e5a11ba?source=rss-1a144ef4afe8------2</link>
            <guid isPermaLink="false">https://medium.com/p/44485e5a11ba</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Ahmed Taha ElElemy]]></dc:creator>
            <pubDate>Sun, 30 Jul 2023 20:21:55 GMT</pubDate>
            <atom:updated>2023-07-30T20:21:55.382Z</atom:updated>
            <content:encoded><![CDATA[<p>The world of software development is filled with principles, methodologies, and best practices that can help developers create high-quality, maintainable software. Among these principles, SOLID stands out as a widely-adopted approach that aims to make software designs more understandable, flexible, and maintainable. In this article, we’ll dive into the second principle of SOLID: the Open/Closed Principle (OCP).</p><h3>What is the Open/Closed Principle?</h3><p>The Open/Closed Principle, a term coined by Bertrand Meyer, states that “software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification”. This principle plays a crucial role in helping us control the complexity of our systems as they grow and change over time.</p><p>The objective of the OCP is to design our modules, classes, and functions in such a way that each time we have new functionality to add, we can do it by adding new code, not by changing old code that already works.</p><h3>Open/Closed Principle in Mobile Development</h3><p>In the realm of mobile development, the Open/Closed Principle is as relevant as it is in general software development. It allows us to add new features or change behaviors without the risk of breaking existing functionality. This is particularly important in mobile apps where any bug can directly affect the user experience.</p><p>Let’s take a look at an example in Swift, a popular language for iOS app development. Consider an app that has a DiscountCalculator class which calculates discounts for different types of products.</p><pre>class DiscountCalculator {<br>    func calculateDiscount(product: Product) -&gt; Double {<br>        if product.type == .electronic {<br>            return product.price * 0.10<br>        } else if product.type == .fashion {<br>            return product.price * 0.20<br>        } <br>        // other types...<br>        else {<br>            return 0.0<br>        }<br>    }<br>}</pre><p>This code works fine, but it violates the Open/Closed Principle. Every time a new product type is added, we have to modify the DiscountCalculator class. This can lead to unexpected bugs and makes the class hard to maintain.</p><h3>Now, let’s refactor this to adhere to the OCP:</h3><pre>protocol Discountable {<br>    func calculateDiscount() -&gt; Double<br>}</pre><pre>class ElectronicProduct: Discountable {<br>    var price: Double</pre><pre>    init(price: Double) {<br>        self.price = price<br>    }</pre><pre>    func calculateDiscount() -&gt; Double {<br>        return price * 0.10<br>    }<br>}</pre><pre>class FashionProduct: Discountable {<br>    var price: Double</pre><pre>    init(price: Double) {<br>        self.price = price<br>    }</pre><pre>    func calculateDiscount() -&gt; Double {<br>        return price * 0.20<br>    }<br>}</pre><p>And then we can simplify our DiscountCalculator class:</p><pre>class DiscountCalculator {<br>    func calculateDiscount(product: Discountable) -&gt; Double {<br>        return product.calculateDiscount()<br>    }<br>}</pre><p>Now, DiscountCalculator is closed for modification but open for extension. If we want to add a new product type, we just have to create a new class that conforms to the Discountable protocol. This approach reduces the risk of introducing new bugs into existing code.</p><h3>Case Study: An E-Commerce App</h3><p>Let’s take a real-world example: an e-commerce app that initially sells books and electronics. They have separate classes for handling each product type, and life is good. But as the business grows, they decide to add fashion items to their store.</p><p>Following the original design would mean modifying existing classes or copying and pasting code to create a new class for fashion items — both options are risky and can lead to bugs. However, by following the Open/Closed Principle, the developers can simply create a new class for fashion items that extends the base class or implements the necessary interface. The existing code doesn’t need to be touched.</p><p><strong>In this way,</strong> the Open/Closed Principle allows the e-commerce app to add as many new product types as they want, without the risk of breaking existing functionality. This leads to more stable, maintainable, and reliable software.</p><h3>Conclusion</h3><p>The Open/Closed Principle is a powerful tool for managing change in software systems. By designing our software in such a way that it is closed for modification but open for extension, we can add new functionality with minimal risk to existing functionality. This is crucial in mobile development where the cost of fixing bugs can be high and the impact on user experience can be significant.</p><p>Remember, the goal of these principles is not to apply them dogmatically, but to understand them and use them where they make sense and add value. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44485e5a11ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOLID Principles: A Deep Dive into the Single Responsibility Principle]]></title>
            <link>https://medium.com/@ahmedtahaelelemy/solid-principles-a-deep-dive-into-the-single-responsibility-principle-e73797df959d?source=rss-1a144ef4afe8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e73797df959d</guid>
            <category><![CDATA[google]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ahmed Taha ElElemy]]></dc:creator>
            <pubDate>Wed, 26 Jul 2023 09:02:06 GMT</pubDate>
            <atom:updated>2023-07-26T09:02:06.486Z</atom:updated>
            <content:encoded><![CDATA[<p>The SOLID principles are a set of five principles of object-oriented design and programming that were brought together by <strong>Robert C. Martin</strong>. The purpose of these principles is to make software designs more understandable, flexible, and maintainable. The acronym SOLID stands for Single Responsibility Principle (SRP), Open-Closed Principle (OCP), Liskov Substitution Principle (LSP), Interface Segregation Principle (ISP), and Dependency Inversion Principle (DIP).</p><p>This article focuses on the first principle — the Single Responsibility Principle (SRP). We will explore this principle in depth, provide code examples, and a case study from a real-world mobile application.</p><h3>What is the Single Responsibility Principle?</h3><p>The Single Responsibility Principle states that a class should have only one reason to change. In simple terms, a class should have only one job or responsibility. This principle is about bounding the context of classes, ensuring that a class takes care of only one concern.</p><p>By adhering to SRP, you reduce the complexity of your code, making it easier to read, maintain, and expand. It reduces errors and increases the overall quality of your code.</p><p>Let’s see how this works in practice with a code example.</p><h3>Code Example</h3><p>Consider you’re building a mobile application for your company blog. One feature is to allow users to create new blog posts.</p><p>Without following SRP, you might design a BlogPost class like this:</p><pre>class BlogPost {<br>    var title: String<br>    var content: String<br>    <br>    init(title: String, content: String) {<br>        self.title = title<br>        self.content = content<br>    }<br>    <br>    func saveToDatabase() {<br>        // Code to save the blog post into the database<br>    }<br>    <br>    func display() {<br>        // Code to display the blog post in the application UI<br>    }<br>}</pre><p>This BlogPost class is responsible for holding the blog post data, saving it to a database, and displaying it in the UI. This class is violating the Single Responsibility Principle because it has more than one reason to change. If you need to modify how blog posts are saved or how they are displayed, you would have to change the BlogPost class.</p><p>Let’s refactor this code to follow the Single Responsibility Principle:</p><pre>class BlogPost {<br>    var title: String<br>    var content: String<br>    <br>    init(title: String, content: String) {<br>        self.title = title<br>        self.content = content<br>    }<br>}</pre><pre>class DatabaseManager {<br>    func save(blogPost: BlogPost) {<br>        // Code to save the blog post into the database<br>    }<br>}</pre><pre>class UIManager {<br>    func display(blogPost: BlogPost) {<br>        // Code to display the blog post in the application UI<br>    }<br>}</pre><p>Now, each class has a single responsibility. The BlogPost class only holds the blog post data. The DatabaseManager class is responsible for saving the data into the database, and the UIManager class is responsible for displaying the blog post in the UI.</p><h3>Case Study</h3><p>Let’s consider a real-world mobile application case study: a fitness app that tracks user’s workouts and provides health tips.</p><p>In its initial release, the Workout class was responsible for storing workout data, calculating statistics like average speed and calories burned, and rendering these details on the UI.</p><pre>class Workout {<br>    // Workout data fields...<br>    <br>    func calculateStatistics() {<br>        // Calculate statistics...<br>    }<br>    <br>    func renderUI() {<br>        // Render details in the UI...<br>    }<br>}</pre><p>Over time, the Workout class became bloated as new features and statistics were added. Changes to the UI logic (like new themes) led to changes in the Workout class, violating the SRP.</p><p>The team decided to refactor the Workout class by separating the responsibilities:</p><pre>class Workout {<br>    // Workout data fields...<br>}</pre><pre>class WorkoutStatistics {<br>    private let workout: Workout</pre><pre>    init(workout: Workout) {<br>        self.workout = workout<br>    }</pre><pre>    func calculate() {<br>        // Calculate statistics...<br>    }<br>}</pre><pre>class WorkoutUI {<br>    private let workout: Workout</pre><pre>    init(workout: Workout) {<br>        self.workout = workout<br>    }</pre><pre>    func render() {<br>        // Render details in the UI...<br>    }<br>}</pre><p>After this refactor, the classes became more manageable. When a new statistic was introduced, only the WorkoutStatistics class needed to change. Similarly, changes to the UI only affected the WorkoutUI class. This made the code easier to understand and maintain, and more flexible for future changes.</p><h3>Conclusion</h3><p>The Single Responsibility Principle is a powerful way to design your classes and objects in a way that promotes readability, maintainability, and flexibility. By ensuring that each class has only one job, you can avoid many common pitfalls in software development, such as code that is difficult tounderstand and maintain.</p><p>However, like all principles, SRP is a guide rather than a strict rule. There might be cases where adhering strictly to SRP might lead to an unnecessary number of classes, making your codebase complex to navigate. Therefore, a balance must be struck to ensure the benefits are achieved without causing unnecessary complexity.</p><p>Remember that the ultimate goal of using SOLID principles, including SRP, is to improve the quality of your software. <strong>As Robert C. Martin</strong> said, “The first rule of classes is that they should be small. The second rule of classes is that they should be smaller than that.”</p><p>By understanding and correctly applying the Single Responsibility Principle, you are taking a significant step towards writing clean, high-quality code. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e73797df959d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Isolates in Flutter for Improved Performance]]></title>
            <link>https://medium.com/@ahmedtahaelelemy/using-isolates-in-flutter-for-improved-performance-439bccb14154?source=rss-1a144ef4afe8------2</link>
            <guid isPermaLink="false">https://medium.com/p/439bccb14154</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Ahmed Taha ElElemy]]></dc:creator>
            <pubDate>Sat, 22 Jul 2023 11:12:58 GMT</pubDate>
            <atom:updated>2023-07-22T11:12:58.703Z</atom:updated>
            <content:encoded><![CDATA[<p>Flutter’s Isolates offer a way to run code in parallel, similar to threads in other programming languages, but with some crucial differences. Their unique properties make them highly useful for improving performance and scalability within your Flutter apps.</p><h3>What are Isolates?</h3><p>Isolates are separate execution units in Dart, the language Flutter is built with, that can run in parallel. They possess two main distinguishing features:</p><ol><li><strong>Independent memory</strong>: Each isolate has its own heap and variables, ensuring they do not share memory. This isolation prevents race conditions and guarantees different parts of your code do not interfere with each other.</li><li><strong>Lightweight nature</strong>: Isolates are less resource-intensive than threads. They can be created and destroyed more easily, consuming less memory, making them a preferred choice for performance-sensitive applications.</li></ol><h3>Implementing Isolates in Flutter</h3><p>Flutter provides two primary ways to use Isolates:</p><ul><li>The Isolate.spawn() method, which creates a new isolate and runs the specified function in it.</li><li>The compute() function, which also creates a new isolate, runs the specified function, and returns a Future object to retrieve the function&#39;s result.</li></ul><p>Here’s a simple example of using the Isolate.spawn() method:</p><pre>import &#39;dart:isolate&#39;;</pre><pre>void main() {<br>  Isolate.spawn(_doSomethingInAnotherIsolate, &#39;Hello, world!&#39;);<br>}</pre><pre>void _doSomethingInAnotherIsolate(message) {<br>  print(&#39;I received the message &quot;$message&quot; from the main isolate.&#39;);<br>}</pre><p>The code above creates a new isolate and runs the _doSomethingInAnotherIsolate() function in it. The function prints the message passed from the main isolate.</p><p>Another way to use isolates is via the compute() function:</p><pre>import &#39;dart:async&#39;;</pre><pre>void main() {<br>  Future&lt;String&gt; result = compute(_doSomethingInAnotherIsolate, &#39;Hello, world!&#39;);<br>  print(result);<br>}</pre><pre>String _doSomethingInAnotherIsolate(message) {<br>  print(&#39;I received the message &quot;$message&quot; from the main isolate.&#39;);<br>  return message;<br>}</pre><p>This code creates a new isolate to run the _doSomethingInAnotherIsolate() function. It prints the received message and returns it. The main isolate then prints the result of the compute() function.</p><h3>Case Study: Enhancing Performance with Isolates</h3><p>Isolates can be utilized to offload computationally expensive tasks to a separate isolate. For instance, you could use an isolate to decode an image or calculate a complex mathematical function, freeing up the main isolate to update the user interface.</p><p>You can also use isolates for concurrent tasks. An isolate could download a file while the main isolate continues to interact with the user, allowing the user to keep using the app during the download.</p><p><strong>Simple Example</strong></p><p>Let’s create a simple example in Dart, a language often used with isolates in the Flutter framework, to demonstrate how isolates can be used to enhance performance by offloading a computationally expensive task.</p><p>In this example, we’ll create a function that calculates the factorial of a large number. Calculating factorials of large numbers can be computationally intensive, so we’ll use isolates to perform this task in the background, while the main isolate remains responsive to user interactions.</p><ol><li>First, let’s create the main Dart file, named main.dart:</li></ol><pre>import &#39;dart:isolate&#39;;</pre><pre>void main() {<br>  print(&quot;Starting factorial calculation...&quot;);</pre><pre>  final int number = 10000;<br>  calculateFactorialInBackground(number).then((result) {<br>    print(&quot;Factorial of $number is: $result&quot;);<br>  });</pre><pre>  // The main isolate can continue to do other tasks while the factorial is being calculated.<br>  for (int i = 0; i &lt; 10; i++) {<br>    print(&quot;Main isolate is doing some other task...&quot;);<br>  }<br>}</pre><pre>Future&lt;int&gt; calculateFactorialInBackground(int number) async {<br>  final ReceivePort receivePort = ReceivePort();</pre><pre>  await Isolate.spawn(_calculateFactorial, {&#39;number&#39;: number, &#39;sendPort&#39;: receivePort.sendPort});</pre><pre>  final completer = Completer&lt;int&gt;();<br>  receivePort.listen((data) {<br>    completer.complete(data);<br>    receivePort.close();<br>  });</pre><pre>  return completer.future;<br>}</pre><pre>void _calculateFactorial(Map&lt;String, dynamic&gt; message) {<br>  final int number = message[&#39;number&#39;];<br>  final SendPort sendPort = message[&#39;sendPort&#39;];</pre><pre>  int result = 1;<br>  for (int i = 1; i &lt;= number; i++) {<br>    result *= i;<br>  }</pre><pre>  sendPort.send(result);<br>}</pre><p><strong>In this example,</strong> we first define a function called calculateFactorialInBackground, which creates an isolate to calculate the factorial in the background. The calculateFactorialInBackground function returns a Future that will eventually hold the result of the factorial calculation.</p><p>The _calculateFactorial function is the actual computation that runs in the isolate. It receives the number for which the factorial needs to be calculated and a SendPort through which it will send back the result.</p><ol><li>Save the code in main.dart and execute it using the Dart SDK:</li></ol><pre>bashCopy code</pre><pre>dart main.dart</pre><p>The output will be:</p><pre>swiftCopy code</pre><pre>Starting factorial calculation...<br>Main isolate is doing some other task...<br>Main isolate is doing some other task...<br>Main isolate is doing some other task...<br>Main isolate is doing some other task...<br>Main isolate is doing some other task...<br>Main isolate is doing some other task...<br>Main isolate is doing some other task...<br>Main isolate is doing some other task...<br>Main isolate is doing some other task...<br>Main isolate is doing some other task...<br>Factorial of 10000 is: ...</pre><p>The factorial calculation is done in the background isolate, and the main isolate continues executing other tasks while waiting for the result.</p><p>Please note that in a real application, you would typically use isolates for more complex tasks and handle error scenarios and other considerations. However, this example demonstrates the basic concept of using isolates to enhance performance by offloading expensive computations to separate isolates.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=439bccb14154" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring List Manipulation in Flutter: Using clear(), any(), and sort() for Efficient and…]]></title>
            <link>https://medium.com/@ahmedtahaelelemy/how-to-use-clear-in-lists-in-flutter-d95ed1892392?source=rss-1a144ef4afe8------2</link>
            <guid isPermaLink="false">https://medium.com/p/d95ed1892392</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[lists]]></category>
            <dc:creator><![CDATA[Ahmed Taha ElElemy]]></dc:creator>
            <pubDate>Thu, 15 Jun 2023 15:37:28 GMT</pubDate>
            <atom:updated>2023-06-18T10:05:02.579Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exploring List Manipulation in Flutter: Using clear(), any(), and sort() for Efficient and Expressive Code</h3><p>If you’re building a Flutter app that deals with data, there’s a good chance you’ll be working with lists. Lists are a fundamental data structure that allow you to store and manipulate collections of data. Flutter provides a rich set of list manipulation methods, including clear(), any(), and sort(), that can help you work with lists more efficiently. In this article, we&#39;ll explore these methods and see how they can be used to simplify your code and make it more expressive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*15UFvi-YnuIWsxuefvhpxA.png" /></figure><h3>How to Use Clear in Lists in Flutter?</h3><p>In Flutter, the Clear method can be used to remove all items from a list. This can be useful when you need to clear the contents of a list and start fresh with new data. In this article, we will explore how to use Clear in lists in Flutter, along with some code examples and a case study.</p><h4>Using Clear in Lists</h4><p>The Clear method is available on all lists in Dart, including lists used in Flutter. It can be called on a list object to remove all items from the list. Here&#39;s an example of how to use Clear in a Flutter app:</p><pre>List&lt;String&gt; fruits = [&#39;apple&#39;, &#39;banana&#39;, &#39;orange&#39;, &#39;kiwi&#39;];</pre><pre>// Clear the list<br>fruits.clear();</pre><pre>// The list is now empty<br>print(fruits); // Output: []</pre><p><strong>In this example, </strong>we define a list of fruits and call the Clear method to remove all items from the list. After calling Clear, we print the contents of the list and see that it is now empty.</p><p>Clearing Lists in Flutter Apps</p><p>Clearing lists can be useful in many scenarios in Flutter apps. For example, suppose you have a list of items that is displayed in a ListView widget. When the user interacts with the app, you may need to update the contents of the list and display new data. In this case, you can use the Clear method to remove all items from the list and then add new items to the list.</p><pre>class MyListWidget extends StatefulWidget {<br>  @override<br>  _MyListWidgetState createState() =&gt; _MyListWidgetState();<br>}</pre><pre>class _MyListWidgetState extends State&lt;MyListWidget&gt; {<br>  List&lt;String&gt; items = [&#39;apple&#39;, &#39;banana&#39;, &#39;orange&#39;];</pre><pre>  void _refreshList() {<br>    // Clear the current list<br>    items.clear();</pre><pre>    // Add new items to the list<br>    items.addAll([&#39;kiwi&#39;, &#39;grape&#39;, &#39;mango&#39;]);</pre><pre>    // Update the state of the widget<br>    setState(() {});<br>  }</pre><pre>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: Text(&#39;My List&#39;),<br>      ),<br>      body: ListView.builder(<br>        itemCount: items.length,<br>        itemBuilder: (BuildContext context, int index) {<br>          return ListTile(<br>            title: Text(items[index]),<br>          );<br>        },<br>      ),<br>      floatingActionButton: FloatingActionButton(<br>        onPressed: _refreshList,<br>        child: Icon(Icons.refresh),<br>      ),<br>    );<br>  }<br>}</pre><p><strong>In this example,</strong> we define a MyListWidget class that displays a list of items in a ListView widget. We also define a _refreshList method that is called when the user taps a FloatingActionButton. The _refreshList method calls the Clear method to remove all items from the list, adds new items to the list, and then updates the state of the widget using setState.</p><h4>Case Study: Clearing a List of Search Results</h4><p>Suppose you have a Flutter app that allows users to search for items and displays the search results in a list. When the user clears the search query, you may need to clear the list of search results. In this case, you can use the Clear method to remove all items from the list.</p><pre>class SearchResultsWidget extends StatefulWidget {<br>  final String query;</pre><pre>  SearchResultsWidget({Key key, @required this.query}) : super(key: key);</pre><pre>  @override<br>  _SearchResultsWidgetState createState() =&gt; _SearchResultsWidgetState();<br>}</pre><pre>class _SearchResultsWidgetState extends State&lt;SearchResultsWidget&gt; {<br>  List&lt;String&gt; searchResults = [];</pre><pre>  void _performSearch() {<br>    // Perform search and update searchResults list<br>  }</pre><pre>  void _clearSearch() {<br>    // Clear the search results list<br>    searchResults.clear();</pre><pre>    // Update the state of the widget<br>    setState(() {});<br>  }</pre><pre>  @override<br>  void initState() {<br>    super.initState();</pre><pre>    // Perform initial search<br>    _performSearch();<br>  }</pre><pre>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: Text(&#39;Search results for ${widget.query}&#39;),<br>        actions: [<br>          IconButton(<br>            icon: Icon(Icons.clear),<br>            onPressed: _clearSearch,<br>          ),<br>        ],<br>      ),<br>      body: ListView.builder(<br>        itemCount: searchResults.length,<br>        itemBuilder: (BuildContext context, int index) {<br>          return ListTile(<br>            title: Text(searchResults[index]),<br>          );<br>        },<br>      ),<br>    );<br>  }<br>}</pre><p><strong>In this example,</strong> we define a SearchResultsWidget class that displays search results in a list. We also define a _clearSearch method that is called when the user taps a IconButton. The _clearSearch method calls the Clearmethod to remove all items from the searchResults list and updates the state of the widget. This ensures that the list of search results is cleared when the user clears the search query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*frnXUFbaeoBKIXNNHPXIeg.png" /></figure><h3>How to Use any in Lists in Flutter:</h3><p>In Flutter, the any method can be used to check if any element in a list meets a specific condition. This can be useful when you need to perform a check on a list and take action based on the result. In this article, we will explore how to use any in lists in Flutter, along with some code examples and a case study.</p><h3>Using any in Lists</h3><p>The any method is available on all lists in Dart, including lists used in Flutter. It can be called on a list object with a function that takes an element of the list as an argument and returns a boolean value. The any method then returns true if any element in the list satisfies the condition specified by the function, or false otherwise.</p><h3>Here’s an example of how to use any in a Flutter app:</h3><pre>List&lt;String&gt; fruits = [&#39;apple&#39;, &#39;banana&#39;, &#39;orange&#39;, &#39;kiwi&#39;];</pre><pre>// Check if the list contains the word &quot;kiwi&quot;<br>bool containsKiwi = fruits.any((fruit) =&gt; fruit == &#39;kiwi&#39;);</pre><pre>// The result is true<br>print(containsKiwi); // Output: true</pre><p><strong>In this example,</strong> we define a list of fruits and use the any method to check if the list contains the word &quot;kiwi&quot;. We pass a function to the any method that takes a fruit as an argument and returns true if the fruit is equal to &quot;kiwi&quot;. After calling any, we print the result and see that it is true.</p><h4>Using any in Flutter Apps</h4><p>Using any can be useful in many scenarios in Flutter apps. For example, suppose you have a list of items that is displayed in a ListView widget. When the user interacts with the app, you may need to check if the list contains a specific item and take action based on the result. In this case, you can use the any method to check if the list contains the item.</p><pre>class MyListWidget extends StatefulWidget {<br>  @override<br>  _MyListWidgetState createState() =&gt; _MyListWidgetState();<br>}</pre><pre>class _MyListWidgetState extends State&lt;MyListWidget&gt; {<br>  List&lt;String&gt; items = [&#39;apple&#39;, &#39;banana&#39;, &#39;orange&#39;];</pre><pre>  void _checkForItem(String item) {<br>    // Check if the list contains the item<br>    bool containsItem = items.any((i) =&gt; i == item);</pre><pre>    // Take action based on the result<br>    if (containsItem) {<br>      // Do something if the item is found<br>      print(&#39;$item is in the list&#39;);<br>    } else {<br>      // Do something if the item is not found<br>      print(&#39;$item is not in the list&#39;);<br>    }<br>  }</pre><pre>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: Text(&#39;My List&#39;),<br>      ),<br>      body: ListView.builder(<br>        itemCount: items.length,<br>        itemBuilder: (BuildContext context, int index) {<br>          return ListTile(<br>            title: Text(items[index]),<br>            onTap: () =&gt; _checkForItem(items[index]),<br>          );<br>        },<br>      ),<br>    );<br>  }<br>}</pre><p><strong>In this example,</strong> we define a MyListWidget class that displays a list of items in a ListView widget. We also define a _checkForItem method that is called when the user taps a ListTile. The _checkForItem method uses the any method to check if the items list contains the tapped item, and then takes action based on the result.</p><h4>Case Study: Checking for Duplicates in a List</h4><p>Suppose you have a Flutter app that allows users to add items to a list. When the user adds a new item, you may need to check if the list already contains the item to avoid duplicates. In this case, you can use the any method to check if the list contains the item.</p><pre>class MyListWidget extends StatefulWidget {<br>  @override<br>  _MyListWidgetState createState() =&gt; _MyListWidgetState();<br>}</pre><pre>class _MyListWidgetState extends State&lt;MyListWidget&gt; {<br>  List&lt;String&gt; items = [&#39;apple&#39;, &#39;banana&#39;, &#39;orange&#39;];</pre><pre>  void _addItem(String newItem) {<br>    // Check if the list already contains the item<br>    bool alreadyExists = items.any((item) =&gt; item == newItem);</pre><pre>    if (alreadyExists) {<br>      // Display an error message if the item already exists<br>      ScaffoldMessenger.of(context).showSnackBar(SnackBar(<br>        content: Text(&#39;$newItem already exists in the list&#39;),<br>      ));<br>    } else {<br>      // Add the new item to the list<br>      items.add(newItem);</pre><pre>      // Update the state of the widget<br>      setState(() {});<br>    }<br>  }</pre><pre>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: Text(&#39;My List&#39;),<br>      ),<br>      body: ListView.builder(<br>        itemCount: items.length,<br>        itemBuilder: (BuildContext context, int index) {<br>          return ListTile(<br>            title: Text(items[index]),<br>          );<br>        },<br>      ),<br>      floatingActionButton: FloatingActionButton(<br>        onPressed: () {<br>          // Show a dialog to get the new item from the user<br>          showDialog(<br>            context: context,<br>            builder: (BuildContext context) {<br>              return AlertDialog(<br>                title: Text(&#39;Add Item&#39;),<br>                content: TextField(<br>                  autofocus: true,<br>                  onSubmitted: _addItem,<br>                ),<br>                actions: [<br>                  TextButton(<br>                    onPressed: () =&gt; Navigator.pop(context),<br>                    child: Text(&#39;Cancel&#39;),<br>                  ),<br>                  TextButton(<br>                    onPressed: () {<br>                      // Get the value of the text field and add the item<br>                      String newItem = (context as Element).findAncestorWidgetOfExactType&lt;TextField&gt;().controller.text;<br>                      _addItem(newItem);</pre><pre>                      // Close the dialog<br>                      Navigator.pop(context);<br>                    },<br>                    child: Text(&#39;Add&#39;),<br>                  ),<br>                ],<br>              );<br>            },<br>          );<br>        },<br>        child: Icon(Icons.add),<br>      ),<br>    );<br>  }<br>}</pre><p><strong>In this example,</strong> we define a MyListWidget class that allows users to add items to a list. We use the any method to check if the list already contains the new item before adding it to the list. If the item already exists, we display an error message using a SnackBar. If the item does not exist, we add it to the list and update the state of the widget using setState.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*kTpeXoqXlUIEaDu25nrVHA.png" /></figure><h3>How to Use sort in Lists in Flutter:</h3><p>In Flutter, the sort method can be used to sort the elements in a list based on a specified comparison function. This can be useful when you need to organize or display data in a specific order. In this article, we will explore how to use sort in lists in Flutter, along with some code examples and a case study.</p><h4>Using sort in Lists</h4><p>The sort method is available on all lists in Dart, including lists used in Flutter. It can be called on a list object with a function that takes two elements of the list as arguments and returns an integer value. The sort method then sorts the list based on the values returned by the comparison function.</p><h4>Here’s an example of how to use sort in a Flutter app:</h4><pre>List&lt;int&gt; numbers = [5, 2, 3, 1, 4];</pre><pre>// Sort the list in ascending order<br>numbers.sort((a, b) =&gt; a.compareTo(b));</pre><pre>// The result is [1, 2, 3, 4, 5]<br>print(numbers);</pre><p><strong>In this example,</strong> we define a list of numbers and use the sort method to sort the list in ascending order. We pass a function to the sort method that takes two numbers as arguments and returns the result of compareTo, which compares the two numbers. After calling sort, we print the result and see that the list is sorted in ascending order.</p><h4>Using sort in Flutter Apps</h4><p>Using sort can be useful in many scenarios in Flutter apps. For example, suppose you have a list of objects that represent items in a shopping cart. When you display the items in the cart, you may want to sort them based on the item name or price. In this case, you can use the sort method to sort the list based on the specified criteria.</p><p>class MyCartWidget extends StatefulWidget {<br> @override<br> _MyCartWidgetState createState() =&gt; _MyCartWidgetState();<br>}</p><pre>class _MyCartWidgetState extends State&lt;MyCartWidget&gt; {<br>  List&lt;Item&gt; items = [<br>    Item(name: &#39;Apple&#39;, price: 0.99),<br>    Item(name: &#39;Banana&#39;, price: 0.59),<br>    Item(name: &#39;Orange&#39;, price: 0.79),<br>  ];</pre><pre>  void _sortByName() {<br>    // Sort the items by name<br>    items.sort((a, b) =&gt; a.name.compareTo(b.name));</pre><pre>    // Update the state of the widget<br>    setState(() {});<br>  }</pre><pre>  void _sortByPrice() {<br>    // Sort the items by price<br>    items.sort((a, b) =&gt; a.price.compareTo(b.price));</pre><pre>    // Update the state of the widget<br>    setState(() {});<br>  }</pre><pre>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: Text(&#39;My Cart&#39;),<br>      ),<br>      body: ListView.builder(<br>        itemCount: items.length,<br>        itemBuilder: (BuildContext context, int index) {<br>          return ListTile(<br>            title: Text(items[index].name),<br>            subtitle: Text(&#39;\$${items[index].price.toStringAsFixed(2)}&#39;),<br>          );<br>        },<br>      ),<br>      floatingActionButton: Row(<br>        mainAxisAlignment: MainAxisAlignment.end,<br>        children: [<br>          FloatingActionButton(<br>            onPressed: _sortByName,<br>            child: Icon(Icons.sort_by_alpha),<br>          ),<br>          SizedBox(width: 12),<br>          FloatingActionButton(<br>            onPressed: _sortByPrice,<br>            child: Icon(Icons.sort),<br>          ),<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><pre>class Item {<br>  final String name;<br>  final double price;</pre><pre>  Item({required this.name, required this.price});<br>}</pre><p><strong>In this example,</strong> we define a MyCartWidget class that displays a list of items in a ListView widget. We also define _sortByName and _sortByPrice methods that are called when the user taps floating action buttons. The _sortByName method uses the sort method to sort the items list by name, while the _sortByPrice method sorts the list by price. After sorting the list, we update the state of the widget using setState.</p><h4>Case Study: Sorting a List of Products</h4><p>Suppose you have a Flutter app that displays a list of products. Each product has a name, price, and rating. You may want to sort the products based on one of these criteria. In this case study, we will sort the products based on their rating.</p><pre>class MyProductListWidget extends StatefulWidget {<br>  @override<br>  _MyProductListWidgetState createState() =&gt; _MyProductListWidgetState();<br>}</pre><pre>class _MyProductListWidgetState extends State&lt;MyProductListWidget&gt; {<br>  List&lt;Product&gt; products = [<br>    Product(name: &#39;Product A&#39;, price: 9.99, rating: 4.5),<br>    Product(name: &#39;Product B&#39;, price: 14.99, rating: 4.2),<br>    Product(name: &#39;Product C&#39;, price: 19.99, rating: 4.8),<br>    Product(name: &#39;Product D&#39;, price: 7.99, rating: 3.9),<br>  ];</pre><pre>  void _sortByRating() {<br>    // Sort the products by rating<br>    products.sort((a, b) =&gt; b.rating.compareTo(a.rating));</pre><pre>    // Update the state of the widget<br>    setState(() {});<br>  }</pre><pre>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: Text(&#39;My Product List&#39;),<br>      ),<br>      body: ListView.builder(<br>        itemCount: products.length,<br>        itemBuilder: (BuildContext context, int index) {<br>          return ListTile(<br>            title: Text(products[index].name),<br>            subtitle: Text(&#39;\$${products[index].price.toStringAsFixed(2)}&#39;),<br>            trailing: Text(products[index].rating.toString()),<br>          );<br>        },<br>      ),<br>      floatingActionButton: FloatingActionButton(<br>        onPressed: _sortByRating,<br>        child: Icon(Icons.sort),<br>      ),<br>    );<br>  }<br>}</pre><pre>class Product {<br>  final String name;<br>  final double price;<br>  final double rating;</pre><pre>  Product({required this.name, required this.price, required this.rating});<br>}</pre><p><strong>In this case study,</strong> we define a MyProductListWidget class that displays a list of products in a ListView widget. We also define a _sortByRating method that is called when the user taps a floating action button. The _sortByRating method uses the sort method to sort the products list by rating in descending order. After sorting the list, we update the state of the widget using setState.</p><p><strong>In conclusion,</strong> Flutter provides a comprehensive set of list manipulation methods that can help you write more efficient and expressive code. By using methods like clear(), any(), and sort(), you can manipulate lists with ease and make your code more readable. Whether you&#39;re working with small or large datasets, these methods can help you achieve your desired results with minimal effort. Hopefully, this article has shed some light on these methods and given you some ideas on how to use them in your Flutter projects. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d95ed1892392" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Lists in Flutter: A Guide to Using firstWhere, fold, and insertAll]]></title>
            <link>https://medium.com/@ahmedtahaelelemy/mastering-lists-in-flutter-a-guide-to-using-firstwhere-fold-and-insertall-127c0e8022c8?source=rss-1a144ef4afe8------2</link>
            <guid isPermaLink="false">https://medium.com/p/127c0e8022c8</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ahmed Taha ElElemy]]></dc:creator>
            <pubDate>Wed, 07 Jun 2023 13:26:43 GMT</pubDate>
            <atom:updated>2023-06-07T13:26:43.700Z</atom:updated>
            <content:encoded><![CDATA[<p>Working with lists is a fundamental part of building apps in Flutter. While there are many built-in methods for manipulating lists, there are a few methods that are particularly useful for common tasks. In this article, we’ll explore three such methods: firstWhere, fold, and insertAll.</p><p>firstWhere allows you to find the first element in a list that satisfies a given condition. This is useful for filtering or searching a list based on a specific criterion. fold allows you to iterate over the elements of a list and accumulate a value based on each element. This is useful for performing calculations or transformations on a list. insertAll allows you to insert multiple elements into a list at a specific index. This is useful for adding new elements to a list.</p><h3><strong>1- firstWhere()</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*tkm-qvdh1mnMhCz0XX5X0w.png" /></figure><p>What is firstWhere?</p><p>It’s a method that allows you to find the first element in a list that satisfies a given condition. It takes a function as an argument that returns a boolean value, indicating whether the current element satisfies the condition. If it does, firstWhere returns that element. If no element satisfies the condition, firstWhere returns a default value.</p><h3>Using firstWhere in Lists:</h3><p>To use firstWhere in a list, you can simply call the method on the list and pass in a function that returns a boolean value. The function should take one parameter, which represents the current element being evaluated:</p><pre>var list = [1, 2, 3, 4, 5];</pre><pre>var firstEven = list.firstWhere((element) =&gt; element % 2 == 0);</pre><pre>print(firstEven); // 2</pre><p>In the example above, we have a list of integers and we want to find the first even number in the list. We call the firstWhere method on the list and pass in a function that checks whether the current element is even by using the modulo operator (%). The firstWhere method returns the first even number it encounters, which is 2 in this case.</p><p>If no element satisfies the condition, you can provide a default value to be returned instead:</p><pre>var list = [1, 3, 5, 7, 9];</pre><pre>var firstEven = list.firstWhere((element) =&gt; element % 2 == 0, orElse: () =&gt; -1);</pre><pre>print(firstEven); // -1</pre><p>In this example, we have a list of odd numbers and we want to find the first even number in the list. Since there are no even numbers in the list, we provide a default value of -1 to be returned instead. The firstWhere method returns the default value since no element satisfies the condition.</p><h4>Using firstWhere in a Shopping App</h4><p>Let’s say we’re building a shopping app and we have a list of products that we want to display to the user. Each product has a name, a price, and a category. We want to display the first product in each category to the user.</p><p>Here’s how we can use firstWhere to achieve this:</p><pre>class Product {<br>  final String name;<br>  final double price;<br>  final String category;</pre><pre>  Product({required this.name, required this.price, required this.category});<br>}</pre><pre>var products = [<br>  Product(name: &#39;iPhone&#39;, price: 999, category: &#39;Electronics&#39;),<br>  Product(name: &#39;AirPods&#39;, price: 199, category: &#39;Electronics&#39;),<br>  Product(name: &#39;T-Shirt&#39;, price: 19.99, category: &#39;Clothing&#39;),<br>  Product(name: &#39;Jeans&#39;, price: 49.99, category: &#39;Clothing&#39;),<br>  Product(name: &#39;Sneakers&#39;, price: 99.99, category: &#39;Shoes&#39;),<br>  Product(name: &#39;Boots&#39;, price: 149.99, category: &#39;Shoes&#39;),<br>];</pre><pre>var firstElectronics = products.firstWhere((product) =&gt; product.category == &#39;Electronics&#39;);<br>var firstClothing = products.firstWhere((product) =&gt; product.category == &#39;Clothing&#39;);<br>var firstShoes = products.firstWhere((product) =&gt; product.category == &#39;Shoes&#39;);</pre><pre>print(firstElectronics.name); // iPhone<br>print(firstClothing.name); // T-Shirt<br>print(firstShoes.name); // Sneakers</pre><p><strong>In this example,</strong> we define a Product class with three properties: name, price, and category. We then create a list of Product objects and use firstWhere to find the first product in each category. We pass a function to firstWhere that checks whether the current product&#39;s category matches the category we&#39;re interested in. The firstWhere method returns the first product it encounters that matches the category.</p><p><strong>using </strong><strong>firstWhere</strong> in lists in Flutter is a powerful way to find the first element that satisfies a given condition. By passing a function that returns a boolean value, you can easily search through a list and return the first element that matches your criteria. With the help of code examples and a case study, we hope this article has provided you with a comprehensive guide to using firstWhere in your Flutter projects.</p><h3>2- fold()</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*5xoQljpJLHdFrWVa9D8kjw.png" /></figure><h3>What is fold?</h3><p>fold is a method that takes an initial value and a function as arguments. The function should take two parameters: an accumulator and the current element being evaluated. The function returns a new accumulator value based on the current element. The fold method returns the final accumulator value after all elements have been evaluated.</p><h3>Using fold in Lists</h3><p>To use fold in a list, you can call the method on the list and pass in an initial value and a function. The initial value is the starting value for the accumulator. The function takes the accumulator and the current element as arguments and returns a new accumulator value based on the current element.</p><p><strong>Here’s an example of using </strong><strong>fold to calculate the sum of all elements in a list:</strong></p><pre>var list = [1, 2, 3, 4, 5];</pre><pre>var sum = list.fold(0, (accumulator, element) =&gt; accumulator + element);</pre><pre>print(sum); // 15</pre><p><strong>In this example,</strong> we have a list of integers and we want to calculate the sum of all elements. We call the fold method on the list and pass in an initial value of 0 and a function that adds the current element to the accumulator. The fold method returns the final accumulator value, which is the sum of all elements in the list.</p><h4>Using fold in a ToDo App</h4><p>Let’s say we’re building a ToDo app and we have a list of tasks that we want to display to the user. Each task has a title, a description, and a completion status. We want to display the number of completed tasks to the user.</p><p>Here’s how we can use fold to achieve this:</p><pre>class Task {<br>  final String title;<br>  final String description;<br>  final bool isComplete;</pre><pre>  Task({required this.title, required this.description, this.isComplete = false});<br>}</pre><pre>var tasks = [<br>  Task(title: &#39;Buy groceries&#39;, description: &#39;Milk, bread, eggs&#39;, isComplete: true),<br>  Task(title: &#39;Walk the dog&#39;, description: &#39;Around the block&#39;),<br>  Task(title: &#39;Do laundry&#39;, description: &#39;Wash, dry, fold&#39;, isComplete: true),<br>  Task(title: &#39;Clean the house&#39;, description: &#39;Vacuum, dust, mop&#39;),<br>];</pre><pre>var completedTasks = tasks.fold(0, (count, task) =&gt; task.isComplete ? count + 1 : count);</pre><pre>print(completedTasks); // 2</pre><p><strong>In this example,</strong> we define a Task class with three properties: title, description, and isComplete. We then create a list of Task objects and use fold to count the number of completed tasks. We pass an initial value of 0 to fold and a function that checks whether the current task is complete. If the task is complete, we increment the count by 1. The fold method returns the final count of completed tasks.</p><h3>3- insertAll()</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*k3fb8oDch1OnzcI39s7i-A.png" /></figure><h3>What is insertAll?</h3><p>insertAll is a method that takes an index and an iterable of elements as arguments. The iterable of elements is inserted into the list at the specified index.</p><h3>Using insertAll in Lists</h3><p>To use insertAll in a list, you can call the method on the list and pass in an index and an iterable of elements. The iterable of elements is inserted into the list at the specified index.</p><h4>Here’s an example of using insertAll to insert multiple elements into a list:</h4><pre>var list = [1, 2, 3, 4, 5];</pre><pre>list.insertAll(2, [6, 7, 8]);</pre><pre>print(list); // [1, 2, 6, 7, 8, 3, 4, 5]</pre><p><strong>In this example,</strong> we have a list of integers and we want to insert the elements [6, 7, 8] into the list at index 2. We call the insertAll method on the list and pass in the index 2 and the iterable of elements [6, 7, 8]. The insertAll method inserts the elements into the list at the specified index.</p><h3>Using insertAll in a Recipe App</h3><p>Let’s say we’re building a recipe app and we have a list of ingredients for a recipe. Each ingredient has a name and a quantity. We want to allow the user to add multiple ingredients at once.</p><h4>Here’s how we can use insertAll to achieve this:</h4><pre>class Ingredient {<br>  final String name;<br>  final double quantity;</pre><pre>  Ingredient({required this.name, required this.quantity});<br>}</pre><pre>var ingredients = [<br>  Ingredient(name: &#39;Flour&#39;, quantity: 2),<br>  Ingredient(name: &#39;Sugar&#39;, quantity: 1),<br>  Ingredient(name: &#39;Eggs&#39;, quantity: 3),<br>];</pre><pre>var newIngredients = [<br>  Ingredient(name: &#39;Milk&#39;, quantity: 1),<br>  Ingredient(name: &#39;Butter&#39;, quantity: 0.5),<br>];</pre><pre>ingredients.insertAll(1, newIngredients);</pre><pre>print(ingredients); // [Ingredient(name: &#39;Flour&#39;, quantity: 2.0), Ingredient(name: &#39;Milk&#39;, quantity: 1.0), Ingredient(name: &#39;Butter&#39;, quantity: 0.5), Ingredient(name: &#39;Sugar&#39;, quantity: 1.0), Ingredient(name: &#39;Eggs&#39;, quantity: 3.0)]</pre><p><strong>In this example,</strong> we define an Ingredient class with two properties: name and quantity. We then create a list of Ingredient objects and use insertAll to add multiple ingredients to the list at once. We create a new list of Ingredient objects and call insertAll on the original list at index 1 to insert the new ingredients. The insertAll method inserts the new ingredients into the original list at the specified index.</p><p>In conclusion, knowing how to effectively manipulate lists is an important skill for building apps in Flutter. The firstWhere, fold, and insertAll methods are powerful tools that can help you work with lists more efficiently and effectively. By mastering these methods, you can streamline your code and make your apps more responsive and user-friendly.</p><p>We hope that this article has been a helpful guide to understanding firstWhere, fold, and insertAll and how to use them in your Flutter projects. Whether you&#39;re a seasoned developer or just getting started with Flutter, these methods are essential tools to have in your toolkit. So go forth and start manipulating those lists!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=127c0e8022c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Manipulating List Data in Flutter: Exploring IndexOf(), Reduce(), and SetRange() Methods]]></title>
            <link>https://medium.com/@ahmedtahaelelemy/manipulating-list-data-in-flutter-exploring-indexof-reduce-and-setrange-methods-8122a6f9e853?source=rss-1a144ef4afe8------2</link>
            <guid isPermaLink="false">https://medium.com/p/8122a6f9e853</guid>
            <category><![CDATA[google]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[mobile]]></category>
            <dc:creator><![CDATA[Ahmed Taha ElElemy]]></dc:creator>
            <pubDate>Sat, 27 May 2023 18:31:41 GMT</pubDate>
            <atom:updated>2023-05-27T22:04:57.604Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Flutter</strong> provides developers with a plethora of methods to build performant and visually appealing mobile applications. Some useful methods are IndexOf(), Reduce(), and SetRange().</p><p><strong>IndexOf()</strong> allows developers to find the index of a specific element in a list or array. This is useful to implement search functionality, filter data, and much more.</p><p><strong>Reduce()</strong> allows developers to reduce a collection of values to a single value. This can be used to calculate things like sums, products, and concatenations of list elements.</p><p><strong>SetRange()</strong> allows developers to replace a range of elements in a list with new elements. This helps update subsets of data in lists with minimal effort.</p><p><strong>Together,</strong> these methods provide developers with the ability to efficiently manipulate and process list data within their Flutter applications. By leveraging these and other useful methods, developers can build robust applications that handle complex data manipulation tasks with ease.</p><h3>IndexOf():</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*MqTLzciGcXbfC1onYqxIig.png" /></figure><p><strong>In this article</strong>, we will explore the ‘index of’ method in Flutter and its usage with examples and code snippets.</p><p>The ‘index of’ method is a built-in method of the Dart programming language, which is the underlying language of the Flutter framework. This method is used to find the index of the first occurrence of a specified element in a list or an array. The syntax of the ‘index of’ method is as follows:</p><pre>int indexOf(Object element, [int start = 0])</pre><p><strong>Here,</strong> the ‘element’ parameter is the value to be searched in the list, and the ‘start’ parameter is the index from where the search should start. If the ‘start’ parameter is not provided, then the search will start from the beginning of the list. The ‘indexOf’ method returns the index of the first occurrence of the specified element in the list, or -1 if the element is not found.</p><p>Now, let’s take a look at some examples to understand the usage of the ‘index of’ method in Flutter.</p><h3>Example 1:</h3><p>Suppose we have a list of integers, and we want to find the index of the element 5 in the list. Here’s how we can use the ‘index of’ method to accomplish this task:</p><pre>List&lt;int&gt; numbers = [2, 4, 6, 8, 5, 10];<br>int index = numbers.indexOf(5);<br>print(index); // Output: 4</pre><p><strong>In this example,</strong> we have defined a list of integers called ‘numbers’ and initialized it with some values. We have then used the ‘indexOf’ method to find the index of the element 5 in the list. The method returns the value 4, which is the index of the first occurrence of the element 5 in the list.</p><h3>Example 2:</h3><p>Let’s take another example where we have a list of strings, and we want to find the index of the first occurrence of a string that starts with the letter ‘a’. Here’s how we can achieve this using the ‘index of’ method:</p><pre>List&lt;String&gt; fruits = [&#39;apple&#39;, &#39;banana&#39;, &#39;apricot&#39;, &#39;cherry&#39;, &#39;avocado&#39;];<br>int index = fruits.indexWhere((fruit) =&gt; fruit.startsWith(&#39;a&#39;));<br>print(index); // Output: 0</pre><p><strong>In this example,</strong> we have defined a list of strings called ‘fruits’ and initialized it with some values. We have then used the ‘indexWhere’ method along with a lambda function to find the index of the first occurrence of a string that starts with the letter ‘a’. The method returns thevalue 0, which is the index of the first occurrence of the string ‘apple’ in the list.</p><h3>Case Study:</h3><p>Let’s consider a real-world scenario where the ‘index of’ method can be used in a Flutter app. Suppose we are building a mobile app that displays a list of products, and we want to implement a search functionality that allows users to search for a specific product by name. Here’s how we can use the ‘index of’ method to accomplish this task:</p><pre>List&lt;Product&gt; products = [<br>  Product(name: &#39;iPhone 12&#39;, price: 999),<br>  Product(name: &#39;Samsung Galaxy S21&#39;, price: 899),<br>  Product(name: &#39;Google Pixel 5&#39;, price: 699),<br>  Product(name: &#39;OnePlus 9 Pro&#39;, price: 799),<br>];</pre><pre>String searchQuery = &#39;Google Pixel 5&#39;;<br>int index = products.indexWhere((product) =&gt; product.name == searchQuery);<br>if (index != -1) {<br>  // Product found<br>  print(&#39;Product Found: ${products[index].name}&#39;);<br>} else {<br>  // Product not found<br>  print(&#39;Product not found&#39;);<br>}</pre><p><strong>In this example,</strong> we have defined a list of ‘Product’ objects and initialized it with some values. We have then defined a ‘searchQuery’ variable that contains the name of the product we want to search for. We have used the ‘indexWhere’ method along with a lambda function to find the indexof the first occurrence of a product whose name matches the search query. If the index is not -1, then the product is found, and its name is printed. Otherwise, the product is not found, and a message is printed.</p><h3>Reduce():</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*XMkYSxqH_Ku9AikS9T3C4w.png" /></figure><p>One such method is the ‘reduce’ method, which is useful for reducing a collection of values to a single value. In this article, we will explore the ‘reduce’ method in Flutter and its usage with examples and code snippets.</p><p>The ‘reduce’ method is a built-in method of the Dart programming language, which is the underlying language of the Flutter framework. This method takes a collection of values and a ‘combine’ function as input and returns a single value that is the result of combining all the values in the collection. The syntax of the ‘reduce’ method is as follows:</p><pre>T reduce&lt;T&gt;(T combine(T previousValue, T element))</pre><p>Here, the ‘combine’ function is a callback function that takes two arguments: the previous value and the current element. The ‘combine’ function combines these two values and returns a new value that becomes the previous value for the next iteration. The ‘reduce’ method returns the final value obtained after all iterations are completed.</p><p>Now, let’s take a look at some examples to understand the usage of the ‘reduce’ method in Flutter.</p><h3>Example 1:</h3><p>Suppose we have a list of integers, and we want to find the sum of all the integers in the list. Here’s how we can use the ‘reduce’ method to accomplish this task:</p><pre>List&lt;int&gt; numbers = [1, 3, 5, 7, 9];<br>int sum = numbers.reduce((previousValue, element) =&gt; previousValue + element);<br>print(sum); // Output: 25</pre><p>In this example, we have defined a list of integers called ‘numbers’ and initialized it with some values. We have then used the ‘reduce’ method to find the sum of all the integers in the list. The ‘combine’ function takes two arguments: the previous sum and the current element. It adds these two values and returns the new sum, which becomes the previous sum for the next iteration. Finally, the ‘reduce’ method returns the final sum, which is 25.</p><h3>Example 2:</h3><p>Let’s take another example where we have a list of strings, and we want to concatenate all the strings in the list. Here’s how we can achieve this using the ‘reduce’ method:</p><pre>List&lt;String&gt; fruits = [&#39;apple&#39;, &#39;banana&#39;, &#39;orange&#39;, &#39;pear&#39;];<br>String result = fruits.reduce((previousValue, element) =&gt; previousValue + &#39;, &#39; + element);<br>print(result); // Output: apple, banana, orange, pear</pre><p><strong>In this example,</strong> we have defined a list of strings called ‘fruits’ and initialized it with some values. We have then used the ‘reduce’ method to concatenate all the strings in the list. The ‘combine’ function takes two arguments: the previous string and the current element. It concatenates these two valueswith a comma and a space in between and returns the new string, which becomes the previous string for the next iteration. Finally, the ‘reduce’ method returns the final concatenated string, which is ‘apple, banana, orange, pear’.</p><h3>Case Study:</h3><p>Let’s consider a real-world scenario where the ‘reduce’ method can be used in a Flutter app. Suppose we are building a mobile app that displays a list of products, and we want to calculate the total price of all the products. Here’s how we can use the ‘reduce’ method to accomplish this task:</p><pre>List&lt;Product&gt; products = [<br>  Product(name: &#39;iPhone 12&#39;, price: 999),<br>  Product(name: &#39;Samsung Galaxy S21&#39;, price: 899),<br>  Product(name: &#39;Google Pixel 5&#39;, price: 699),<br>  Product(name: &#39;OnePlus 9 Pro&#39;, price: 799),<br>];</pre><pre>double totalPrice = products.map((product) =&gt; product.price).reduce((previousValue, element) =&gt; previousValue + element);<br>print(totalPrice); // Output: 3396.0</pre><p><strong>In this example,</strong> we have defined a list of ‘Product’ objects and initialized it with some values. We have then used the ‘map’ method to extract the price of each product and create a new list of prices. We have then used the ‘reduce’ method to add up all the prices in the list and calculate the total price of all the products. The ‘combine’ function takes two arguments: the previous total price and the current price of the product. It adds these two values and returns the new total price, which becomes the previous total price for the next iteration. Finally, the ‘reduce’ method returns the final total price, which is 3396.0.</p><h3>SetRange():</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*vQhiZC1bX1dGcNLe0-1AKg.png" /></figure><p>One of the essential methods in Flutter is the ‘setRange()’ method, which is used to replace a range of elements in a list with new elements. In this article, we will explore the ‘setRange()’ method in Flutter and its usage with examples and code snippets.</p><p>The ‘setRange()’ method is a built-in method of the Dart programming language, which is the underlying language of the Flutter framework. This method is used to replace a range of elements in a list with new elements. The syntax of the ‘setRange()’ method is as follows:</p><pre>void setRange(int start, int end, Iterable&lt;E&gt; iterable, [int skipCount = 0])</pre><p><strong>Here,</strong> the ‘start’ parameter is the index of the first element to be replaced, and the ‘end’ parameter is the index of the last element to be replaced. The ‘iterable’ parameter is an iterable object containing the new elements to be inserted, and the ‘skipCount’ parameter is the number of elements to skip in the iterable object before starting to insert the new elements. If the ‘skipCount’ parameter is not provided, then it defaults to 0.</p><p>Now, let’s take a look at some examples to understand the usage of the ‘setRange()’ method in Flutter.</p><h3>Example 1:</h3><p>Suppose we have a list of integers, and we want to replace a range of elements in the list with new elements. Here’s how we can use the ‘setRange()’ method to accomplish this task:</p><pre>List&lt;int&gt; numbers = [1, 2, 3, 4, 5];<br>List&lt;int&gt; newNumbers = [6, 7, 8];<br>numbers.setRange(1, 4, newNumbers);<br>print(numbers); // Output: [1, 6, 7, 8, 5]</pre><p><strong>In this example</strong>, we have defined a list of integers called ‘numbers’ and initialized it with some values. We have then defined a new list of integers called ‘newNumbers’ and initialized it with some new values. We have then used the ‘setRange()’ method to replace a range of elements in the ‘numbers’ list with the new elements from the ‘newNumbers’ list. The method replaces the elements from index 1 to index 4 (excluding index 4) with the new elements from the ‘newNumbers’ list. Finally, we print the modified ‘numbers’ list, which is [1, 6, 7, 8, 5].</p><h3>Example 2:</h3><p>Let’s take another example where we have a list of strings, and we want to replace a range of elements in the list with new elements. Here’s how we can achieve this using the ‘setRange()’ method:</p><pre>List&lt;String&gt; fruits =[&#39;apple&#39;, &#39;banana&#39;, &#39;orange&#39;, &#39;pear&#39;];<br>List&lt;String&gt; newFruits = [&#39;mango&#39;, &#39;kiwi&#39;];<br>fruits.setRange(1, 3, newFruits);<br>print(fruits); // Output: [apple, mango, kiwi, pear]</pre><p><strong>In this example,</strong> we have defined a list of strings called ‘fruits’ and initialized it with some values. We have then defined a new list of strings called ‘newFruits’ and initialized it with some new values. We have then used the ‘setRange()’ method to replace a range of elements in the ‘fruits’ list with the new elements from the ‘newFruits’ list. The method replaces the elements from index 1 to index 3 (excluding index 3) with the new elements from the ‘newFruits’ list. Finally, we print the modified ‘fruits’ list, which is [‘apple’, ‘mango’, ‘kiwi’, ‘pear’].</p><h3>Case Study:</h3><p>Let’s consider a real-world scenario where the ‘setRange()’ method can be used in a Flutter app. Suppose we are building a mobile app that allows users to create a to-do list and mark tasks as completed. Here’s how we can use the ‘setRange()’ method to mark multiple tasks as completed:</p><pre>List&lt;Task&gt; tasks = [<br>  Task(title: &#39;Buy groceries&#39;, isCompleted: false),<br>  Task(title: &#39;Clean the house&#39;,isCompleted: false),<br>  Task(title: &#39;Take out the trash&#39;, isCompleted: false),<br>  Task(title: &#39;Do laundry&#39;, isCompleted: false),<br>];</pre><pre>List&lt;int&gt; completedTaskIndices = [1, 3];<br>for (int index in completedTaskIndices) {<br>  tasks[index].isCompleted = true;<br>}</pre><p><strong>In this example,</strong> we have defined a list of ‘Task’ objects called ‘tasks’ and initialized it with some values. We have then defined a list of integers called ‘completedTaskIndices’ and initialized it with the indices of the tasks that we want to mark as completed. Finally, we have used a loop to iterate over the ‘completedTaskIndices’ list and mark the corresponding tasks as completed by setting the ‘isCompleted’ property to true. This approach works fine for marking a few tasks as completed, but it can become cumbersome and error-prone for marking a large number of tasks as completed.</p><p><strong>Instead,</strong> we can use the ‘setRange()’ method to mark multiple tasks as completed in a single line of code:</p><pre>List&lt;int&gt; completedTaskIndices = [1, 3];<br>tasks.setRange(1, 4, tasks.getRange(1, 4).map((task) =&gt; Task(title: task.title, isCompleted: true)));</pre><p><strong>In this approach,</strong> we have used the ‘getRange()’ method to get a range of tasks from the ‘tasks’ list that we want to mark as completed.We have then used the ‘map()’ method to create a new list of ‘Task’ objects with the same title as the original tasks but with the ‘isCompleted’ property set to true. Finally, we have used the ‘setRange()’ method to replace the range of tasks with the new list of completed tasks. This approach is more concise and less error-prone, especially when dealing with a large number of tasks.</p><h3>At The End :</h3><p><strong>As seen in the examples and case studies,</strong> IndexOf() allows locating products by name, Reduce() allows calculating total prices of products, and SetRange() allows marking multiple todo list items as completed in a simple way. These methods, and others like them, helpFlutter developers work smarter, not harder.</p><p><strong>In summary,</strong> the list manipulation methods provided by Flutter, like IndexOf(), Reduce(), and SetRange(), allow developers to efficiently perform common tasks when working with data in lists. Understanding and utilizing these methods appropriately can improve the functionality, performance, and maintainability of Flutter applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8122a6f9e853" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>