<?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 Khondakar Afridi on Medium]]></title>
        <description><![CDATA[Stories by Khondakar Afridi on Medium]]></description>
        <link>https://medium.com/@afridi.khondakar?source=rss-3ee2b01f5cab------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6Dp3n59Kn2-CuquiWFc3DQ.jpeg</url>
            <title>Stories by Khondakar Afridi on Medium</title>
            <link>https://medium.com/@afridi.khondakar?source=rss-3ee2b01f5cab------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 14:43:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@afridi.khondakar/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[Understanding Flutter Keys Beyond the Basics: ValueKey, ObjectKey, UniqueKey, and GlobalKey]]></title>
            <link>https://medium.com/@afridi.khondakar/understanding-flutter-keys-beyond-the-basics-valuekey-objectkey-uniquekey-and-globalkey-2c59b94fd4bd?source=rss-3ee2b01f5cab------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c59b94fd4bd</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <dc:creator><![CDATA[Khondakar Afridi]]></dc:creator>
            <pubDate>Fri, 30 Oct 2026 13:12:07 GMT</pubDate>
            <atom:updated>2026-10-30T13:12:07.975Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h8UCohtSo0k15XLdB4fGvA.png" /></figure><p><em>How Flutter manages widget identity, preserves state, and why choosing the wrong key can cause some surprisingly difficult bugs.</em></p><p>If you’ve been working with Flutter for a while, you’ve probably used ValueKey, UniqueKey, or even GlobalKey at some point.</p><p>Maybe you’ve used a GlobalKey&lt;FormState&gt; to validate a form. Or perhaps you&#39;ve worked with a ReorderableListView and Flutter required you to assign a key to every item.</p><p>And in most cases, that’s where our understanding of keys stops.</p><p>We know what they do, at least on the surface. But what actually happens behind the scenes? Why does a widget sometimes lose its state after being moved? Why does assigning a UniqueKey fix one problem while potentially introducing another? And why does Flutter need keys in the first place?</p><p>These questions become much more relevant when you’re working on larger production applications, especially ones with dynamic lists, complex stateful components, real-time data, and frequently changing UI structures.</p><p>In this article, I want to go through how keys actually work in Flutter, starting with the fundamentals and gradually building a production-style example.</p><p>Rather than using four completely unrelated examples, we’ll build a shopping cart and checkout flow, introduce a few realistic problems, and see how each type of key helps us solve them.</p><p>Along the way, we’ll also look at what’s happening inside Flutter’s rendering framework.</p><p>Let’s get into it.</p><h3>1. Before Understanding Keys, We Need to Understand How Flutter Rebuilds Widgets</h3><p>One of the first things we learn about Flutter is that widgets are immutable.</p><p>Whenever we call setState(), Flutter schedules a rebuild of the affected part of the widget tree.</p><p>But here’s something worth understanding:</p><p><strong>Rebuilding a widget does not necessarily mean Flutter destroys the existing UI and recreates everything from scratch.</strong></p><p>Flutter maintains three important trees:</p><p><strong>Widget Tree</strong></p><p>This is the configuration of our UI. Widgets describe what we want the interface to look like.</p><p><strong>Element Tree</strong></p><p>This is where Flutter maintains the actual structure of mounted widgets, tracks their identities, and associates stateful widgets with their State objects.</p><p><strong>RenderObject Tree</strong></p><p>This handles layout, painting, hit testing, and other rendering responsibilities.</p><p>Not every widget creates its own RenderObject, but the Element tree is central to connecting widget configurations with the underlying rendering system.</p><p>The important part for our discussion is the relationship between Widgets and Elements.</p><p>Widgets are lightweight configurations that Flutter can recreate frequently.</p><p>Elements, on the other hand, are persistent objects that Flutter attempts to reuse.</p><p>And for a StatefulWidget, the associated State object belongs to its StatefulElement.</p><p>This distinction is important because when a widget rebuilds, Flutter needs to answer a question:</p><p><strong>Should I update the existing Element with this new widget configuration, or should I replace it with a completely new Element?</strong></p><p>This is where keys come into play.</p><h3>How Flutter decides whether to reuse an Element</h3><p>Internally, Flutter uses a method called Widget.canUpdate().</p><p>Its implementation is surprisingly simple:</p><pre>static bool canUpdate(<br>  Widget oldWidget,<br>  Widget newWidget,<br>) {<br>  return oldWidget.runtimeType ==<br>             newWidget.runtimeType &amp;&amp;<br>         oldWidget.key == newWidget.key;<br>}</pre><p>Essentially, Flutter compares two things:</p><ol><li>The runtime type of the widget.</li><li>The key assigned to the widget.</li></ol><p>If both match, the existing Element can be updated with the new widget.</p><p>For stateful widgets, this generally means the existing State object can be preserved.</p><p>If they don’t match, Flutter cannot update that Element with the new configuration. It must instead reconcile the change using another Element or create a new one.</p><p>There’s an interesting detail here.</p><p>When neither widget has a key, both keys are null.</p><p>So if the widgets have the same runtime type, Flutter can consider them compatible even if they represent completely different pieces of application data.</p><p>And that brings us to our first real problem.</p><h3>2. Let’s Build a Shopping Cart</h3><p>Imagine we’re developing an e-commerce application.</p><p>Our shopping cart contains multiple products, and each cart item allows users to adjust quantities, select options, and add notes.</p><p>Let’s start with a simple product model.</p><pre>class CartItem {<br>  final String id;<br>  final String name;<br>  final double price;</pre><pre>  const CartItem({<br>    required this.id,<br>    required this.name,<br>    required this.price,<br>  });<br>}</pre><p>Now imagine we have three products:</p><pre>final products = [<br>  CartItem(<br>    id: &#39;bag-101&#39;,<br>    name: &#39;Everyday Tote&#39;,<br>    price: 1299,<br>  ),<br>  CartItem(<br>    id: &#39;wallet-102&#39;,<br>    name: &#39;Classic Wallet&#39;,<br>    price: 499,<br>  ),<br>  CartItem(<br>    id: &#39;watch-103&#39;,<br>    name: &#39;Minimal Watch&#39;,<br>    price: 1899,<br>  ),<br>];</pre><p>For demonstration purposes, let’s create a stateful cart item widget.</p><pre>class CartItemTile extends StatefulWidget {<br>  final CartItem product;</pre><pre>  const CartItemTile({<br>    super.key,<br>    required this.product,<br>  });</pre><pre>  @override<br>  State&lt;CartItemTile&gt; createState() =&gt;<br>      _CartItemTileState();<br>}</pre><pre>class _CartItemTileState<br>    extends State&lt;CartItemTile&gt; {<br>  int quantity = 1;</pre><pre>  @override<br>  Widget build(BuildContext context) {<br>    return ListTile(<br>      title: Text(widget.product.name),<br>      subtitle: Text(<br>        &#39;Quantity: $quantity&#39;,<br>      ),<br>      trailing: IconButton(<br>        icon: const Icon(Icons.add),<br>        onPressed: () {<br>          setState(() =&gt; quantity++);<br>        },<br>      ),<br>    );<br>  }<br>}</pre><p>This implementation keeps the quantity inside the widget’s local State.</p><p>In a production e-commerce application, the actual cart quantity would usually belong to a cart controller, Bloc, Riverpod provider, or another application-level state holder.</p><p>But we’re deliberately keeping it local for now, because it makes a common Element identity problem easier to understand.</p><p>Let’s render the products:</p><pre>Column(<br>  children: [<br>    for (final product in products)<br>      CartItemTile(product: product),<br>  ],<br>)</pre><p>Everything works.</p><p>We increment the quantity of the bag to three. The wallet remains at one.</p><p>Now we introduce sorting.</p><p>Maybe users want to sort their cart by price, product name, or recently added items.</p><p>When the order changes, something unexpected can happen.</p><p>The bag’s quantity might appear on the wallet.</p><p>Why?</p><p>Because Flutter was matching the stateful widgets by their type and position.</p><p>Before sorting:</p><p>PositionProductElementQuantity0BagElement A31WalletElement B12WatchElement C1</p><p>After sorting without keys:</p><p>PositionProductReused ElementQuantity0WalletElement A31BagElement B12WatchElement C1</p><p>Notice what happened?</p><p>Flutter preserved the Elements at their positions, but the product configurations changed.</p><p>The local State remained associated with the Element rather than following the logical product.</p><p>From Flutter’s perspective, this behavior makes sense.</p><p>The widgets have the same runtime type, and neither has a key.</p><p>There is nothing telling the framework that the bag at position zero is the same logical item that has now moved to position one.</p><p><strong>This is the problem keys are designed to solve.</strong></p><h3>3. ValueKey: Preserving Identity Using a Stable Value</h3><p>The first and most commonly useful key is ValueKey.</p><p>A ValueKey&lt;T&gt; uses the equality of its underlying value to establish identity.</p><p>For example:</p><pre>const key1 = ValueKey(&#39;bag-101&#39;);<br>const key2 = ValueKey(&#39;bag-101&#39;);</pre><pre>print(key1 == key2); // true</pre><p>Even though these are two separate variable declarations, the keys represent the same identity because their values are equal.</p><p>Now let’s update our shopping cart.</p><pre>Column(<br>  children: [<br>    for (final product in products)<br>      CartItemTile(<br>        key: ValueKey(product.id),<br>        product: product,<br>      ),<br>  ],<br>)</pre><p>That’s it.</p><p>We’ve associated each widget with a stable product ID.</p><p>Now, when the order changes, Flutter can match the keyed child with its corresponding existing Element.</p><p>The bag moves to a new position, but its State moves with it.</p><p>The quantity remains three.</p><p>The wallet remains at one.</p><p>The important distinction is that we’re no longer relying purely on positional identity.</p><p>We’re using <strong>logical identity</strong>.</p><h3>Why not use the list index?</h3><p>You might have seen something like this:</p><pre>CartItemTile(<br>  key: ValueKey(index),<br>  product: product,<br>)</pre><p>And technically, this is a valid key.</p><p>But it doesn’t solve our particular problem.</p><p>Suppose the bag is at index zero and the wallet is at index one.</p><p>After sorting, the wallet moves to index zero.</p><p>Its key is now ValueKey(0), which is exactly the key previously associated with the bag.</p><p>We’ve essentially recreated the same positional identity problem, just with additional code.</p><p>For dynamic collections, keys should represent the underlying data rather than its current position.</p><p>So this:</p><pre>ValueKey(product.id)</pre><p>is generally preferable to this:</p><pre>ValueKey(index)</pre><p>when items can be inserted, removed, or reordered.</p><h3>What about API refreshes?</h3><p>This is another reason stable IDs matter.</p><p>Imagine our shopping cart is synchronized with a backend.</p><p>The user opens the application, we fetch products from Firestore or an API, and construct our model objects.</p><p>Later, we refresh the cart and recreate those model instances.</p><p>The objects might be completely new Dart instances, but their product IDs remain the same.</p><p>With:</p><pre>ValueKey(product.id)</pre><p>Flutter still recognizes the logical identity of each product.</p><p>The key remains stable even though the model instance has changed.</p><p>That’s exactly the behavior we want in most API-driven applications.</p><h3>A production consideration: Unique IDs</h3><p>The value used for a key must be unique among sibling widgets participating in the same reconciliation scope.</p><p>For example, if the same product can appear twice as separate cart lines because it has different variants, using only the product ID might not be sufficient.</p><p>Instead, use a stable cart-line ID:</p><pre>CartItemTile(<br>  key: ValueKey(cartLine.id),<br>  product: cartLine.product,<br>)</pre><p>The identity should describe the actual entity represented by the UI, not just one of its properties.</p><p><strong>My general rule:</strong> When you’re rendering a dynamic collection of entities with stable IDs, ValueKey should usually be your first consideration.</p><h3>4. ObjectKey: When the Object Instance Itself Defines Identity</h3><p>Now let’s extend the shopping cart.</p><p>Suppose we’re implementing a product customization feature.</p><p>Users can add custom accessories to their cart, configure colors, modify options, and maintain multiple independent drafts.</p><p>Unlike our regular products, these customization drafts may not have backend IDs yet.</p><p>Instead, the application creates a draft object and keeps that exact instance alive while the user edits it.</p><p>Something like:</p><pre>class CustomizationDraft {<br>  String color;<br>  String? engraving;</pre><pre>  CustomizationDraft({<br>    required this.color,<br>    this.engraving,<br>  });<br>}</pre><p>We might maintain a collection of these objects:</p><pre>final drafts = [<br>  CustomizationDraft(color: &#39;Red&#39;),<br>  CustomizationDraft(color: &#39;Black&#39;),<br>];</pre><p>We want to be able to reorder these drafts while preserving each editor’s local State.</p><p>But now, instead of using a database ID, the individual draft object is our identity.</p><p>This is where ObjectKey becomes useful.</p><pre>Column(<br>  children: [<br>    for (final draft in drafts)<br>      CustomizationEditor(<br>        key: ObjectKey(draft),<br>        draft: draft,<br>      ),<br>  ],<br>)</pre><p>An ObjectKey identifies a widget based on the identity of the object it wraps.</p><p>But there’s a subtle difference between ObjectKey and ValueKey.</p><h3>Value equality vs object identity</h3><p>Consider the following class:</p><pre>class Product {<br>  final String id;</pre><pre>  Product(this.id);</pre><pre>  @override<br>  bool operator ==(Object other) {<br>    return other is Product &amp;&amp;<br>        other.id == id;<br>  }</pre><pre>  @override<br>  int get hashCode =&gt; id.hashCode;<br>}</pre><p>Now we create two product instances:</p><pre>final productA = Product(&#39;101&#39;);<br>final productB = Product(&#39;101&#39;);</pre><p>Because we’ve overridden equality:</p><pre>print(productA == productB);<br>// true</pre><p>But these are still two distinct objects in memory.</p><pre>print(identical(productA, productB));<br>// false</pre><p>Now compare their keys:</p><pre>print(<br>  ValueKey(productA) == ValueKey(productB),<br>);<br>// true</pre><p>And:</p><pre>print(<br>  ObjectKey(productA) == ObjectKey(productB),<br>);<br>// false</pre><p>That’s the fundamental distinction.</p><p>ValueKey compares the wrapped values using ==.</p><p>ObjectKey compares the wrapped objects using identical().</p><h3>When does this matter in production?</h3><p>Let’s return to our customization drafts.</p><p>If the user reorders a list while we continue using the same draft objects, ObjectKey allows Flutter to preserve the correct editor State.</p><p>But if we replace a draft with a completely new object instance, Flutter treats it as a different identity.</p><p>Even if the new draft contains identical values.</p><p>This can be useful when replacing the entire draft is supposed to represent a new editing session.</p><p>However, it can also be problematic when your state-management architecture frequently recreates immutable model objects.</p><p>For example, imagine a Bloc emitting a new list of copied objects after every state update.</p><p>Using ObjectKey on those objects could repeatedly change widget identities and cause unexpected State loss.</p><p>That’s why I wouldn’t use ObjectKey as a general replacement for ValueKey.</p><p>Use it when <strong>the specific object instance is the entity you want Flutter to track</strong>.</p><p>For most server-backed business entities with persistent identifiers, ValueKey remains the better option.</p><h3>5. UniqueKey: When We Actually Want Flutter to Forget the Old State</h3><p>So far, we’ve used keys to preserve State.</p><p>But there are situations where preserving State is precisely what we don’t want.</p><p>Let’s add another feature to our shopping cart application.</p><p>Suppose users can preview a promotional product configuration before adding it to their cart.</p><p>The preview has its own internal State, perhaps an animation controller, selected options, and temporary preview interactions.</p><p>When the user selects <strong>Start New Preview</strong>, we want the entire preview experience to start fresh.</p><p>We could manually reset every controller and local variable.</p><p>But sometimes, there’s a simpler solution.</p><p>UniqueKey.</p><p>Unlike ValueKey or ObjectKey, every newly constructed UniqueKey has its own identity.</p><pre>final key1 = UniqueKey();<br>final key2 = UniqueKey();</pre><pre>print(key1 == key2);</pre><pre>// false</pre><p>Now let’s implement our preview.</p><pre>class ProductPreviewHost<br>    extends StatefulWidget {<br>  const ProductPreviewHost({<br>    super.key,<br>  });</pre><pre>  @override<br>  State&lt;ProductPreviewHost&gt; createState() =&gt;<br>      _ProductPreviewHostState();<br>}</pre><pre>class _ProductPreviewHostState<br>    extends State&lt;ProductPreviewHost&gt; {<br>  Key _previewKey = UniqueKey();</pre><pre>  void _restartPreview() {<br>    setState(() {<br>      _previewKey = UniqueKey();<br>    });<br>  }</pre><pre>  @override<br>  Widget build(BuildContext context) {<br>    return Column(<br>      children: [<br>        ProductPreview(<br>          key: _previewKey,<br>        ),<br>        ElevatedButton(<br>          onPressed: _restartPreview,<br>          child: const Text(<br>            &#39;Start New Preview&#39;,<br>          ),<br>        ),<br>      ],<br>    );<br>  }<br>}</pre><p>Here’s what happens when the button is pressed.</p><p>First, we generate a completely new key.</p><p>Then Flutter rebuilds the parent and compares the previous ProductPreview widget with the new one.</p><p>The runtime type is the same.</p><p>But the keys are different.</p><p>Therefore, Widget.canUpdate() returns false for that pair.</p><p>Flutter cannot reuse the old Element for the new configuration.</p><p>Instead, it creates a fresh Element, and the new stateful preview gets a new State object.</p><p>The old preview is removed through Flutter’s normal Element lifecycle and eventually disposed.</p><p>This gives us a clean reset of the local widget subtree.</p><h3>A very common mistake</h3><p>Consider this:</p><pre>@override<br>Widget build(BuildContext context) {<br>  return ProductPreview(<br>    key: UniqueKey(),<br>  );<br>}</pre><p>It looks harmless.</p><p>But there’s a problem.</p><p>Every time the parent rebuilds, we’re constructing another unique identity.</p><p>That means Flutter cannot reuse the preview’s previous Element through normal matching.</p><p>Even if nothing meaningful about the preview changed.</p><p>Imagine that our shopping cart rebuilds when:</p><ul><li>A product quantity changes.</li><li>A promotional offer updates.</li><li>The cart total changes.</li><li>A parent Bloc emits a new state.</li></ul><p>If we continuously generate new keys during those builds, the preview’s local State can keep resetting.</p><p>That might cause animations to restart, controllers to be recreated, or temporary user interactions to disappear.</p><p>The issue isn’y is inherently expt that UniqueKeensive.</p><p>The issue is that we’re telling Flutter to treat an otherwise unchanged widget as a completely new entity.</p><p><strong>Use </strong><strong>UniqueKey when you intentionally need a new identity, not as a general solution for rebuild problems.</strong></p><p>There’s also an architectural consideration here.</p><p>If resetting a widget requires discarding important domain data, using a new key isn’t necessarily the right solution.</p><p>Application-level data should be reset through the appropriate state-management layer.</p><p>Keys control widget identity. They should not become a substitute for proper business-state management.</p><h3>6. GlobalKey: Going Beyond Local Widget Identity</h3><p>Now let’s move to our checkout screen.</p><p>The user has selected their products and is ready to place an order.</p><p>We need to collect their name, phone number, and delivery address.</p><p>Naturally, we’ll use a Form.</p><p>And we want to validate the entire form before allowing checkout.</p><p>This is one of the most common legitimate use cases for GlobalKey.</p><pre>class CheckoutPage<br>    extends StatefulWidget {<br>  const CheckoutPage({<br>    super.key,<br>  });</pre><pre>  @override<br>  State&lt;CheckoutPage&gt; createState() =&gt;<br>      _CheckoutPageState();<br>}</pre><pre>class _CheckoutPageState<br>    extends State&lt;CheckoutPage&gt; {<br>  final _formKey =<br>      GlobalKey&lt;FormState&gt;();</pre><pre>  void _placeOrder() {<br>    if (_formKey.currentState<br>            ?.validate() ??<br>        false) {<br>      // Submit checkout data<br>    }<br>  }</pre><pre>  @override<br>  Widget build(BuildContext context) {<br>    return Column(<br>      children: [<br>        Form(<br>          key: _formKey,<br>          child: Column(<br>            children: [<br>              TextFormField(<br>                decoration:<br>                    const InputDecoration(<br>                  labelText: &#39;Full Name&#39;,<br>                ),<br>                validator: (value) {<br>                  if (value == null ||<br>                      value.trim().isEmpty) {<br>                    return &#39;Name is required&#39;;<br>                  }</pre><pre>                  return null;<br>                },<br>              ),<br>              TextFormField(<br>                decoration:<br>                    const InputDecoration(<br>                  labelText: &#39;Phone Number&#39;,<br>                ),<br>                validator: (value) {<br>                  if (value == null ||<br>                      value.trim().isEmpty) {<br>                    return &#39;Phone is required&#39;;<br>                  }</pre><pre>                  return null;<br>                },<br>              ),<br>            ],<br>          ),<br>        ),<br>        ElevatedButton(<br>          onPressed: _placeOrder,<br>          child: const Text(&#39;Place Order&#39;),<br>        ),<br>      ],<br>    );<br>  }<br>}</pre><p>Here, the GlobalKey&lt;FormState&gt; gives us access to the FormState associated with that Form.</p><p>When we call:</p><pre>_formKey.currentState?.validate();</pre><p>we’re interacting with the existing FormState from outside the Form&#39;s own build implementation.</p><p>GlobalKeys expose useful properties, including:</p><ul><li>currentState</li><li>currentContext</li><li>currentWidget</li></ul><p>These give us access to the associated mounted objects when they’re available.</p><p>But there’s much more to GlobalKeys than form validation.</p><h3>LocalKey vs GlobalKey</h3><p>The keys we’ve discussed so far — ValueKey, ObjectKey, and UniqueKey — all extend LocalKey.</p><p>Their identity is scoped to the children managed by a particular parent.</p><p>A GlobalKey, however, must be unique across the entire active widget hierarchy.</p><p>This allows Flutter to do something that LocalKeys cannot do by themselves.</p><p><strong>Move an existing Element between different parent locations while preserving its State.</strong></p><h3>Let’s build on our product preview</h3><p>Imagine our shopping cart supports a floating product preview.</p><p>When the user opens the cart, the preview appears in the main content area.</p><p>When the user switches into a compact layout, we want to move the existing preview into a floating panel without restarting its animation or discarding its State.</p><p>We could use a GlobalKey for the preview.</p><pre>class PreviewLayout extends StatefulWidget {<br>  const PreviewLayout({<br>    super.key,<br>  });</pre><pre>  @override<br>  State&lt;PreviewLayout&gt; createState() =&gt;<br>      _PreviewLayoutState();<br>}</pre><pre>class _PreviewLayoutState<br>    extends State&lt;PreviewLayout&gt; {<br>  final _previewKey =<br>      GlobalKey&lt;ProductPreviewState&gt;();</pre><pre>  bool _isFloating = false;</pre><pre>  @override<br>  Widget build(BuildContext context) {<br>    final preview = ProductPreview(<br>      key: _previewKey,<br>    );</pre><pre>    return Column(<br>      children: [<br>        SwitchListTile(<br>          title: const Text(<br>            &#39;Floating Preview&#39;,<br>          ),<br>          value: _isFloating,<br>          onChanged: (value) {<br>            setState(() {<br>              _isFloating = value;<br>            });<br>          },<br>        ),</pre><pre>        if (!_isFloating)<br>          Expanded(<br>            child: Container(<br>              alignment: Alignment.center,<br>              child: preview,<br>            ),<br>          ),</pre><pre>        if (_isFloating)<br>          Align(<br>            alignment: Alignment.bottomRight,<br>            child: SizedBox(<br>              width: 240,<br>              height: 180,<br>              child: preview,<br>            ),<br>          ),<br>      ],<br>    );<br>  }<br>}</pre><p>For this example, assume ProductPreview is a StatefulWidget with a publicly accessible ProductPreviewState type.</p><p>When the layout changes, the GlobalKey gives Flutter a way to identify the previously mounted Element and relocate it to its new parent.</p><p>Provided the widget is removed from its old location and inserted into the new location within the same animation frame, Flutter can preserve its existing State.</p><p>This behavior is called <strong>Element reparenting</strong>.</p><p>Without the GlobalKey, ordinary local reconciliation across separate parents would typically result in the old preview being removed and a new one being created.</p><h3>What happens internally?</h3><p>When Flutter moves a globally keyed subtree, the existing Element can be deactivated and then reactivated under its new parent.</p><p>Conceptually:</p><pre>Existing ProductPreview<br>          |<br>          v<br>Removed from old parent<br>          |<br>          v<br>State.deactivate()<br>          |<br>          v<br>Element becomes inactive<br>          |<br>          v<br>New parent receives widget<br>with the same GlobalKey<br>          |<br>          v<br>Existing Element reactivated<br>          |<br>          v<br>State.activate()<br>          |<br>          v<br>Same State, new location</pre><p>It’s a powerful mechanism.</p><p>But it isn’t free.</p><p>Reparenting a GlobalKey subtree can deactivate its descendants and cause widgets depending on inherited data to rebuild.</p><p>That’s why Flutter’s documentation specifically warns that GlobalKey reparenting is relatively expensive.</p><h3>Why not use GlobalKey everywhere?</h3><p>Because in most cases, we don’t need global identity.</p><p>Let’s say we have a shopping cart with 100 products.</p><p>Assigning a GlobalKey to every product would create unnecessary global identity management and make the widget architecture harder to reason about.</p><p>A regular ValueKey(product.id) would usually be sufficient.</p><p>GlobalKey also introduces a stricter uniqueness requirement.</p><p>Two simultaneously active widgets cannot share the same GlobalKey.</p><p>And similar to UniqueKey, recreating a GlobalKey inside build() is a common mistake.</p><p>For example:</p><pre>Widget build(BuildContext context) {<br>  final formKey =<br>      GlobalKey&lt;FormState&gt;();<br>      return Form(<br>      key: formKey,<br>      child: ...<br>      );<br>}</pre><p>Every rebuild creates a different GlobalKey.</p><p>This can cause the Form subtree to lose its existing identity and State.</p><p>Instead, we should generally create the GlobalKey once and keep it in the owning State object.</p><p>One final consideration: using GlobalKey.currentState to call methods on child widgets can introduce tight coupling between components.</p><p>It’s convenient, but convenience alone doesn’t make it a good architectural decision.</p><p>For more complex business logic, a dedicated controller or state-management solution is often more maintainable.</p><p>Use GlobalKeys when you need their specific capabilities.</p><h3>7. An Important Detail: Where You Place the Key Matters</h3><p>Now that we’ve explored all four key types, let’s discuss something that can catch even experienced Flutter developers off guard.</p><p>A key can be perfectly valid and still fail to preserve the State you expected.</p><p>Why?</p><p>Because keys participate in reconciliation at a specific level of the widget tree.</p><p>Consider our shopping cart again.</p><p>Suppose we wrap each item in Padding.</p><pre>Column(<br>  children: [<br>    Padding(<br>      padding:<br>          const EdgeInsets.all(8),<br>      child: CartItemTile(<br>        key: ValueKey(&#39;bag-101&#39;),<br>        product: bag,<br>      ),<br>    ),<br>    Padding(<br>      padding:<br>          const EdgeInsets.all(8),<br>      child: CartItemTile(<br>        key: ValueKey(&#39;wallet-102&#39;),<br>        product: wallet,<br>      ),<br>    ),<br>  ],<br>)</pre><p>At first glance, everything seems correct.</p><p>Both CartItemTile widgets have stable keys.</p><p>But there’s a problem.</p><p>The direct children of Column are not CartItemTile widgets.</p><p>They’re Padding widgets.</p><p>When the product order changes, Flutter first reconciles the Padding widgets within the Column.</p><p>Since those outer widgets are unkeyed and have the same runtime type, Flutter can reuse their existing Elements by position.</p><p>Then each Padding reconciles its own child.</p><p>At that point, the nested ValueKey doesn&#39;t match the previous child under that parent.</p><p>Because LocalKeys don’t provide global Element reparenting, Flutter cannot simply move the nested CartItemTile State from one Padding parent to another.</p><p>The result can be unexpected State loss.</p><h3>The correct approach</h3><p>Place the key on the outermost widget representing the movable item.</p><pre>Column(<br>  children: [<br>    Padding(<br>      key: const ValueKey(&#39;bag-101&#39;),<br>      padding:<br>          const EdgeInsets.all(8),<br>      child: CartItemTile(<br>        product: bag,<br>      ),<br>    ),<br>    Padding(<br>      key: const ValueKey(&#39;wallet-102&#39;),<br>      padding:<br>          const EdgeInsets.all(8),<br>      child: CartItemTile(<br>        product: wallet,<br>      ),<br>    ),<br>  ],<br>)</pre><p>Now the Column can match the correct keyed Padding subtrees.</p><p>Their descendants, including the stateful cart items, can move along with them.</p><p>Another option is KeyedSubtree:</p><pre>KeyedSubtree(<br>  key: ValueKey(product.id),<br>  child: Padding(<br>    padding:<br>        const EdgeInsets.all(8),<br>    child: CartItemTile(<br>      product: product,<br>    ),<br>  ),<br>)</pre><p>This becomes especially useful when the widget you need to identify isn’t the outermost component in a collection.</p><p>The key takeaway here is:</p><p><strong>A LocalKey doesn’t magically identify a widget anywhere in the tree. Its position within the parent-child structure matters.</strong></p><h3>8. What About ReorderableListView and Lazy Lists?</h3><p>Since we’ve been working with a shopping cart, let’s turn our example into a draggable list.</p><p>Flutter provides ReorderableListView for this.</p><p>One important requirement is that every item must have a key.</p><pre>ReorderableListView(<br>  onReorder: (oldIndex, newIndex) {<br>    setState(() {<br>      if (newIndex &gt; oldIndex) {<br>        newIndex -= 1;<br>      }<br>      final item =<br>          products.removeAt(oldIndex);<br>      products.insert(<br>        newIndex,<br>        item,<br>      );<br>    });<br>  },<br>  children: [<br>    for (final product in products)<br>      CartItemTile(<br>        key: ValueKey(product.id),<br>        product: product,<br>      ),<br>  ],<br>)<br></pre><p>This uses the traditional onReorder callback, where adjusting the destination index is necessary when moving an item downward.</p><p>Newer Flutter APIs also provide onReorderItem, which supplies an already-adjusted destination index.</p><p>The larger point remains the same.</p><p>Each child needs a stable identity so Flutter can maintain its association with the correct Element while items move.</p><h3>A less obvious issue with ListView.builder</h3><p>In large production applications, we usually use lazy lists rather than eagerly constructing every widget.</p><p>For example:</p><pre>ListView.builder(<br>  itemCount: products.length,<br>  itemBuilder: (context, index) {<br>    final product = products[index];<br>    return CartItemTile(<br>      key: ValueKey(product.id),<br>      product: product,<br>    );<br>  },<br>)</pre><p>This is a good starting point.</p><p>However, if the ordering of your data can change while the list is mounted, there is another important mechanism worth understanding.</p><p>findChildIndexCallback.</p><p>For builder-backed slivers, this callback helps Flutter locate the new index associated with a previously keyed child.</p><p>Without this information, reordering can cause a child to lose its association with an existing RenderObject and potentially its State.</p><p>A more complete approach would be:</p><pre>final indexById = {<br>  for (var i = 0; i &lt; products.length; i++)<br>    products[i].id: i,<br>};<br><br>ListView.builder(<br>  itemCount: products.length,<br>  findChildIndexCallback: (key) {<br>    if (key is ValueKey&lt;String&gt;) {<br>      return indexById[key.value];<br>    }<br>    return null;<br>  },<br>  itemBuilder: (context, index) {<br>    final product = products[index];<br>    return CartItemTile(<br>      key: ValueKey&lt;String&gt;(<br>        product.id,<br>      ),<br>      product: product,<br>    );<br>  },<br>)</pre><p>Here, we’re giving Flutter a way to map an existing keyed child to its new index.</p><p>This matters for feeds, sorted collections, search results, and other data-driven interfaces where items can change positions.</p><p>Keep in mind that this mechanism is not the same as keeping every item alive indefinitely.</p><p>Lazy-list lifecycle management, keep-alive behavior, and state restoration are separate concerns.</p><p>Keys help Flutter identify and reconcile children. They don’t guarantee that every off-screen or removed widget will retain its State forever.</p><h3>9. Do Keys Actually Improve Performance?</h3><p>This is where I think we need to be careful with how we describe keys.</p><p>A common statement is that keys optimize Flutter rebuilds.</p><p>That’s not entirely accurate.</p><p><strong>Keys are primarily about identity and correct Element reconciliation, not about preventing rebuilds.</strong></p><p>For example, if a widget has a stable ValueKey but receives new configuration data, its existing Element can still rebuild.</p><p>The key doesn’t stop that from happening.</p><p>What it does is help Flutter reuse the correct Element rather than associating State with the wrong widget or unnecessarily replacing an Element during structural changes.</p><p>That can prevent expensive recreation of controllers, animations, and other stateful resources.</p><p>But adding keys everywhere isn’t automatically a performance optimization.</p><p>In some cases, unnecessary keys can actually cause additional work.</p><p>Consider a UniqueKey generated inside build().</p><p>Instead of reusing the existing stateful subtree, Flutter is forced to treat the newly keyed widget as a different identity.</p><p>And GlobalKeys have their own reparenting costs and bookkeeping requirements.</p><p>So the right mental model isn’t:</p><p>“Keys make Flutter faster.”</p><p>It’s:</p><p>“Keys help Flutter understand which UI elements represent the same logical entities across changes.”</p><p>Correct identity management can improve application behavior and avoid unnecessary work, but it isn’t a universal rebuild optimization strategy.</p><h3>10. Putting It All Together: Which Key Should You Actually Use?</h3><p>Let’s revisit everything we’ve built.</p><p>We started with a simple shopping cart.</p><p>Then we gradually introduced sorting, custom product drafts, preview resets, checkout validation, and UI relocation.</p><p>Each problem required a different kind of identity.</p><p>KeyIdentity mechanismOur exampleValueKeyValue equality (==)Preserve cart item State when sorting or reorderingObjectKeyObject identity (identical)Track individual in-memory customization draftsUniqueKeyUnique key instanceReset a product preview and create fresh StateGlobalKeyGlobal key identityValidate checkout forms or reparent a stateful preview</p><p>There is also a fifth option that developers sometimes overlook.</p><p><strong>Not using a key at all.</strong></p><p>Not every widget needs a key.</p><p>If your UI structure is stable, the widget doesn’t represent a movable logical entity, and normal type-and-position matching gives you the behavior you want, an explicit key may be unnecessary.</p><p>Adding keys everywhere can make the code harder to follow without providing a meaningful benefit.</p><p>The important part is understanding when identity matters.</p><h3>11. A Few Mistakes Worth Avoiding</h3><p>Before wrapping up, there are a few recurring mistakes I’d particularly watch for in code reviews.</p><h3>Using an index as identity for dynamic content</h3><pre>ValueKey(index)</pre><p>This can cause State to follow positions rather than logical items.</p><p>Use stable domain identifiers when items can move.</p><h3>Creating UniqueKeys during every build</h3><pre>Widget build(BuildContext context) {<br>  return MyWidget(<br>    key: UniqueKey(),<br>  );<br>}</pre><p>This introduces a new identity every time the parent rebuilds.</p><p>Only generate a new key when a new identity is actually intended.</p><h3>Using ObjectKey with frequently recreated models</h3><p>If your architecture reconstructs immutable model instances after every state update, ObjectKey may not preserve identity the way you expect.</p><p>Use a stable ValueKey when logical identity is represented by an ID.</p><h3>Using GlobalKey as a substitute for architecture</h3><p>Accessing child State directly can be useful, but using it for all communication between widgets creates unnecessary coupling.</p><p>Prefer explicit data flow and application-level state management for business logic.</p><h3>Assuming keys preserve State forever</h3><p>Keys do not provide persistence on their own.</p><p>If a widget is permanently removed and its State is disposed, inserting a new widget with the same LocalKey later does not resurrect the old State.</p><p>If you need data to survive widget removal, navigation, application restarts, or process termination, that requires appropriate state ownership or persistence mechanisms.</p><h3>Final Thoughts</h3><p>Flutter keys are easy to overlook because most applications work perfectly well without us thinking about them.</p><p>Until one day, a list gets reordered, a text field starts showing the wrong value, an animation unexpectedly restarts, or a stateful component loses its internal State after being moved.</p><p>And then suddenly, keys become very important.</p><p>What helped me understand them more clearly is thinking less about the key classes themselves and more about how Flutter identifies and reuses Elements.</p><p>Because that’s really what keys are about.</p><p>ValueKey tells Flutter that two widget configurations represent the same identity when their key values are equal.</p><p>ObjectKey ties identity to a specific object instance.</p><p>UniqueKey gives us a way to deliberately introduce a new identity.</p><p>And GlobalKey extends identity beyond a single parent, allowing State access and cross-parent subtree reparenting.</p><p>It’s not simply about knowing which key to use.</p><p>It’s about understanding <strong>why Flutter needs that identity in the first place, what happens when identity changes, and how that affects the lifecycle of your UI.</strong></p><h3>Try It Yourself: Flutter Keys Playground</h3><p>Want to see how these keys actually behave in practice?</p><p>I&#39;ve put together a small <strong>Flutter sandbox application</strong> on GitHub where you can experiment with ValueKey, ObjectKey, UniqueKey, and GlobalKey. It includes interactive examples that demonstrate how Flutter preserves, resets, and manages widget State when elements are reordered, rebuilt, or moved around the widget tree.</p><p>Feel free to clone the repository, play around with the examples, and explore what&#39;s happening behind the scenes. Sometimes, the best way to understand a concept is to break things and see how Flutter handles them.</p><p><strong>GitHub Repository: </strong>Flutter Keys Playground</p><h3>References and Further Reading</h3><ul><li><a href="https://docs.flutter.dev/resources/inside-flutter">Flutter — Inside Flutter</a></li><li><a href="https://api.flutter.dev/flutter/foundation/Key-class.html">Flutter API — Key</a></li><li><a href="https://api.flutter.dev/flutter/widgets/Widget/canUpdate.html">Flutter API — Widget.canUpdate</a></li><li><a href="https://api.flutter.dev/flutter/foundation/ValueKey-class.html">Flutter API — ValueKey</a></li><li><a href="https://api.flutter.dev/flutter/widgets/ObjectKey-class.html">Flutter API — ObjectKey</a></li><li><a href="https://api.flutter.dev/flutter/foundation/UniqueKey-class.html">Flutter API — UniqueKey</a></li><li><a href="https://api.flutter.dev/flutter/widgets/GlobalKey-class.html">Flutter API — GlobalKey</a></li><li><a href="https://api.flutter.dev/flutter/material/ReorderableListView-class.html">Flutter API — ReorderableListView</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c59b94fd4bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an Immich TV App in a Week: Because I wanted to see Photos on the Big Screen]]></title>
            <link>https://medium.com/@afridi.khondakar/building-an-immich-tv-app-in-a-week-because-i-wanted-to-see-photos-on-the-big-screen-0c75ce545ad2?source=rss-3ee2b01f5cab------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c75ce545ad2</guid>
            <category><![CDATA[immich]]></category>
            <category><![CDATA[self-hosting]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Khondakar Afridi]]></dc:creator>
            <pubDate>Thu, 14 May 2026 07:43:20 GMT</pubDate>
            <atom:updated>2026-05-14T07:43:20.955Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KqDv3mZsVbq_MYktmz7iPg.png" /></figure><p>For almost a year now, I have been using <strong>Immich</strong> to host my personal photo and video library.</p><p>At this point, my library is well over <strong>300GB+</strong> of images and videos. Like many people, I originally used Google Photos because it was convenient, polished, and “just worked.” But over time, the pricing model started to feel increasingly hard to justify, especially for a growing media library.</p><p>So I made the jump. I ditched Google Photos and moved to Immich. And honestly? I loved it.</p><p>Immich gave me exactly what I wanted, control over my media, a great user experience, solid mobile apps, and the freedom of self-hosting without feeling like I had downgraded from a commercial product. The experience was good enough that I eventually introduced it to my family.</p><p>That was the real test. And Immich passed. But there was one missing piece.</p><h3>The TV Problem</h3><p>Once my family started using Immich, it became obvious that we wanted to enjoy our photos and videos on the TV, on the bigger screen.</p><p>Family trips. Old memories. Random funny videos. Photos from weddings, birthdays, and vacations, what not. These are the kinds of things that are just better on a large screen, especially when multiple people are sitting together.</p><p>Unfortunately, there was no Immich TV app that fit what I wanted. There were a few options and workarounds, but none of them felt truly designed for a TV-first experience. The main issue was remote control usability. A TV app is not just a mobile app stretched onto a bigger display or a desktop for what matters. It has a completely different interaction model.</p><p>On a TV, everything needs to be navigable with a remote. And you need to account for focus for almost all the activites. No touch gestures. No mouse pointer. No tiny buttons. No awkward focus traps. The entire UI needs to be built around directional navigation, focus states, large visual targets, and predictable behavior.</p><p>So I decided to build one.</p><h3>Starting the Project</h3><p>This started as one of those “I’ll just try something quickly” projects.</p><p>The goal was straight and simple: Build an Immich client for TV that is actually comfortable to use with a remote. I chose <strong>Flutter</strong> for the frontend because I already enjoy working with it, and it gives a lot of flexibility when building custom UIs across different platforms. For state management, I used <strong>BLoC</strong>, which helped keep the app logic predictable and structured as the project grew.</p><p>The core focus from the beginning was not just “can I show photos and videos from Immich?” It was: Can every part of this app be controlled comfortably from a TV remote? That shaped almost every decision.</p><h3>Designing for Remote-First Navigation</h3><p>One thing I quickly realized is that TV UI development forces you to think differently. On mobile, the user can directly tap whatever they want. On desktop, they can point and click. But on TV, users move through the interface one focusable element at a time. That means focus management becomes a first-class concern.</p><p>Every button, image, album, video, menu item, and dialog needs to have a clear focus state. The user should always know where they are. Pressing left, right, up, or down should feel natural. Pressing back should behave predictably.</p><p>I spent a good amount of time making sure components were accessible and controllable from the remote. The app needed to feel like it belonged on a TV, not like a hacked-together port of a mobile interface.</p><p>Some of the things I focused on:</p><ul><li>Large, readable UI elements</li><li>Clear focus indicators</li><li>Smooth grid navigation</li><li>Remote-friendly menus</li><li>Predictable back navigation</li><li>Simple browsing of albums and assets</li><li>Comfortable photo and video viewing from the couch</li></ul><p>The goal was not to build the most feature-complete Immich client immediately. The goal was to build something everyone could use without anyone explaining how to use it.</p><p>That is usually the best usability test.</p><h3>Vibe Coding, Agentic Coding, and Moving Fast</h3><p>The most surprising part of this project was how fast it came together. Most of the app was built through a mix of <strong>vibe coding</strong> and <strong>agentic coding</strong>. I had a clear idea of what I wanted, and AI-assisted development made it possible to move from idea to working implementation extremely quickly.</p><p>The actual development time was probably around <strong>one to two days</strong>.</p><p>Of course, that does not mean everything was magically perfect. There were still bugs, UI issues (Oh god, the UI issues), refactors, and platform-specific details to handle. But the speed at which I could build, test, iterate, and polish was honestly kind of WILD.</p><p>Development in 2026 feels very different and FUN.</p><p>You can have an idea, build a real app, test it, improve it, and publish it within a week. Not a prototype. Not just a demo. A full usable app.</p><p>That still feels crazy to me.</p><h3>Self-Hosting Still Feels Empowering</h3><p>This project also reminded me why I like self-hosting. There is something deeply satisfying about owning the full flow: storing your own data, running your own services, and building your own clients when something is missing.</p><p>Immich already solved the hardest part for me: a great self-hosted photo and video platform.</p><p>I just needed a better way to bring that experience to the TV.</p><p>And because Immich exists, because Flutter exists, and because AI-assisted development has become so powerful, building that missing piece was actually achievable in a few days.</p><p>What a time to be a developer!</p><h3>Thoughts</h3><p>This project started from a simple frustration:</p><p>I wanted to use Immich on my TV, but the available options were not remote-friendly enough.</p><p>So I built my own.</p><p>It was fun, fast, and surprisingly practical. I got to work with Flutter, structure the app with BLoC, think deeply about TV-first UX, and use modern AI-assisted workflows to move at a pace that would have felt unrealistic just a few years ago.</p><p>Development in 2026 is fun.</p><p>You can create, build, and publish apps within a week.</p><p>And sometimes, that app starts with nothing more than wanting to see your damn photos on the bigger screen. :)</p><p>Checkout the REPOSITORY: <a href="https://github.com/WorkWithAfridi/immich-tv">https://github.com/WorkWithAfridi/immich-tv</a><br>Checkout the App on Google Play: <a href="https://play.google.com/store/apps/details?id=com.workwithafridi.immichtv">https://play.google.com/store/apps/details?id=com.workwithafridi.immichtv</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c75ce545ad2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How We Cut Our App’s Upload Time by ⅓ (Without Touching the Backend) Using A Simple Stupid Hack]]></title>
            <link>https://medium.com/@afridi.khondakar/how-we-cut-our-apps-upload-time-by-%E2%85%93-without-touching-the-backend-using-a-simple-stupid-hack-9cc8e8f9381f?source=rss-3ee2b01f5cab------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cc8e8f9381f</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Khondakar Afridi]]></dc:creator>
            <pubDate>Wed, 21 Jan 2026 04:27:00 GMT</pubDate>
            <atom:updated>2026-01-21T04:27:00.473Z</atom:updated>
            <content:encoded><![CDATA[<p>Performance issues have a funny way of announcing themselves. Ours showed up when users tried to upload multiple photos and videos and the app responded with the digital equivalent of “yeah… give me a minute.”</p><p>Actually, make that several minutes.</p><p>Uploads were technically working, but they were slow enough to feel broken. After watching files crawl through the pipeline one by one, it became obvious: the app was not slow, our upload strategy was.</p><p>This article breaks down how we optimized uploads using a simple queuing system with controlled concurrency, how the code works, and what further improvements (like isolates) could unlock even more performance. This single change cut our upload time by roughly <strong>one third</strong>, and made the app feel dramatically faster.</p><h3>The Original Bottleneck: Sequential Uploads</h3><p>The original mental model was simple and very common:</p><pre>for each file:<br>  upload file<br>  wait until done</pre><p>This approach has a few problems:</p><ul><li>The network sits idle between uploads</li><li>Large files block smaller ones</li><li>The UI has no sense of momentum</li><li>Users think the app is slow</li></ul><p>Modern phones, modern networks, and modern backends can handle more than one upload at a time. We just were not letting them.</p><h3>The Shift in Thinking: Uploads Are a Queue, Not a Loop</h3><p>Instead of thinking in terms of a loop, we reframed uploads as a <strong>queue of work</strong>:</p><ul><li>Files go into a queue</li><li>A fixed number of workers pull from that queue</li><li>Each worker uploads independently</li><li>Progress is tracked globally</li></ul><p>This gives us parallelism without chaos.</p><h3>The Upload Queue Cubit (High-Level Structure)</h3><p>At the top level, we have a Cubit responsible for orchestrating everything:</p><pre>class UploadQueueCubit extends Cubit&lt;UploadQueueState&gt; {<br>  final PhotostreamService _photostreamService;<br>  UploadQueueCubit(this._photostreamService)<br>      : super(UploadQueueInitial());<br>}</pre><p>This keeps upload logic out of the UI and makes progress easy to observe.</p><h3>Step 1: Cap Concurrency (This Is Critical)</h3><p>Unlimited concurrency is a great way to melt phones and anger servers. We hard-cap the number of simultaneous uploads:</p><pre>static const int _maxConcurrentUploads = 3;</pre><p>Three turned out to be the sweet spot for us (Mind you, these are HiRes large files). Enough parallelism to feel fast, not enough to overwhelm the device. Maybe in Part II we can try implementing a dynamic system to calculate the concurrent uploads. 🤔</p><h3>Step 2: Initialize State and the Queue</h3><p>When uploads begin, we reset state and create a working queue:</p><pre>final totalFileCount = mediaFiles.length;<br>int uploadedFileCount = 0;<br>int activeUploads = 0;<br>final queue = List&lt;File&gt;.from(mediaFiles);</pre><p>Why copy the list?</p><p>Because this list becomes mutable shared state. Workers will remove items as they go.</p><h3>Step 3: Emit Meaningful Progress</h3><p>Instead of vague “loading” indicators, we track real metrics:</p><pre>void emitProgress() {<br>  emit(<br>    UploadQueueInProgress(<br>      totalFileCount: totalFileCount,<br>      uploadedFileCount: uploadedFileCount,<br>      activeUploads: activeUploads,<br>    ),<br>  );<br>}</pre><p>This allows the UI to show:</p><ul><li>How many files are done</li><li>How many are currently uploading</li><li>How many are left</li></ul><p>Perceived performance matters just as much as actual speed.</p><h3>Step 4: The Worker Pattern (Where the Magic Happens)</h3><p>Each worker is an async function that keeps pulling files until the queue is empty:</p><pre>Future&lt;void&gt; worker() async {<br>  while (queue.isNotEmpty) {<br>    final file = queue.removeAt(0);<br>    activeUploads++;<br>    emitProgress();<br>    try {<br>          await _photostreamService.uploadMedia(<br>            path: file.path,<br>            eventUid: eventUid,<br>          );<br>          uploadedFileCount++;<br>        } finally {<br>          activeUploads--;<br>          emitProgress();<br>        }<br>      }<br>}</pre><p>Key ideas here:</p><ul><li>Workers are independent</li><li>Failures do not crash the entire queue</li><li>Progress is updated before and after each upload</li><li>No worker ever blocks another</li></ul><h3>Step 5: Spawn a Fixed Number of Workers</h3><p>Instead of one long loop, we spawn workers up front:</p><pre>final List&lt;Future&lt;void&gt;&gt; workers = [];</pre><pre>for (int i = 0; i &lt; _maxConcurrentUploads; i++) {<br>  workers.add(worker());<br>}</pre><pre>await Future.wait(workers);<br>emit(UploadQueueSuccess());</pre><p>This pattern is simple, readable, and extremely effective.</p><p>When all workers finish, the queue is empty and uploads are complete.</p><h3>The Result: ⅓ Faster Uploads, Instantly</h3><p>After rolling this out:</p><ul><li>Total upload time dropped by about <strong>33%</strong></li><li>The UI felt alive instead of blocked</li><li>Large batches no longer felt intimidating</li><li>User complaints disappeared almost overnight</li></ul><p>No backend changes. No infrastructure changes. Just better client-side orchestration.</p><h3>Can This Be Improved Further? Absolutely. (Maybe a story for another day) :)</h3><h3>1. Failed Upload Retry Queues</h3><p>Right now, failed uploads are ignored. A retry queue with exponential backoff would make this even more robust.</p><h3>2. Priority Queues</h3><p>Small thumbnails could upload before large videos to improve perceived speed even more.</p><h3>3. Dart Isolates (When They Make Sense)</h3><p>Network calls themselves do not need isolates, but , multi threading becomes useful if you add:</p><ul><li>Image compression</li><li>Video transcoding</li><li>Encryption</li><li>Metadata extraction</li></ul><p>Those CPU-heavy tasks can be offloaded to isolates <strong>before</strong> files enter the upload queue, keeping the UI thread smooth.</p><p>A future pipeline might look like:</p><pre>Isolate → preprocess file<br>        → enqueue for upload<br>        → concurrent workers upload</pre><h3>Final Takeaway</h3><p>Performance optimizations do not always come from exotic tricks. Sometimes, they come from asking a basic question: “Why is the system doing this one at a time?”</p><p>Queues, worker pools, and controlled concurrency are foundational patterns that scale surprisingly far. In our case, this small architectural shift made the app feel faster, more reliable, and more professional.</p><p>And honestly, watching three uploads fly at once instead of one crawling along is just more fun.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cc8e8f9381f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing Reliable Integration Tests in Flutter with Patrol]]></title>
            <link>https://medium.com/@afridi.khondakar/writing-reliable-integration-tests-in-flutter-with-patrol-b1a88a56d96d?source=rss-3ee2b01f5cab------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1a88a56d96d</guid>
            <category><![CDATA[integration-testing]]></category>
            <category><![CDATA[ui-testing]]></category>
            <category><![CDATA[patrol]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Khondakar Afridi]]></dc:creator>
            <pubDate>Sun, 09 Mar 2025 06:01:58 GMT</pubDate>
            <atom:updated>2025-03-09T06:03:11.110Z</atom:updated>
            <content:encoded><![CDATA[<p>As Flutter developers, writing efficient, reliable tests is a crucial part of our development process. It helps ensure our app’s functionality, stability, and user experience remain intact as we make changes and add new features. One of the most powerful tools in the Flutter testing ecosystem is Patrol.</p><p>In this post, we’ll explore why you should consider using Patrol for your Flutter integration tests, what makes it special, and how to use it effectively. We’ll walk through a complete example of a test using Patrol to simulate a real user flow in a Flutter application, from sign-in to password reset, and show how it can make your testing process more efficient and reliable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RdpoWP9kGPuh5Dt1hjdaTg.jpeg" /></figure><h4>What is Patrol?</h4><p>Patrol is an open-source testing library for Flutter designed for integration testing. It helps you write tests that simulate user interactions in a way that mimics how a real user would interact with your application. Unlike unit tests or widget tests, which focus on individual widgets or logic, integration tests allow you to test your app’s complete user flow, including navigation, UI interactions, and state changes.</p><p>Patrol simplifies integration testing in Flutter by offering powerful utilities to interact with UI elements, manage app states, and handle transitions — even native ones! It’s built on top of Flutter’s integration_test package but adds more abstraction and functionality for a smoother and more readable test-writing experience.</p><h4><strong>Why Use Patrol?</strong></h4><h4><strong>1. Complete User Flow Testing</strong></h4><p>Integration tests with Patrol allow you to test an entire user flow, ensuring all components work together seamlessly. You can simulate real-world scenarios like logging in, filling out forms, toggling native features like wifi, gps, etc. and interacting with various screens.</p><h4><strong>2. Built for Flutter</strong></h4><p>Patrol was specifically built to make integration testing in Flutter easier and more powerful. It integrates tightly with Flutter’s test framework and provides easy-to-use functions to control app navigation, widget state, and UI interactions.</p><h4><strong>3. Better Debugging</strong></h4><p>Patrol provides excellent error messages and logs that make debugging easier. It offers clear information about which widgets failed to load, where an interaction failed, and what the expected state was, making troubleshooting much simpler.</p><h4><strong>4. Simplicity and Readability</strong></h4><p>Patrol provides an intuitive API that makes writing tests more natural and readable. You don’t need to worry about managing async states, waiting for transitions, or dealing with complex widget trees manually — Patrol handles much of it for you.</p><h4><strong>5. Cross-Platform Testing</strong></h4><p>Patrol supports both Android and iOS, so you can write your tests once and run them on both platforms with no modifications. This ensures your app works correctly across different devices and OS versions.</p><h4><strong>6. No External Dependencies</strong></h4><p>Patrol provides all the utilities you need in one package. It doesn’t require external plugins or packages for basic functionality, making it a simple solution out of the box.</p><h4><strong>What makes Patrol standout?</strong></h4><p>Patrol is unique in that it is designed to address the pain points of integration testing in Flutter. Here’s what makes it stand out:</p><h4><strong>1. Simplified Navigation Handling</strong></h4><p>With Patrol, you don’t have to manually manage widget navigation or transitions. It automatically waits for your app to settle and ensures actions are performed in the correct order. This reduces flaky tests that result from race conditions or missed transitions.</p><h4><strong>2. Built-in Widget Interaction</strong></h4><p>Patrol includes built-in functions for interacting with widgets like buttons, text fields, and custom elements. For example, you can easily simulate text input, button clicks, and form submissions, all while handling app state automatically.</p><h4><strong>3. Test Stability</strong></h4><p>One common issue with integration tests is flakiness. Patrol mitigates this by offering functions like await $.native.pressBack();, which lets us easily navigate between screens or view.</p><h4><strong>4. Readability</strong></h4><p>The API is designed to be intuitive and readable. Writing integration tests with Patrol feels much like writing standard Flutter code, making it easy for developers to write and maintain tests.</p><h4><strong>Implementing Patrol in a Real-World Example</strong></h4><p>To further illustrate Patrol’s capabilities, let’s integrate it into a basic Flutter app with a Splash Screen, Authentication (Sign In, Sign Up, Forgot Password), Form Validations, and a Home Page. I will be adding inline comment to document the code, instead of explaining it in plain text. :)</p><p><em>Please be advised, that I wont be going through the installation process, I believe Patrol has a very straight forward setup process, and their documentation is well structured to get the job done!</em></p><p>Patrol: <a href="https://patrol.leancode.co/documentation">https://patrol.leancode.co/documentation</a></p><pre>import &#39;package:f_patrol/keys/app_keys.dart&#39;;<br>import &#39;package:f_patrol/main.dart&#39;;<br>import &#39;package:flutter_test/flutter_test.dart&#39;;<br>import &#39;package:patrol/patrol.dart&#39;;<br><br>// run test using -&gt;  patrol test -t integration_test/example_test.dart;<br><br>void main() {<br>  patrolTest(&#39;Complete app flow - integration test&#39;, ($) async {<br>    // Pump the app widget and wait for it to settle<br>    await $.pumpWidgetAndSettle(FPatrolApp());<br><br>    // Verify that the Splash Screen is displayed and wait for navigation to complete<br>    expect($(&#39;Splash Screen&#39;), findsOne);<br>    <br>    await Future.delayed(<br>      const Duration(seconds: 3),<br>    ); // Wait for auto-navigation // Or we could use await $(&#39;Sign In&#39;).waitUntilVisible(); to wait until the Sign In screen is visible<br><br>    // Ensure that the app has settled after the splash screen<br>    await $.pumpAndSettle();<br><br>    // Verify we are on the Sign In Screen by checking the appearance of &#39;Sign In&#39; elements<br>    expect($(&#39;Sign In&#39;), findsExactly(2)); // 1-&gt; Appbar, 2-&gt; SignIn button<br><br>    // Test the Sign In functionality with invalid credentials<br>    await $(appKeys.signInView.email).enterText(&#39;invalid_email&#39;);<br>    await $(appKeys.signInView.password).enterText(&#39;123&#39;);<br>    await $(appKeys.signInView.signin).tap();<br>    // Check for validation messages on the Sign In form<br>    expect($(&#39;Enter a valid email&#39;), findsOne);<br>    expect($(&#39;Password too short&#39;), findsOne);<br><br>    // Test Sign In with valid credentials<br>    await $(appKeys.signInView.email).enterText(&#39;user@example.com&#39;);<br>    await $(appKeys.signInView.password).enterText(&#39;securePassword123&#39;);<br>    await $(appKeys.signInView.signin).tap();<br>    // Wait for the navigation to the Home Screen to complete<br>    await $.pumpAndSettle();<br><br>    // Verify that we are on the Home Screen by checking for &#39;Welcome Home&#39;<br>    expect($(&#39;Welcome Home&#39;), findsOne);<br><br>    // Navigate to the Sign Up Screen by pressing the back button and tapping the Sign Up button<br>    await $.native.pressBack();<br>    await $(appKeys.signInView.signup).tap();<br>    await $.pumpAndSettle();<br>    // Verify the presence of &#39;Sign Up&#39; elements on the screen<br>    expect($(&#39;Sign Up&#39;), findsExactly(2)); // 1-&gt; Appbar, 2-&gt; SignUp button<br><br>    // Fill out and submit the Sign Up form<br>    await $(appKeys.signUpView.name).enterText(&#39;New User&#39;);<br>    await $(appKeys.signUpView.email).enterText(&#39;newuser@example.com&#39;);<br>    await $(appKeys.signUpView.password).enterText(&#39;newPassword123&#39;);<br>    await $(appKeys.signUpView.signup).tap();<br>    await $.pumpAndSettle();<br><br>    // After successful sign-up, verify that the Home Screen is displayed again<br>    expect($(&#39;Welcome Home&#39;), findsOne);<br><br>    // Navigate to the Forgot Password Screen<br>    await $.native.pressBack();<br>    await $(appKeys.signInView.forgotPassword).tap();<br>    await $.pumpAndSettle();<br>    // Verify the Forgot Password screen is displayed<br>    expect($(&#39;Forgot Password&#39;), findsOne);<br><br>    // Enter email to reset password and submit the request<br>    await $(appKeys.forgotPasswordView.email).enterText(&#39;user@example.com&#39;);<br>    await $(appKeys.forgotPasswordView.submit).tap();<br>    await $.pumpAndSettle();<br><br>    // On the Reset Password Screen, enter new password and confirm it<br>    await $(appKeys.setPasswordView.passwordOne).enterText(&#39;newSecurePass123&#39;);<br>    await $(appKeys.setPasswordView.passwordTwo).enterText(&#39;newSecurePass123&#39;);<br>    await $(appKeys.setPasswordView.resetPassword).tap();<br><br>    // After password reset, verify that the Home Screen is displayed once again<br>    expect($(&#39;Welcome Home&#39;), findsOne);<br>  });<br>}</pre><p>Watch the test run in real time: <a href="https://youtu.be/j5B8vaxLYG8">https://youtu.be/j5B8vaxLYG8</a></p><p><strong>Key Takeaways:</strong></p><ul><li>App Flow Simulation: The test covers a complete user journey — from signing in with invalid credentials to resetting a password and verifying navigation between screens.</li><li>Widget Interaction: We use Patrol’s built-in functions to interact with the app’s UI elements (e.g., buttons, text fields).</li><li>Async Handling: Patrol automatically manages async operations, ensuring the app’s state is settled before making assertions, reducing flakiness.</li></ul><h4><strong>Some Patrol Tips &amp; Tricks :D</strong></h4><p>Patrol allows you to interact with native system elements that standard Flutter tests struggle with. You can perform actions like pressing hardware buttons, granting permissions, or interacting with system alerts. If your app depends on native device permissions (camera, location, notifications), you can automate these interactions without manual intervention.</p><pre>await $.native.pressBack(); // Simulates the Android/iOS back button  <br>await $.native.enableWifi(); // Enables Wi-Fi (useful for network-dependent tests)<br>await $.native.openApp(&#39;com.example.myapp&#39;); // Opens another app during tests</pre><p>Patrol Handles Delays &amp; Transitions GracefullyMany integration tests fail because the app hasn’t fully loaded or a widget is still animating. Patrol provides a robust way to ensure UI stability before proceeding. You can call await $.pumpAndSettle(); after every major navigation or interaction to reduce test flakiness.</p><pre>await $.pumpAndSettle(); // Waits until the UI has fully settled before continuing</pre><p>Wait for Widgets Dynamically Instead of Using Fixed Delays. Instead of using Future.delayed(Duration(seconds: 3)), which can make tests slow and unreliable, use Patrol’s dynamic wait functions to check for elements before interacting.</p><pre>await $(&#39;Sign In&#39;).waitUntilVisible(); // Waits dynamically for the Sign In screen</pre><p>Now you might be asking: Why it’s better ? Well, it makes tests more efficient by only waiting as long as necessary instead of an arbitrary time delay.</p><p>Test Both Android &amp; iOS Without Code Changes. Patrol’s API works seamlessly on both platforms, so you don’t need separate test scripts. Just run:</p><pre>patrol test --target=integration_test/app_test.dart --device=android<br>patrol test --target=integration_test/app_test.dart --device=ios</pre><p>You can run tests in real devices &amp; emulators at the same time using:</p><pre>patrol test --device=all</pre><p>Use findsExactly(n) for Precise Assertions. If your app has multiple widgets with the same text, standard findsOne may not work as expected. Instead, use:</p><pre>expect($(&#39;Sign In&#39;), findsExactly(2)); // Ensures two instances of &#39;Sign In&#39; exist  </pre><p>When to use? This is useful when testing buttons, headers, and form labels that appear multiple times in a single screen, for example in my example project, I searched for the “Sign In” text, for 2 exact matches.</p><p>Handle App Restarts &amp; Backgrounding. Patrol lets you test real-world scenarios like app restarts, minimizing, and reopening, which helps catch issues where the app loses state when reopened.</p><pre>await $.native.pressHome(); // Minimizes the app  <br>await Future.delayed(Duration(seconds: 5)); // Simulate user waiting  <br>await $.native.openApp(&#39;com.example.myapp&#39;); // Reopens the app</pre><p>Automate Login Flows with SetUp Functions. If multiple tests require logging in first, avoid repeating login steps by using a setup function.</p><pre>Future&lt;void&gt; login(PatrolTester $) async {<br>  await $(appKeys.signInView.email).enterText(&#39;user@example.com&#39;);<br>  await $(appKeys.signInView.password).enterText(&#39;securePassword123&#39;);<br>  await $(appKeys.signInView.signin).tap();<br>  await $.pumpAndSettle();<br>}</pre><h4><strong>Now lets go over some debugging guidelines and best practices.</strong></h4><h4><strong>Use Descriptive Logs for Better Debugging</strong></h4><p>Always log actions in your tests to track progress and pinpoint failures easily. Add logs before major actions (navigation, form submissions) to see where failures occur.</p><pre>print(&#39;🔍 Navigating to Sign In Screen...&#39;);<br>await $(appKeys.signInView.email).enterText(&#39;invalid_email&#39;);</pre><h4><strong>Handle Widget Not Found Errors</strong></h4><p><strong>Error: </strong>Expected: exactly one matching node in the widget tree</p><p><strong>Solution:</strong></p><ul><li>Ensure the key used in the test matches the widget’s key in your app.</li><li>If the widget is expected after a delay, use dynamic waits instead of Future.delayed().</li></ul><p>Doing this will eliminate flakiness caused by timing issues.</p><h4><strong>Debug Flaky Tests with Screenshots</strong></h4><p>If a test fails, you can capture a screenshot at the point of failure to analyze the UI state. This helps in identifying missing widgets or incorrect navigation states.</p><pre>await $.native.takeScreenshot(&#39;failed-test-signin&#39;);</pre><h4><strong>Run Tests in Debug Mode for More Insights</strong></h4><p>Always try running Patrol tests with detailed logs by enabling verbose mode. It provides more details on failed assertions, missing widgets, and navigation issues.</p><pre>patrol test --verbose</pre><h4>Mock Network Calls for More Predictable Tests</h4><p>If your app depends on APIs, ensure tests don’t break due to network failures:</p><ul><li>Use mock data instead of real API calls.</li><li>If using Firebase or external services, disable network dependency during tests.</li></ul><h4>Best Practices for Stable &amp; Maintainable Patrol Tests</h4><h4>Keep Test Names Descriptive</h4><pre>// Instead of <br>patrolTest(&#39;Login test&#39;, ($) async { ... });</pre><pre>// Use<br>patrolTest(&#39;User should see error when entering invalid login credentials&#39;, ($) async { ... });</pre><h4>Avoid Hardcoded Delays</h4><pre>// Instead of <br>await Future.delayed(Duration(seconds: 3));</pre><pre>// Use<br>await $(&#39;Sign In&#39;).waitUntilVisible();</pre><h4>Group Similar Tests Together</h4><p>Organise tests into categories to improve maintainability:</p><pre>group(&#39;Authentication Tests&#39;, () {<br>  patrolTest(&#39;User can sign in&#39;, ($) async { ... });<br>  patrolTest(&#39;User sees error for invalid email&#39;, ($) async { ... });<br>});</pre><h4>Clean Up State Before Each Test</h4><p>Reset app state before every test to avoid cross-test contamination:</p><pre>setUp(() async {<br>  await $.native.restartApp();<br>});</pre><h4>Final Takeaways</h4><p>Patrol is a powerful tool that makes Flutter integration testing more reliable, readable, and user-friendly. By integrating it into your app’s authentication and navigation flows, you ensure a seamless experience for users while catching potential issues early in development. Implement Patrol in your testing workflow today to enhance app quality and stability!</p><p><strong>Explore the source code at:</strong> <a href="https://github.com/WorkWithAfridi/F-Patrol.git">https://github.com/WorkWithAfridi/F-Patrol.git</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1a88a56d96d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Native Bridging in Flutter: A Deep Dive]]></title>
            <link>https://medium.com/@afridi.khondakar/mastering-native-bridging-in-flutter-a-deep-dive-e07a11dc3099?source=rss-3ee2b01f5cab------2</link>
            <guid isPermaLink="false">https://medium.com/p/e07a11dc3099</guid>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Khondakar Afridi]]></dc:creator>
            <pubDate>Tue, 25 Feb 2025 11:13:38 GMT</pubDate>
            <atom:updated>2025-02-25T11:13:38.941Z</atom:updated>
            <content:encoded><![CDATA[<p>Flutter is powerful, but there are times when we need to interact with native platform features that are not available in Dart. This is where <strong>Method Channels</strong> come into play. Native Bridging allows Flutter apps to communicate with native Android (Kotlin/Java) and iOS (Swift/Objective-C) code seamlessly.</p><p>In this article, we will:</p><ul><li>Understand what Native Bridging is.</li><li>Set up a <strong>Method Channel</strong> in Flutter.</li><li>Implement platform-specific functionality in <strong>Android</strong> and <strong>iOS</strong>.</li><li>Handle <strong>“complex” native operations</strong>.</li><li>Manage <strong>bi-directional communication</strong>.</li><li>Debug <strong>common issues</strong>.</li></ul><p>Let’s dive in!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WAghyt-N6Yc9f_i3uxxmAQ.png" /></figure><h3>What is Native Bridging in Flutter?</h3><p><strong>Native Bridging in Flutter</strong> refers to the process of enabling communication between <strong>Dart (Flutter’s language)</strong> and the <strong>native platforms (Android and iOS)</strong>. While Flutter provides a rich set of plugins and libraries for most functionalities, sometimes you need to interact directly with platform-specific APIs, such as accessing native device features like the camera, GPS, sensors, or system information.</p><p>Flutter facilitates this communication using <strong>Platform Channels</strong>, which act as a bridge between Dart and the native languages <strong>(Kotlin/Java for Android, Swift/Objective-C for iOS)</strong>.</p><h3>📌 Types of Platform Channels in Flutter</h3><p>Flutter provides three types of platform channels for communication:</p><h3>1. MethodChannel (Request-Response Communication)</h3><p><strong>MethodChannel</strong> is the most commonly used platform channel, allowing Flutter to invoke native methods and receive responses. This is ideal for <strong>one-time function calls</strong> where Flutter needs a result from native code.</p><h4>How it Works</h4><ol><li><strong>Flutter (Dart Side)</strong> → Calls a method using MethodChannel.</li><li><strong>Native Code (Android/iOS)</strong> → Receives the request, processes it, and sends back a response.</li><li><strong>Flutter (Dart Side)</strong> → Receives the response and processes it further.</li></ol><h4>Use Cases</h4><ul><li>Fetching <strong>device information</strong> (e.g., battery level, model, OS version).</li><li>Performing <strong>native-specific operations</strong> (e.g., taking a screenshot).</li><li>Calling <strong>third-party NATIVE SDKs</strong> only available for Android/iOS.</li></ul><h3>2. EventChannel (Continuous Data Streams)</h3><p>Unlike MethodChannel, which is <strong>request-response based</strong>, EventChannel is used when <strong>Flutter needs to receive a continuous stream of data from native code</strong>. This is commonly used for event-driven data such as <strong>real-time updates from sensors, location tracking, or system events</strong>.</p><h4>How it Works</h4><ol><li><strong>Flutter (Dart Side)</strong> → Listens to an event using EventChannel.</li><li><strong>Native Code (Android/iOS)</strong> → Continuously sends data back to Flutter as a <strong>stream</strong>.</li><li><strong>Flutter (Dart Side)</strong> → Receives and processes the data in real-time.</li></ol><h4>Use Cases</h4><ul><li><strong>Real-time sensor updates</strong> (e.g., gyroscope, accelerometer, proximity sensor).</li><li><strong>Live location tracking</strong> instead of fetching location once.</li><li><strong>Device orientation changes</strong> or other continuous system events.</li></ul><h3>3. BasicMessageChannel (Bi-Directional Messaging)</h3><p>BasicMessageChannel is used for <strong>sending and receiving raw messages</strong> (text or binary data) between Flutter and native code <strong>without needing a direct method call</strong>. This is useful for <strong>lightweight messaging</strong> where you don’t require structured method calls.</p><h4>How it Works</h4><ol><li><strong>Flutter (Dart Side)</strong> → Sends a raw message using BasicMessageChannel.</li><li><strong>Native Code (Android/iOS)</strong> → Receives and processes the message.</li><li><strong>Native Code</strong> can also send a message back to Flutter at any time.</li></ol><h4>Use Cases</h4><ul><li><strong>Custom communication protocols</strong> between Flutter and native code.</li><li><strong>Data exchange without invoking specific methods.</strong></li><li><strong>Passing raw binary data</strong>, such as images or encrypted data.</li></ul><p>In general native bridging allows Flutter developers to access <strong>platform-specific functionality</strong> while still leveraging Flutter’s cross-platform capabilities. While most functionalities are available through plugins, <strong>some advanced or unique use cases require direct native interaction</strong>, making platform channels essential for <strong>unlocking full device capabilities</strong>.</p><p>For this guide, we will only <strong>focus on </strong><strong>MethodChannel</strong>, as it is the most commonly used channel for calling native code from Flutter. 🚀</p><h3>When to Use Method Channeling in Flutter (and When NOT to)</h3><h3>When to Use Method Channels</h3><p>Method channels are useful when you need to communicate between Flutter and platform-specific native code. Here are <strong>key scenarios where using method channels makes sense</strong>:</p><h3>1. Accessing Native Device Features Not Available in Flutter</h3><p>Flutter does not provide direct access to <strong>low-level device features</strong> like:</p><ul><li><strong>Battery information</strong></li><li><strong>Storage details</strong></li><li><strong>Bluetooth &amp; NFC communication</strong></li><li><strong>WiFi, cellular, and network configurations</strong></li><li><strong>Background services</strong></li><li><strong>Native notifications with advanced customization</strong></li></ul><p>If your app <strong>requires such hardware or OS-specific interactions</strong>, method channels are necessary to bridge the gap between Dart and the platform APIs.</p><h3>2. Implementing Performance-Critical Operations in Native Code</h3><p>Dart is not always the most efficient way to perform <strong>CPU-intensive</strong> or <strong>I/O-heavy</strong> tasks.<br>For example:</p><ul><li><strong>Image processing</strong> → Native libraries like OpenCV (C++/Kotlin/Swift) are much faster.</li><li><strong>Video compression</strong> → Using FFmpeg in native code performs better than a Dart-based solution.</li><li><strong>Cryptographic operations</strong> → Native libraries provide better security and speed.</li><li><strong>Machine learning (ML) models</strong> → Running TensorFlow or CoreML directly in native code is better than running it in Dart.</li></ul><p>If performance is a concern, <strong>offloading the task to native code via method channels is a good strategy</strong>.</p><h3>3. Using a Native SDK That Doesn’t Have a Flutter Plugin</h3><p>If you are <strong>integrating a third-party native SDK</strong> that doesn’t have a Flutter plugin, you may need to use method channels.<br>Examples:</p><ul><li><strong>Payment Gateways</strong> → Some regional payment providers only offer native SDKs.</li><li><strong>Hardware APIs</strong> → Some barcode scanners, fingerprint readers, or IoT devices only have native SDKs.</li><li><strong>Platform-Specific Services</strong> → Some apps rely on native features like Samsung’s S-Pen or Apple’s ProMotion.</li></ul><p>In such cases, <strong>method channels allow Flutter to communicate with those SDKs.</strong></p><h3>When NOT to Use Method Channels</h3><h3>1. When a Flutter Plugin Already Exists</h3><p>🚨 <strong>Don’t reinvent the wheel!</strong> If there is already a <strong>well-maintained</strong> Flutter package that does what you need, <strong>use it instead of writing your own method channel code</strong>.<br>For example:<br>✅ <strong>Want to access the device camera?</strong> → Use camera instead of writing your own native implementation.<br>✅ <strong>Need location data?</strong> → Use geolocator instead of method channels.<br>✅ <strong>Want to send push notifications?</strong> → Use firebase_messaging instead of creating your own notification system.</p><p>Using an existing package <strong>saves time, reduces maintenance effort, and ensures better cross-platform compatibility.</strong></p><h3>2. When an Existing Plugin is “Almost” What You Need</h3><p>🔧 <strong>Modify an existing plugin instead of creating a new one from scratch!</strong><br>If a plugin <strong>almost does what you need</strong> but lacks a specific feature, <strong>fork it</strong> from GitHub and customize it.</p><p>For example:</p><ul><li>If you need <strong>customized permissions handling</strong> for geolocator, fork it and modify the permissions logic instead of building a new location plugin.</li><li>If camera doesn’t support a particular resolution, tweak the native Android/iOS code inside the plugin instead of writing a new method channel.</li></ul><p><strong>Forking and modifying an existing plugin is often easier and more maintainable than creating an entirely new bridge.</strong></p><h3>3. When the Task Can Be Done Entirely in Dart</h3><p>If a feature <strong>can be implemented natively in Dart</strong>, avoid method channels altogether.</p><p>❌ <strong>Bad practice:</strong> Writing a method channel for <strong>parsing JSON</strong> when Dart’s dart:convert library does it natively.<br>❌ <strong>Bad practice:</strong> Using method channels to <strong>store data</strong> when Dart has shared_preferences or hive.<br>❌ <strong>Bad practice:</strong> Calling native code just to <strong>display text alerts</strong> when Flutter’s showDialog works fine.</p><p><strong>General Rule:</strong><br>👉 If the task can be done <strong>entirely in Dart</strong>, <strong>stick to Dart</strong>. Only use method channels when absolutely necessary.</p><h3>Method Channeling in Action : Setting Up the Flutter Method Channel</h3><p>Let’s start by creating a <strong>NativeBridge</strong> class in Flutter.</p><h3>Flutter Side (Dart)</h3><pre>import &#39;package:flutter/services.dart&#39;;<br><br>/// NativeBridge class acts as a bridge between Flutter and the native platform.<br>/// It uses a MethodChannel to invoke platform-specific methods.<br>class NativeBridge {<br>  // Define a MethodChannel with a unique channel name.<br>  static const MethodChannel _channel = MethodChannel(&#39;com.example.app/native&#39;);<br><br>  /// Fetch the platform version (Android/iOS)<br>  static Future&lt;String&gt; getPlatformVersion() async {<br>    try {<br>      // Call the native method &#39;getPlatformVersion&#39; and return the result.<br>      final String version = await _channel.invokeMethod(&#39;getPlatformVersion&#39;);<br>      return version;<br>    } catch (e) {<br>      return &quot;Error: $e&quot;; // Handle any exceptions<br>    }<br>  }<br><br>  /// Fetch the battery level of the device<br>  static Future&lt;String&gt; getBatteryLevel() async {<br>    try {<br>      // Call the native method &#39;getBatteryLevel&#39; and return the result.<br>      final int batteryLevel = await _channel.invokeMethod(&#39;getBatteryLevel&#39;);<br>      return &quot;Battery Level: $batteryLevel%&quot;;<br>    } catch (e) {<br>      return &quot;Error: $e&quot;; // Handle any errors<br>    }<br>  }<br><br>  /// Fetch the device model (e.g., &quot;Samsung Galaxy S21&quot; or &quot;iPhone 14&quot;)<br>  static Future&lt;String&gt; getDeviceModel() async {<br>    try {<br>      // Call the native method &#39;getDeviceModel&#39;<br>      final String model = await _channel.invokeMethod(&#39;getDeviceModel&#39;);<br>      return &quot;Device Model: $model&quot;;<br>    } catch (e) {<br>      return &quot;Error: $e&quot;;<br>    }<br>  }<br><br>  /// Fetch the available free storage space on the device<br>  static Future&lt;String&gt; getFreeStorage() async {<br>    try {<br>      // Call the native method &#39;getFreeStorage&#39;<br>      final String storage = await _channel.invokeMethod(&#39;getFreeStorage&#39;);<br>      return &quot;Free Storage: $storage&quot;;<br>    } catch (e) {<br>      return &quot;Error: $e&quot;;<br>    }<br>  }<br><br>  /// Fetch the current GPS location of the device<br>  static Future&lt;String&gt; getLocation() async {<br>    try {<br>      // Call the native method &#39;getLocation&#39;<br>      final String location = await _channel.invokeMethod(&#39;getLocation&#39;);<br>      return &quot;Current Location: $location&quot;;<br>    } catch (e) {<br>      return &quot;Error: $e&quot;;<br>    }<br>  }<br><br>  /// Show a native alert dialog (uses native UI components)<br>  static Future&lt;void&gt; showAlert(String message) async {<br>    try {<br>      // Invoke the native method &#39;showAlert&#39; and pass the message as an argument<br>      await _channel.invokeMethod(&#39;showAlert&#39;, {&#39;message&#39;: message});<br>    } catch (e) {<br>      print(&quot;Error: $e&quot;);<br>    }<br>  }<br><br>  /// Take a screenshot and return the file path where it is saved<br>  static Future&lt;String&gt; takeScreenshot() async {<br>    try {<br>      // Call the native method &#39;takeScreenshot&#39;<br>      final String screenshotPath = await _channel.invokeMethod(&#39;takeScreenshot&#39;);<br>      return &quot;Screenshot saved at: $screenshotPath&quot;;<br>    } catch (e) {<br>      return &quot;Error: $e&quot;;<br>    }<br>  }<br>}</pre><h3>Android Implementation</h3><p>Now, let’s implement these methods in native <strong>Kotlin</strong> for Android.</p><h3>Step 1: Configure the Method Channel in MainActivity</h3><p>Open <strong>MainActivity.kt</strong> and modify it:</p><pre>package com.example.app<br><br>import android.os.Build<br>import android.os.Bundle<br>import android.os.Environment<br>import android.os.Handler<br>import android.os.Looper<br>import android.widget.Toast<br>import androidx.annotation.NonNull<br>import io.flutter.embedding.android.FlutterActivity<br>import io.flutter.embedding.engine.FlutterEngine<br>import io.flutter.plugin.common.MethodChannel<br>import java.io.File<br>import java.text.SimpleDateFormat<br>import java.util.*<br><br>class MainActivity : FlutterActivity() {<br>    // Define a MethodChannel with a unique identifier<br>    private val CHANNEL = &quot;com.example.app/native&quot;<br><br>    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {<br>        super.configureFlutterEngine(flutterEngine)<br><br>        // Set up the MethodChannel to listen for calls from Flutter<br>        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result -&gt;<br>            when (call.method) {<br>                &quot;getPlatformVersion&quot; -&gt; result.success(&quot;Android &quot; + Build.VERSION.RELEASE)<br>                &quot;getBatteryLevel&quot; -&gt; result.success(getBatteryLevel()) // Call battery level method<br>                &quot;getDeviceModel&quot; -&gt; result.success(Build.MODEL) // Get device model<br>                &quot;getFreeStorage&quot; -&gt; result.success(getFreeStorage()) // Get storage info<br>                &quot;getLocation&quot; -&gt; result.success(getMockLocation()) // Mock GPS location<br>                &quot;showAlert&quot; -&gt; showAlert(call.argument(&quot;message&quot;)!!) // Show native alert<br>                &quot;takeScreenshot&quot; -&gt; result.success(takeScreenshot()) // Capture screenshot<br>                else -&gt; result.notImplemented()<br>            }<br>        }<br>    }<br><br>    // Get the battery level (Mocked; real implementation requires BatteryManager API)<br>    private fun getBatteryLevel(): Int {<br>        return 85 // Mock value, replace with real battery level fetching<br>    }<br><br>    // Get free storage space in MB<br>    private fun getFreeStorage(): String {<br>        val stat = Environment.getExternalStorageDirectory()<br>        val availableBytes = stat.freeSpace / (1024 * 1024)<br>        return &quot;$availableBytes MB&quot;<br>    }<br><br>    // Mock location data (Real implementation requires GPS permissions)<br>    private fun getMockLocation(): String {<br>        return &quot;Latitude: 37.7749, Longitude: -122.4194&quot;<br>    }<br><br>    // Show a native Android Toast message<br>    private fun showAlert(message: String) {<br>        Handler(Looper.getMainLooper()).post {<br>            Toast.makeText(applicationContext, message, Toast.LENGTH_LONG).show()<br>        }<br>    }<br><br>    // Mock taking a screenshot (Real implementation requires a Screenshot API)<br>    private fun takeScreenshot(): String {<br>        val timestamp = SimpleDateFormat(&quot;yyyyMMdd_HHmmss&quot;, Locale.getDefault()).format(Date())<br>        val file = File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), &quot;screenshot_$timestamp.png&quot;)<br>        return file.absolutePath<br>    }<br>}</pre><h3>iOS Implementation</h3><p>For iOS, open <strong>AppDelegate.swift</strong> and modify it:</p><pre>import UIKit<br>import Flutter<br>import CoreLocation<br><br>/// The AppDelegate class, responsible for setting up the Flutter application <br>/// and handling method channel communication with the native iOS side.<br>@main<br>@objc class AppDelegate: FlutterAppDelegate, CLLocationManagerDelegate {<br>    <br>    /// Instance of CLLocationManager to fetch current location.<br>    var locationManager = CLLocationManager()<br><br>    /// Called when the application has finished launching.<br>    /// Sets up the Flutter method channel and listens for method calls from Dart.<br>    ///<br>    /// - Parameters:<br>    ///   - application: The singleton app object.<br>    ///   - launchOptions: A dictionary containing information about the reason the app was launched.<br>    /// - Returns: `true` if the application launched successfully.<br>    override func application(<br>        _ application: UIApplication,<br>        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?<br>    ) -&gt; Bool {<br>        <br>        // Get the root FlutterViewController.<br>        let controller = window?.rootViewController as! FlutterViewController<br>        <br>        // Create a method channel for communication with Flutter.<br>        let channel = FlutterMethodChannel(name: &quot;com.example.app/native&quot;, binaryMessenger: controller.binaryMessenger)<br><br>        // Set a method call handler to respond to calls from Flutter.<br>        channel.setMethodCallHandler { (call, result) in<br>            switch call.method {<br>                case &quot;getPlatformVersion&quot;:<br>                    // Returns the iOS version.<br>                    result(&quot;iOS &quot; + UIDevice.current.systemVersion)<br>                <br>                case &quot;getBatteryLevel&quot;:<br>                    // Fetches and returns the battery level.<br>                    result(Int(UIDevice.current.batteryLevel * 100))<br>                <br>                case &quot;getDeviceModel&quot;:<br>                    // Returns the device model.<br>                    result(UIDevice.current.model)<br>                <br>                case &quot;getFreeStorage&quot;:<br>                    // Calls the function to fetch available storage space.<br>                    result(self.getFreeStorageSpace())<br>                <br>                case &quot;getLocation&quot;:<br>                    // Fetches the current GPS location.<br>                    self.getCurrentLocation { location in result(location) }<br>                <br>                case &quot;showAlert&quot;:<br>                    // Displays a native alert dialog with the given message.<br>                    let message = call.arguments as? String ?? &quot;Default Message&quot;<br>                    self.showNativeAlert(message: message)<br>                    result(nil)<br>                <br>                case &quot;takeScreenshot&quot;:<br>                    // Takes a screenshot and returns the file path.<br>                    result(self.takeScreenshot())<br>                <br>                default:<br>                    // If the method is not implemented, return an error.<br>                    result(FlutterMethodNotImplemented)<br>            }<br>        }<br><br>        return super.application(application, didFinishLaunchingWithOptions: launchOptions)<br>    }<br><br>    /// Retrieves the amount of free storage space available on the device.<br>    ///<br>    /// - Returns: A string indicating the available storage space in MB.<br>    private func getFreeStorageSpace() -&gt; String {<br>        let fileURL = URL(fileURLWithPath: NSHomeDirectory() as String)<br>        <br>        do {<br>            let values = try fileURL.resourceValues(forKeys: [.volumeAvailableCapacityKey])<br>            if let freeSpace = values.volumeAvailableCapacity {<br>                return &quot;\(freeSpace / (1024 * 1024)) MB free&quot;<br>            }<br>        } catch {<br>            return &quot;Storage info not available&quot;<br>        }<br>        <br>        return &quot;Storage info not available&quot;<br>    }<br><br>    /// Fetches the current GPS location of the device.<br>    ///<br>    /// - Parameter completion: A closure returning the location as a string.<br>    private func getCurrentLocation(completion: @escaping (String) -&gt; Void) {<br>        // Request permission to access location services.<br>        locationManager.requestWhenInUseAuthorization()<br>        <br>        if let location = locationManager.location {<br>            // Return the latitude and longitude of the device.<br>            completion(&quot;Lat: \(location.coordinate.latitude), Lng: \(location.coordinate.longitude)&quot;)<br>        } else {<br>            completion(&quot;Location not available&quot;)<br>        }<br>    }<br><br>    /// Displays a native alert dialog with a given message.<br>    ///<br>    /// - Parameter message: The message to be displayed in the alert.<br>    private func showNativeAlert(message: String) {<br>        let alert = UIAlertController(title: &quot;Native Alert&quot;, message: message, preferredStyle: .alert)<br>        alert.addAction(UIAlertAction(title: &quot;OK&quot;, style: .default))<br>        <br>        // Present the alert on the main UI thread.<br>        DispatchQueue.main.async {<br>            self.window?.rootViewController?.present(alert, animated: true)<br>        }<br>    }<br><br>    /// Captures a screenshot of the current screen.<br>    ///<br>    /// - Returns: A string indicating the file path where the screenshot was saved.<br>    private func takeScreenshot() -&gt; String {<br>        // Get the root window.<br>        guard let window = UIApplication.shared.windows.first else {<br>            return &quot;Error: No active window found&quot;<br>        }<br><br>        // Render the view into an image.<br>        UIGraphicsBeginImageContextWithOptions(window.bounds.size, false, 0.0)<br>        window.drawHierarchy(in: window.bounds, afterScreenUpdates: true)<br>        let screenshot = UIGraphicsGetImageFromCurrentImageContext()<br>        UIGraphicsEndImageContext()<br>        <br>        // Save the image to the device.<br>        if let image = screenshot, let imageData = image.pngData() {<br>            let filePath = NSTemporaryDirectory().appending(&quot;screenshot.png&quot;)<br>            FileManager.default.createFile(atPath: filePath, contents: imageData, attributes: nil)<br>            return &quot;Screenshot saved at: \(filePath)&quot;<br>        }<br>        <br>        return &quot;Error capturing screenshot&quot;<br>    }<br>}</pre><h3>Wrapping Up</h3><p>Now, you have a complete <strong>Flutter Native Bridging setup</strong> that supports: ✅ Platform version retrieval<br>✅ Battery level fetching<br>✅ Device model retrieval<br>✅ Free storage information<br>✅ GPS location retrieval<br>✅ Native alerts<br>✅ Screenshot handling</p><p>This method allows Flutter apps to <strong>seamlessly integrate with native features</strong> while keeping the UI in Flutter.</p><p>Do you have any other complex native functionalities in mind? Let me know in the comments! 🚀</p><p>Checkout the github repo at: <a href="https://github.com/WorkWithAfridi/FlutterMethodChanneling-NativeBridge.git">https://github.com/WorkWithAfridi/FlutterMethodChanneling-NativeBridge.git</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e07a11dc3099" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Encrypt & Decrypt data in Dart/ Flutter: A Guide to Encrypting and Decrypting Data]]></title>
            <link>https://medium.com/@afridi.khondakar/how-to-encrypt-decrypt-data-in-dart-flutter-a-guide-to-encrypting-and-decrypting-data-65d733b6dd99?source=rss-3ee2b01f5cab------2</link>
            <guid isPermaLink="false">https://medium.com/p/65d733b6dd99</guid>
            <category><![CDATA[decryption]]></category>
            <category><![CDATA[encryption]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Khondakar Afridi]]></dc:creator>
            <pubDate>Thu, 23 May 2024 05:01:22 GMT</pubDate>
            <atom:updated>2024-05-23T05:05:49.971Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Encrypt &amp; Decrypt data in Dart/ Flutter: A Guide to Encrypting and Decrypting Data, the why, what, and how!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aLbNzdHjcePfEJ8b.jpg" /><figcaption>Encryption converts regular text into a coded language that only someone with the right key can decode.</figcaption></figure><p>Heyyy! Today we’re diving into an essential aspect of app development — keeping our users’ data secure. In this article, we’ll explore how to encrypt and decrypt data in Flutter apps. We’ll go through the why, what, and how, complete with code snippets and practical tips. That being said, let’s get started!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*j5_Z6jN4bc3m8W0oRMRgUw.gif" /><figcaption>By the end of this article we should be able to build something like this! <a href="https://github.com/WorkWithAfridi/Flutter-encrypt-decrypt.git">https://github.com/WorkWithAfridi/Flutter-encrypt-decrypt.git</a></figcaption></figure><h3>What is Encryption?</h3><p>Encryption is the process of converting plain text into a coded format (ciphertext) that is unreadable without a key. Decryption is the reverse process, converting ciphertext back to its original form using the key. This key is also known as SALT btw.</p><h3>Why Encrypt Data?</h3><p><strong>Data security is paramount.</strong> Encryption ensures that even if data is intercepted via a man in the middle ;), it remains unreadable without the correct decryption key. This is crucial for protecting sensitive information like user credentials, personal details, and any other confidential data your app handles.</p><h3>How to Encrypt and Decrypt Data</h3><p>Encryption can be done very easily by using third party packages and with a little bit of setup, packages like <strong>encrypt and </strong><strong>cypher </strong>being the top two<strong>.</strong> We’ll be exploring the <strong>encrypt</strong> package and setup our own encryptor and decryptor in this article!</p><p>Learn more about the encrypt package at: <a href="https://github.com/leocavalcante/encrypt">https://github.com/leocavalcante/encrypt</a></p><p>But before that lets explore some encryption algorithms and get to know about them, a little.</p><p>For starters lets begin with <strong>AES, aka Advanced Encryption Standard</strong>, AES is considered safe and is widely used for securing data. <strong>AES is a symmetric encryption algorithm</strong> standardized by the National Institute of Standards and Technology (NIST) in 2001. With <strong>encryption strength, algorithm design, implementation, endorsement by experts and security being its strengths</strong>.</p><p>We also have Triple DES &amp; Twofish in the top symmetric encryption algorithms list. With <strong>Triple DES known as an enhancement of DES that applies the DES algorithm three times to each data block</strong>. It provides improved security but is slower and less efficient than AES. And <strong>Twofish</strong> being a symmetric key block cipher that was a finalist in the AES competition. It <strong>is known for its speed and high level of security</strong>.</p><p>Now you might be asing <strong>what are these symmetric and asymmetric Encryption Algorithms?</strong> Well to simply put it, symmetric and asymmetric encryption algorithms are<strong> two fundamental types of cryptographic techniques used to secure data</strong>. Where <strong>symmetric encryption algorithms use the same key for both encryption and decryption</strong>. This means that <strong>both the sender and the recipient of the message share a single, secret key</strong>. And<strong> asymmetric encryption algorithms using a pair of keys: a public key for encryption and a private key for decryption</strong>. These keys are mathematically related but cannot be derived from each other.</p><p>Anywho, for the Asymmetric Encryption Algorithm list we have <strong>RSA (Rivest-Shamir-Adleman), ECC (Elliptic Curve Cryptography) &amp; DSA (Digital Signature Algorithm) </strong>on the list.</p><p>That being said, now you might be wondering <strong>which one should I be using?</strong> <strong>Aymmetric or Asymmetric Encryption Algorithms?</strong> Well that <strong>depends on various factors including security requirements, performance considerations, and the specific use case</strong>. Most importantly <strong>it depends on the specific requirements and constraints of your application, as well as considerations for security, performance, and interoperability</strong>.</p><p>I digress, let get back to the fun part, I mean the coding part. Like I said before, encryption can be easily implemented through packages and some custom codes.</p><p>Lets being with the encrypt package.</p><p>First, add the necessary dependencies and import the necessary packages.</p><pre>dependencies:<br>  cupertino_icons: ^1.0.6<br>  encrypt: ^5.0.3<br>  flutter:<br>    sdk: flutter</pre><p><strong>For encryption, we need a key and an initialization vector (IV). </strong>The key should always be kept secure.</p><pre>final key = encrypt.Key.fromUtf8(&#39;MYKEY&#39;); <br>// where MYKEY.length should be 32.<br>// MYKEY could be something like &quot;b8cc8e559b5915ad4a61c0414f9017882d91d8c1d5d4179ff1f87ac14f209d20&quot;<br>// A 32 byte long key will ensure AES-256 level encryption, which rest assured VERY secure!<br><br>final iv = encrypt.IV.fromLength(16);<br>// IV (Initialization Vector) is a random or pseudo-random value used along with the encryption key to initialize the encryption algorithm.<br>// Its purpose is to ensure that even if the same plaintext is encrypted multiple times with the same key, the resulting ciphertexts are different.<br>// IVs are typically of fixed length and should be unique for each encryption operation. <br>// Here IVs are generated internally using a secure random number generator provided by the encrypt package. <br>// Does the Decryptor Need to Know the IV?<br>// Yes, the decryptor needs to know the IV to correctly decrypt the data. <br>// The decryption process must use the same IV that was used during encryption. <br>// However, the IV does not need to be kept secret. It can be safely stored or transmitted along with the ciphertext.</pre><p>Now lets create our encryptor and initialise it with our key and iv.</p><p><em>NOTE: Plese note that this key and iv should be same when decrypting the data, otherwise the decrypted data wont make any sense!</em></p><pre>final encrypter = encrypt.Encrypter(encrypt.AES(key));</pre><p>Now we can simply encrypt our data using</p><pre>final myText = &#39;Do nulla pariatur tempor reprehenderit reprehenderit sint anim minim enim sunt laborum adipisicing laborum et.&#39;;<br>final encrypted = encrypter.encrypt(myText, iv: iv);<br>// here iv is ensuing that we get diffrent cypher text everytime we encrypt the data.</pre><p>We can <strong>also setup or change encryption modes and not use the default one</strong> by setting up an encryption model class and using the pre-defined ones, and by passing down the mode as string while setting up the encryptor.</p><p><strong>Encryption modes determine how the algorithm processes the input data and how it encrypts blocks of data. Different modes offer different security properties and use cases.</strong> For example:</p><ul><li><strong>CBC</strong> (Cipher Block Chaining): This mode XORs each plaintext block with the previous ciphertext block before encryption. It requires an IV and is widely used for its security properties.</li><li><strong>CFB64</strong> (Cipher Feedback): This mode makes a block cipher into a self-synchronizing stream cipher. It processes data in segments (64 bits in this case).</li><li><strong>CTR</strong> (Counter): This mode turns a block cipher into a stream cipher. It encrypts a counter value and XORs it with the plaintext. It allows parallel processing.</li><li><strong>ECB</strong> (Electronic Codebook): This mode encrypts each block independently. It&#39;s not recommended for most use cases due to patterns in the plaintext being visible in the ciphertext.</li><li><strong>OFB64GCTR</strong> and <strong>OFB64</strong> (Output Feedback): These modes turn a block cipher into a synchronous stream cipher, generating keystream blocks independent of the plaintext and ciphertext.</li><li><strong>SIC</strong> (Segmented Integer Counter): This is another name for the CTR mode.</li></ul><pre>class EncryptionModes {<br>  static const CBC = &#39;AESMode.cbc&#39;;<br>  static const CFB64 = &#39;AESMode.cfb64&#39;;<br>  static const CTR = &#39;AESMode.ctr&#39;;<br>  static const ECB = &#39;AESMode.ecb&#39;;<br>  static const OFB64GCTR = &#39;AESMode.ofb64Gctr&#39;;<br>  static const OFB64 = &#39;AESMode.ofb64&#39;;<br>  static const SIC = &#39;AESMode.sic&#39;;<br>  static const PADDING = &#39;PKCS7&#39;;<br>  static const AESPADDING = &#39;PKCS7&#39;;<br>}<br>// These are already defined on the encrypt package, I just creating another seperate class just for readbility.</pre><p>And then use it while setting up the encryptor for encrypting the data as:</p><pre> final key = encrypt.Key.fromUtf8(&#39;MYKEY&#39;); <br>  final iv = encrypt.IV.fromLength(16); <br><br>  final encrypter = encrypt.Encrypter(<br>    encrypt.AES(<br>      key,<br>      mode: EncryptionModes.CBC, <br>      padding: EncryptionModes.PADDING,<br>    ),<br>  );<br>  // Here we are setting up the encrypter with the encryption modes along with padding.<br><br>  final plainText = &#39;Do nulla pariatur tempor reprehenderit reprehenderit sint anim minim enim sunt laborum adipisicing laborum et.&#39;;<br>  final encrypted = encrypter.encrypt(plainText, iv: iv);</pre><p>Now <strong>whats with the padding?</strong> You might ask.</p><p>Well, <strong>Padding schemes are used to ensure that the plaintext data fits the block size required by the encryption algorithm</strong>. For example: <strong>PKCS7</strong> is a common padding scheme where the value of each added byte is the number of bytes added. This ensures that the data can be properly unpadded after decryption.</p><p>Anyways we can get the encryped data using:</p><pre>log(encrypted.base64);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*cs4HnbLInoD70oUg18rNow.png" /></figure><p>Now you might be thinking <strong>why base64</strong>? Hmm, well,<strong> encrypted data are usually represented as a series of bytes</strong>. But in our case, since <strong>we’ll be storing these data on some server with most likely on a text-based formats (like JSON), its better off dealing with strings.</strong> <strong>Base64 encoding converts binary data into a string of ASCII characters, making it safe for transmission or storage in text-based formats.</strong></p><p>Now for the decrypting part, we can decrypt the data simply with: <em>(Provided, we are setting up the encrypter with the proper key and iv, like we did for the encryption part!)</em></p><pre>final decrypted = encrypter.decrypt(encryptedData, iv: iv);<br>log(&quot;This is my decrypted data: ${decrypted}&quot;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*DPEd3tU_iJ594HzBggnPDQ.png" /></figure><p>Now you might be asking, well Afridi, I know the encryptedData is stored on my server but <strong>where do I get the IV? Don’t they need to be the same for the encryption and the decryption part?</strong></p><p>Well, <strong>yes, the decryptor needs to know the IV to correctly decrypt the data.</strong> But since<strong> it (iv) is not necessary to keep it as a secret like our key, we can bundle up the iv with the encrypted message</strong>. I typically <strong>prefer using a service class</strong> for these scenarios. And heres how I do it.</p><pre>import &#39;package:encrypt/encrypt.dart&#39; as encrypt;<br><br>class EncryptionService {<br>  // The singleton instance<br>  static final EncryptionService _instance = EncryptionService._internal();<br><br>  // Private constructor<br>  EncryptionService._internal();<br><br>  // Factory constructor to return the same instance<br>  factory EncryptionService() {<br>    return _instance;<br>  }<br><br>  // Encryption key<br>  encrypt.Key? _key;<br><br>  // Method to initialize the encryption key<br>  void init(String keyString) {<br>    _key = encrypt.Key.fromUtf8(keyString);<br>  }<br><br>  // Method to encrypt data<br>  String encryptData(String plainText) {<br>    if (_key == null) {<br>      throw Exception(&#39;Encryption key is not initialized.&#39;);<br>    }<br>    final iv = encrypt.IV.fromLength(16); // Generate a random IV<br>    final encrypter = encrypt.Encrypter(encrypt.AES(_key!, mode: encrypt.AESMode.cbc));<br><br>    final encrypted = encrypter.encrypt(plainText, iv: iv);<br>    final ivBase64 = iv.base64;<br>    final encryptedBase64 = encrypted.base64;<br><br>    return &#39;$ivBase64:$encryptedBase64&#39;; // Store IV and ciphertext together<br>  }<br><br>  // Method to decrypt data<br>  String decryptData(String encryptedData) {<br>    if (_key == null) {<br>      throw Exception(&#39;Encryption key is not initialized.&#39;);<br>    }<br>    final parts = encryptedData.split(&#39;:&#39;);<br>    final iv = encrypt.IV.fromBase64(parts[0]); // Extract the IV<br>    final encrypted = encrypt.Encrypted.fromBase64(parts[1]);<br><br>    final encrypter = encrypt.Encrypter(encrypt.AES(_key!, mode: encrypt.AESMode.cbc));<br>    final decrypted = encrypter.decrypt(encrypted, iv: iv);<br><br>    return decrypted;<br>  }<br>}</pre><p>You can view the example project here: <a href="https://github.com/WorkWithAfridi/Flutter-encrypt-decrypt.git">https://github.com/WorkWithAfridi/Flutter-encrypt-decrypt.git</a></p><h3>Typical Workflow for Encryption and Decryption</h3><h3>Encryption</h3><ol><li><strong>Generate a Random IV</strong>: Use a secure random number generator to create a new IV for each encryption operation.</li><li><strong>Encrypt the Data</strong>: Use the key and the IV to encrypt the plaintext.</li><li><strong>Store/Transmit the IV and Ciphertext</strong>: The IV is typically prefixed or appended to the ciphertext, or stored/transmitted separately, but it must be made available to the decryptor.</li></ol><h3>Decryption</h3><ol><li><strong>Retrieve the IV</strong>: Obtain the IV used for the encryption of the ciphertext.</li><li><strong>Decrypt the Data</strong>: Use the key and the IV to decrypt the ciphertext back to the plaintext.</li></ol><p>And yeah, thats pretty much it!</p><p>Oh, now lets go over <strong>some good practises</strong>, before we end it for today.</p><ol><li><strong>Store Keys Securely:</strong> Never, NEVER hard-code keys in your app. Use secure storage solutions like Keychain for iOS and Keystore for Android.</li><li><strong>Use Strong Keys:</strong> Always use keys of appropriate length (256-bit/ 32 byte for AES-256).</li><li><strong>Rotate Keys:</strong> Regularly rotate encryption keys to minimize the impact of a potential compromise.</li><li><strong>Secure Communication:</strong> Ensure data transmitted over networks is encrypted using HTTPS.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65d733b6dd99" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Widget Testing in Flutter: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@afridi.khondakar/widget-testing-in-flutter-a-step-by-step-guide-8deb1b855990?source=rss-3ee2b01f5cab------2</link>
            <guid isPermaLink="false">https://medium.com/p/8deb1b855990</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-testing]]></category>
            <category><![CDATA[widget-testing]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[mockito]]></category>
            <dc:creator><![CDATA[Khondakar Afridi]]></dc:creator>
            <pubDate>Thu, 25 Apr 2024 14:26:04 GMT</pubDate>
            <atom:updated>2024-04-25T14:26:04.904Z</atom:updated>
            <content:encoded><![CDATA[<p>Widget tests in Flutter are designed to test a single widget’s behavior in isolation from the rest of the application. They’re part of the broader category of unit testing because they focus on a small, isolated unit of the UI — specifically, a single widget or a small group of related widgets. Widget testing in Flutter is a powerful tool to ensure your UI components work as expected over time, especially as your app scales and undergoes changes. By regularly writing and maintaining widget tests, you can significantly reduce bugs and improve the stability of your application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*82oaUQVc6knBwFUsXoWNLw@2x.png" /></figure><h3>Key Characteristics of Widget Tests:</h3><ul><li><strong>Isolation:</strong> Widget tests run in a test environment that simulates the widget tree, allowing you to instantiate and render the widgets under test without running the full app.</li><li><strong>Control:</strong> They provide a high level of control over the widget’s lifecycle, including pumping frames to simulate the passing of time or the completion of animations and building the widget tree.</li><li><strong>Mocking:</strong> Widget tests often use mocking to simulate dependencies, such as data fetching services, to focus on the UI’s interaction with given inputs and expected behaviors.</li><li><strong>Environment:</strong> They are faster than integration tests because they do not run on a real device or emulator but instead execute in a simulated environment that mimics the Flutter engine’s behavior.</li></ul><h3>Widget Testing in Action:</h3><p>With all that being said, lets now setup a widget test and see how it goes.</p><p>We’ll be simulating a somewhat complex widget test, that involves scrolling and initiating data fetching to populate a list, we’ll set up a mock for handling asynchronous data fetching.</p><ol><li>Lets start by setting up our Flutter environment/ dependencies.</li></ol><pre>dev_dependencies:<br>  flutter_test:<br>    sdk: flutter<br>  mockito:<br>  build_runner: </pre><p>2. Lets create the model classes and services. Lets assume we have a simple service class that fetches data from an API.</p><pre>import &#39;../models/item.dart&#39;;<br><br>abstract class ItemService {<br>  Future&lt;List&lt;Item&gt;&gt; fetchItems();<br>}<br><br>class DemoItemServices implements ItemService {<br>  @override<br>  Future&lt;List&lt;Item&gt;&gt; fetchItems() async {<br>    return [];<br>  }<br>}</pre><p>3. Implementing the Widget that we’ll be writing the test cases for. The widget uses ItemService to fetch items and display them in a ListView.</p><pre>// File: lib/widgets/items_list.dart<br>import &#39;package:flutter/material.dart&#39;;<br><br>import &#39;../models/item.dart&#39;;<br>import &#39;../services/item_service.dart&#39;;<br><br>class ItemsList extends StatefulWidget {<br>  final ItemService itemService;<br>  // We are injecting the item service class here, to isolate the widget.<br>  // Cleaner and easier to test.<br>  const ItemsList({super.key, required this.itemService});<br><br>  @override<br>  _ItemsListState createState() =&gt; _ItemsListState();<br>}<br><br>class _ItemsListState extends State&lt;ItemsList&gt; {<br>  late List&lt;Item&gt; items = [];<br>  bool isLoading = true;<br>  String? errorMessage;<br><br>  @override<br>  void initState() {<br>    super.initState();<br>    fetchItemList();<br>  }<br><br>  Future fetchItemList() async {<br>    try {<br>      items = await widget.itemService.fetchItems();<br>    } catch (e) {<br>      items = [];<br>      errorMessage = &quot;Failed to fetch data&quot;;<br>    }<br>    isLoading = false;<br>    setState(() {});<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    if (isLoading) {<br>      return const Center(<br>          child: CircularProgressIndicator(<br>        key: GlobalObjectKey(&quot;LOADING_INDICATOR&quot;),<br>      ));<br>    } else if (errorMessage != null) {<br>      return Center(child: Text(errorMessage ?? &quot;&quot;));<br>    } else {<br>      return ListView.builder(<br>        itemCount: items.length,<br>        itemBuilder: (context, index) {<br>          return Text(items[index].title);<br>        },<br>      );<br>    }<br>  }<br>}</pre><p>4. Now that we have our widget and services settled, lets write the widget test codes. I will be doing all the explanations in the code itself.</p><pre>// File: test/widgets/items_list_test.dart<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_test/flutter_test.dart&#39;;<br>import &#39;package:mockito/annotations.dart&#39;;<br>import &#39;package:mockito/mockito.dart&#39;;<br>import &#39;package:widget_test/models/item.dart&#39;;<br>import &#39;package:widget_test/services/item_service.dart&#39;;<br>import &#39;package:widget_test/views/item_list.dart&#39;;<br><br>import &#39;items_list_test.mocks.dart&#39;;<br><br>// Generate ItemService mock by using Mokito and build runner.<br>// MockItemService can simply be generate by adding them in the annotated list in the annotated GenerateMocks from Mokito<br>// and then by running dart run build_runner build<br>@GenerateMocks([ItemService])<br>void main() {<br>  late MockItemService? mockItemService;<br>  late List&lt;Item&gt;? mockItems;<br><br>  group(&quot;Test - Basic loading and scrolling behavior&quot;, () {<br>    // We create a mock ItemService and a list of 100 items.<br>    // The setUp func makes sure all of our services are up and running, before we<br>    // pump the widget.<br>    // And since we&#39;ve already mocked the ItemServide class, we can now manupulate the<br>    // returned data any way we like. Which is being done in the when()... block<br><br>    // setUp gets called before each test<br>    setUp(() async {<br>      mockItemService = MockItemService();<br>      mockItems = List.generate(100, (index) =&gt; Item(id: index, title: &#39;Item $index&#39;));<br><br>      when(mockItemService!.fetchItems()).thenAnswer((_) async {<br>        await Future.delayed(const Duration(seconds: 2));<br>        return mockItems!;<br>      });<br>    });<br><br>    // This tests if the mock service is working<br>    test(&#39;Test - Mock Service&#39;, () async {<br>      expect(await mockItemService?.fetchItems(), equals(mockItems));<br>    });<br><br>    testWidgets(&quot;Test - Loading indicator&quot;, (tester) async {<br>      await tester.pumpWidget(<br>        MaterialApp(<br>          home: Scaffold(<br>            body: ItemsList(itemService: mockItemService!),<br>          ),<br>        ),<br>      );<br>      await tester.pump(); // Trigger a frame to show the loading state<br><br>      // Checks if the ui rendered a loading indicator or not.<br>      expect(find.byType(CircularProgressIndicator), findsOneWidget);<br><br>      // To pump out the remaining frames<br>      await tester.pumpAndSettle();<br>    });<br><br>    // This pumps the MaterialApp along with our list widget, thats being tested.<br>    // .pumpWidget, initializes the widget and prepares it to be tested/ run.<br>    testWidgets(&#39;Test - Scrolling&#39;, (WidgetTester tester) async {<br>      await tester.pumpWidget(<br>        MaterialApp(<br>          title: &#39;Flutter Demo&#39;,<br>          theme: ThemeData(<br>            colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),<br>            useMaterial3: true,<br>          ),<br>          home: Scaffold(<br>            body: ItemsList(<br>              itemService: mockItemService!,<br>            ),<br>          ),<br>        ),<br>      );<br><br>      // Complete the futures and animations by repeatly calling pump<br>      await tester.pumpAndSettle();<br><br>      // Initial item checks<br>      // This checks the rendered UI and crosschecks if the rendered items contain any widget with<br>      // the text &quot;Item 0&quot;.<br>      expect(find.text(&#39;Item 0&#39;), findsOneWidget);<br><br>      // This checks the rendered UI and whether or not the rendered items contain item 99 or not<br>      expect(find.text(&#39;Item 99&#39;), findsNothing);<br><br>      // Perform a scroll to reveal the last item,<br>      await tester.drag(find.byType(ListView), const Offset(0, -5000));<br><br>      // Runs the required functions and animations<br>      await tester.pumpAndSettle();<br><br>      // Verify that the last item is now in view<br>      // This func again checks the rendered UI and crosschecks if the rendered items contain any widget with<br>      // the text &quot;Item 99&quot;.<br>      expect(find.text(&#39;Item 99&#39;), findsOneWidget);<br>    });<br><br>    tearDown(() {<br>      mockItemService = null;<br>      mockItems = null;<br>    });<br>  });<br>}</pre><p>To further expand our understanding of widget testing in Flutter, let’s delve deeper into the setup, execution, and the practical nuances of verifying UI components through examples. This will not only reinforce the concepts but also illustrate how widget testing fits into the broader context of application development.</p><h4>Expanded Explanation of Widget Testing Elements</h4><h3>Efficiency and Performance:</h3><p>Widget tests are particularly valuable because they run quickly. Unlike integration or end-to-end tests, widget tests do not need to interact with a real device or a full-fledged emulator, which significantly speeds up the feedback loop for developers. This rapid testing allows for more frequent and comprehensive testing cycles, which is critical in agile development environments.</p><h4>Mocking and Dependency Injection:</h4><p>The use of mocks in widget tests is crucial for isolating the component under test. By mocking dependencies, we ensure that the tests are not affected by external factors such as network latency or database access delays. For example, in our ItemsList widget, the ItemService is mocked to return controlled test data. This approach simulates different scenarios and edge cases (like empty data, error responses, etc.) to verify the widget’s resilience and handling under various conditions.</p><p>Let dive a little deeper and simulate a network error, where the list fails to load!</p><p>Our objective here is to test how our <strong>ItemsList</strong> widget behaves when the data service throws an exception (e.g., due to a network error).</p><pre><br>// Add this block of code in the main test block and run it to see the results. <br><br>group(&quot;Test - Basic error handling&quot;, () {<br>    // The setUp func makes sure all of our services are up and running, before we<br>    // pump the widget.<br>    // And since we&#39;ve already mocked the ItemServide class, we can now manupulate the<br>    // returned data any way we like. Which is being done in the when()... block<br>    setUp(() async {<br>      mockItemService = MockItemService();<br>      // We will throw an exception here to simulate a network error.<br>      when(mockItemService?.fetchItems()).thenAnswer((realInvocation) async {<br>        await Future.delayed(const Duration(seconds: 1)).then((value) {<br>          throw Exception(&#39;Failed to fetch data&#39;);<br>        });<br>      });<br>    });<br><br>    // Test to simulate an error during fetch<br>    testWidgets(&#39;Test - Error in fetch request&#39;, (WidgetTester tester) async {<br>      await tester.pumpWidget(<br>        MaterialApp(<br>          home: Scaffold(<br>            body: ItemsList(itemService: mockItemService!),<br>          ),<br>        ),<br>      );<br><br>      // Pumps out the remaining frames<br>      await tester.pumpAndSettle();<br><br>      // Check that the widget shows an error message<br>      expect(find.text(&#39;Failed to fetch data&#39;), findsOneWidget);<br><br>      // Ensure no items are displayed<br>      expect(find.byType(ListTile), findsNothing);<br>    });<br>  })</pre><h3>Advanced Interaction Testing:</h3><p>Testing user interactions like taps, scrolls, and input entry is crucial for ensuring that the widget responds as expected. Flutter’s testing framework provides methods like tap, drag, and enterText to simulate these actions.</p><p>Example of Interaction Testing:</p><p>Here’s an example on how we might test that tapping a list item opens a detail view:</p><pre>testWidgets(&#39;Tapping on an item opens the detail view&#39;, (WidgetTester tester) async {<br>  await tester.pumpWidget(MaterialApp(<br>    home: ItemsList(itemService: mockItemService),<br>  ));<br><br>  await tester.pumpAndSettle(); // Complete the futures and animations<br><br>  await tester.tap(find.text(&#39;Item 0&#39;));<br>  await tester.pumpAndSettle(); // Process the tap and animate to the next frame<br><br>  expect(find.byType(DetailView), findsOneWidget); // Check if the DetailView is displayed<br>});</pre><p>This test verifies that when a user taps on an item, the application navigates to the detail view, demonstrating the widget’s interactivity and responsiveness.</p><h3>Visual Verification:</h3><p>Flutter also offers tools to verify that widgets look as expected. This is crucial for maintaining UI consistency, especially after changes in the codebase. The <strong>matchesGoldenFile</strong> method can compare the current rendering of a widget with a saved &#39;golden&#39; file, which is a snapshot of the expected appearance.</p><pre>testWidgets(&#39;ItemsList matches the golden file snapshot&#39;, (WidgetTester tester) async {<br>  await tester.pumpWidget(MaterialApp(<br>    home: ItemsList(itemService: mockItemService),<br>  ));<br><br>  await tester.pumpAndSettle();<br>  expect(find.byType(ItemsList), matchesGoldenFile(&#39;goldens/items_list.png&#39;));<br>});</pre><p>This ensures the ItemsList widget’s layout and visual elements remain consistent with previous iterations or designs, guarding against unintended changes.</p><p>Yeah, thats pretty much it, I think we have covered most of widget testing here, lets end it off here... Explore the example Widget testing repo at : <a href="https://github.com/WorkWithAfridi/WidgetTest-Flutter">GITHUB REPO</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8deb1b855990" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Property Wrappers: Streamlining SwiftUI Development]]></title>
            <link>https://medium.com/@afridi.khondakar/mastering-property-wrappers-streamlining-swiftui-development-4d90b4b02faf?source=rss-3ee2b01f5cab------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d90b4b02faf</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[property-wrapper]]></category>
            <dc:creator><![CDATA[Khondakar Afridi]]></dc:creator>
            <pubDate>Sun, 14 Apr 2024 03:39:58 GMT</pubDate>
            <atom:updated>2024-04-14T03:39:58.949Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4HBTcKyYK4w7igTJ7IB4WA.png" /></figure><p>Property wrappers are powerful features introduced in Swift that streamline the management of property behavior and offer a clean syntax for defining custom property implementations. Since their inception, property wrappers have become an essential tool for developers working with SwiftUI, Apple’s declarative framework for building user interfaces. In SwiftUI, property wrappers play a crucial role in simplifying data management, enabling developers to encapsulate complex logic and behaviors within properties effortlessly.</p><p>Property wrappers in SwiftUI serve a variety of purposes, ranging from simplifying data validation to managing state and data flow within views. We’ll be going over some the commonly user wrappers in this Article. :)</p><h4><strong>@State</strong></h4><ul><li>@State property wrapper allows us to modify values inside a struct, which would normally not be allowed because structs are value types.</li><li>When we use @State before a property in SwiftUI, we move its storage to a special place managed by SwiftUI. This allows SwiftUI to recreate our structure whenever necessary without losing the data it was holding.</li><li>If we don’t declare @State property, it means we can not change the value of that property.</li></ul><pre>struct StateView: View {<br>    @State private var count = 0<br><br>    var body: some View {<br>        VStack {<br>            Button {<br>                count += 1<br>            } label: {<br>                Text(&quot;\(count)&quot;)<br>            }<br>        }<br>    }<br>}</pre><h4>@Bindings</h4><p>There can be multiple reusable components in one view. When you want the child view to change in the parent view, you can use a binding property wrapper. By using this in the child view, you can read or modify the parent view’s source of truth.</p><ul><li>@Binding does not accept any default value. • @Binding has to be public, not private.</li><li>You have to use $ to pass a binding reference because, without $, Swift will pass a copy of the value instead of passing a bindable reference.</li></ul><pre>struct StateBindingView: View {<br>    @State private var intValue = 0<br><br>    var body: some View {<br>        VStack {<br>            Text(&quot;intValue equals \(intValue)&quot;)<br>            BindingView(intValue: $intValue)<br>        }<br>    }<br>}<br><br>struct BindingView: View {<br>    @Binding var intValue: Int<br><br>    var body: some View {<br>        Button(&quot;Increment&quot;) {<br>            intValue += 1<br>        }<br>    }<br>}</pre><h4>@Published</h4><ul><li>@Published is the most useful property wrapper in SwiftUI. It allows to create the observable objects that automatically announce when changes occur.</li><li>SwiftUI automatically observes changes and re-invokes the body property of views that rely on the data. Whenever an object property marked @Published is changed, all views using that object will be reloaded to reflect those changes.</li><li>You don’t need to do anything else; the @Published property wrapper effectively adds a willSet property observer to the employee, so any changes are automatically sent out to observers.</li><li>As you can see, @Published is <em>opt-in. You</em> need to list which properties should cause announcements because the default is that changes don’t cause reloads. This means you can have properties that store caches, properties for internal use, and more. And they won’t force SwiftUI to reload views when they change unless you specifically mark them with @Published</li></ul><pre>class Company: ObservableObject {<br>    @Published var employee = [String]()<br>}</pre><h4>@StateObject</h4><ul><li>@StateObject is similar to @State property, except it’s applied to @ObservableObjects. An @ObservableObject protocol is always a reference type (class) and informs SwiftUI whenever one of its @Published properties will change.</li><li>When you need to create a reference type inside one of your views and ensure it stays alive for use in that view and others you share it with, that’s where @StateObject is used.</li><li>A property marked as @StateObject will keep its initially assigned instance as long as the view is needed, even when the struct gets recreated by SwiftUI.</li><li>This is the same behavior you see in @State, except it’s applied to an ObservableObject rather than a value type like a struct.</li></ul><pre>class CounterViewModel: ObservableObject {<br>    @Published var count = 0<br>}<br><br>struct CounterView: View {<br>    @StateObject var viewModel = CounterViewModel()<br>    <br>    var body: some View {<br>        VStack {<br>            Text(&quot;\(viewModel.count)&quot;)<br>            Button(&quot;Increment&quot;) {<br>                viewModel.count += 1<br>            }<br>        }<br>    }<br>}<br><br>struct RandomNumberView: View {<br>    @State var randomNumber = 0<br><br>    var body: some View {<br>        VStack {<br>            Text(&quot;\(randomNumber)&quot;)<br>            Button(&quot;Random number&quot;) {<br>                randomNumber = (0..&lt;1000).randomElement()!<br>            }<br>        }.padding(.bottom)<br>        CounterView()<br>    }<br>}</pre><h4>@ObservedObject</h4><p>An @ObservedObject is used to wrap ObservableObject instances that are not created or owned by the view that’s used. It’s applied to the same types of objects as @StateObject, and it provides similar features, except a view doesn’t create its own @ObservedObject instances.</p><ul><li>Any type marked with @ObservedObject must conform to the ObservableObject protocol.</li><li>Observed objects are specifically designed for data that is external to your view, which means it might be shared across more than one view. The @ObservedObject property wrapper will automatically make sure the property is watched closely so that important changes will reload any views using it. This also means the data must be created elsewhere, and then sent into your view.</li><li>Not all properties in an observed object cause views to refresh –The @Published property wrapper is added to any properties inside an observed object that should cause views to update when they change. ObservedObjects are usually used when the data is stored outside of the view, so when the view is redrawn, you won’t lose the data. StateObjects are usually used when that data needs to be stored inside the view.</li></ul><pre>class CounterViewModel: ObservableObject {<br>    @Published var count = 0<br>}<br><br>struct CounterView: View {<br>    @ObservedObject var viewModel = CounterViewModel()<br>    <br>    var body: some View {<br>        VStack {<br>            Text(&quot;\(viewModel.count)&quot;)<br>            Button(&quot;Increment&quot;) {<br>                viewModel.count += 1<br>            }<br>        }<br>    }<br>}</pre><p><strong>Observable Objects with Custom Publishers</strong></p><p>In advanced use-cases, you might want to have custom logic to decide when to publish changes. This is done by creating custom publishers:</p><pre>class UserProfile: ObservableObject {<br>    let objectWillChange = ObservableObjectPublisher()<br>    var username = &quot;John Doe&quot; {<br>        willSet { objectWillChange.send() } // this will manually update the view<br>    }<br>}<br>struct ContentView: View {<br>    @ObservedObject var userProfile = UserProfile()<br>    var body: some View {<br>        Text(userProfile.username)<br>    }<br>}</pre><p>In this case, the objectWillChange sends notifications whenever the username changes.</p><h4>@EnvironmentObject</h4><p>SwiftUI’s @EnvironmentObject property wrappers allow us to create views that rely on shared data, often across an entire SwiftUI app.</p><ul><li>@EnvironmentObject is created with and stored at the application level. It’s shared data that every view can read/write if they want to.</li><li>Since all views point to the same model, if one view changes the model, all views immediately update, i.e., there’s no risk of getting different parts of your app out of sync.</li><li>@EnvironmentObject has a lot in common with @ObservedObject — both must refer to a class that conforms to ObservableObject, both can be shared across many views, and both will update any views that are watching when significant changes happen. However, @EnvironmentObject specifically means “this object will be provided from some outside entity, rather than being created by the current view or specifically passed in.”</li><li>Just like @ObservedObject, you never assign a value to an @EnvironmentObject property. Instead, it should be passed in from elsewhere, and ultimately you’re probably going to want to use @StateObject to create it somewhere.</li><li>However, <em>unlike</em> @ObservedObject, we don’t pass our objects into other views by hand. Instead, we send the data into a modifier called environmentObject(), which makes the object available in SwiftUI’s environment for that view plus any others inside it.</li><li>If you need to add multiple objects to the environment, you should add multiple environmentObject() modifiers; just call them one after the other.</li></ul><pre>class Score: ObservableObject {<br>    @Published var count = 0<br>}<br><br>struct EnvironmentObjectView: View {<br>    @StateObject var score = Score()<br><br>    var body: some View {<br>        NavigationStack {<br>            VStack {<br>                Button(&quot;Increment Counter&quot;) {<br>                    score.count += 1<br>                }<br>                NavigationLink {<br>                    EnvionmentDetailView()<br>                } label: {<br>                    Text(&quot;Show Detail View&quot;)<br>                }<br>            }<br>        }.environmentObject(score)<br>    }<br>}<br><br>struct EnvionmentDetailView: View {<br>    @EnvironmentObject var score: Score<br><br>    var body: some View {<br>       Text(&quot;Incremented Score = \(score.count)&quot;)<br>    }<br>}</pre><h4>@Environment</h4><p>@Environment property observer is used when we might need to read a device setting or device environment to adjust our view or behavior to match user needs. Examples of these values are current device locale, device current calendar, color scheme (dark or light), and size class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*doe5WCPn7KDtLq3fqRiRFg.png" /></figure><pre>struct ContentView: View {<br>    @Environment(\.colorScheme) private var colorScheme<br><br>    var body: some View {<br>        VStack {<br>            Text(colorScheme == .dark ? &quot;dark&quot; : &quot;light&quot;)<br>        }<br>    }<br>}</pre><p>Besides using the predefined values provided by SwiftUI, we can also create our own custom @Environment values using the following three steps: <br>1. Declaring a new environment key type:</p><pre>private struct AnalyticsCategoryEnvironmentKey: EnvironmentKey {<br>    static let defaultValue: String = &quot;none&quot;<br>}</pre><p>2. Defining our environment value property by extending EnvironmentValues:</p><pre>extension EnvironmentValues {<br>    var analyticsCategory: String {<br>        get { self[AnalyticsCategoryEnvironmentKey.self] }<br>        set { self[AnalyticsCategoryEnvironmentKey.self] = newValue }<br>    }<br>}</pre><p>3. Now, we can use the environment value in our views.</p><pre>// Setting the environment value.<br>LoginView()<br>    .environment(\.analyticsCategory, &quot;login&quot;)<br><br>// Accessing the environment value.<br>struct LoginView: View {<br>    @Environment(\.analyticsCategory) var analyticsCategory: String<br><br>    var body: some View {<br>        Text(analyticsCategory)<br>    }<br>}</pre><h4>@AppStorage</h4><p>@AppStorage is a property wrapper provided by SwiftUI that simplifies the process of persisting small amounts of user settings or preferences across app launches. It automatically stores and retrieves values from the user defaults, making it convenient for managing simple app-wide data.</p><pre>import SwiftUI<br><br>struct ContentView: View {<br>    // Define a property wrapped with AppStorage<br>    @AppStorage(&quot;username&quot;) var username: String = &quot;Guest&quot;<br>    <br>    var body: some View {<br>        VStack {<br>            Text(&quot;Welcome, \(username)!&quot;)<br>            <br>            // Text field to update the username<br>            TextField(&quot;Enter your username&quot;, text: $username)<br>                .padding()<br>                .textFieldStyle(RoundedBorderTextFieldStyle())<br>                .padding()<br>        }<br>        .padding()<br>    }<br>}<br><br>struct ContentView_Previews: PreviewProvider {<br>    static var previews: some View {<br>        ContentView()<br>    }<br>}</pre><h4>@FetchRequest</h4><p>@FetchRequest is a property wrapper provided by SwiftUI specifically for managing Core Data fetch requests. It allows you to easily integrate Core Data with SwiftUI views by automatically executing a fetch request and providing the results to your view.</p><pre>import SwiftUI<br>import CoreData<br><br>struct ContentView: View {<br>    @Environment(\.managedObjectContext) private var viewContext<br>    <br>    // Declare a fetch request using @FetchRequest<br>    @FetchRequest(<br>        sortDescriptors: [NSSortDescriptor(keyPath: \TodoItem.timestamp, ascending: true)],<br>        animation: .default)<br>    private var todoItems: FetchedResults&lt;TodoItem&gt;<br><br>    var body: some View {<br>        NavigationView {<br>            List {<br>                ForEach(todoItems) { item in<br>                    Text(item.title ?? &quot;Untitled&quot;)<br>                }<br>                .onDelete(perform: deleteItems)<br>            }<br>            .navigationBarItems(trailing: EditButton())<br>        }<br>    }<br><br>    private func deleteItems(offsets: IndexSet) {<br>        withAnimation {<br>            offsets.map { todoItems[$0] }.forEach(viewContext.delete)<br><br>            do {<br>                try viewContext.save()<br>            } catch {<br>                // Handle error<br>                let nsError = error as NSError<br>                fatalError(&quot;Unresolved error \(nsError), \(nsError.userInfo)&quot;)<br>            }<br>        }<br>    }<br>}<br><br>struct ContentView_Previews: PreviewProvider {<br>    static var previews: some View {<br>        let persistenceController = PersistenceController.preview<br>        return ContentView().environment(\.managedObjectContext, persistenceController.container.viewContext)<br>    }<br>}</pre><h4>@FocusedBinding</h4><p>@FocusedBinding is designed to watch for values in the key window, such as a text field that is currently selected.</p><h4>@FocusedValue</h4><p>@FocusedValue is a simpler version of @FocusedBinding that doesn’t unwrap the bound value for you</p><h4>@GestureState</h4><p>@GestureState is a property wrapper that allows you to track the state of a gesture across its lifetime. It’s particularly useful for managing transient state changes during gesture interactions, such as dragging, tapping, or pinching. It stores values associated with a gesture that is currently in progress, such as how far you have swiped, except it will be reset to its default value when the gesture stops.</p><pre>import SwiftUI<br><br>struct DraggableView: View {<br>    @GestureState private var dragOffset: CGSize = .zero<br><br>    var body: some View {<br>        let dragGesture = DragGesture()<br>            .updating($dragOffset) { value, dragOffset, _ in<br>                dragOffset = value.translation<br>            }<br><br>        return RoundedRectangle(cornerRadius: 10)<br>            .frame(width: 200, height: 200)<br>            .foregroundColor(.blue)<br>            .offset(dragOffset)<br>            .gesture(dragGesture)<br>    }<br>}<br><br>struct ContentView: View {<br>    var body: some View {<br>        DraggableView()<br>    }<br>}<br><br>struct ContentView_Previews: PreviewProvider {<br>    static var previews: some View {<br>        ContentView()<br>    }<br>}</pre><h4>@Namespace</h4><p>@Namespace” is a property wrapper provided by SwiftUI that allows you to synchronize the namespace of matched views for use in animations. It’s commonly used in conjunction with matchedGeometryEffect to create smooth transitions between views when their positions or sizes change.</p><pre>import SwiftUI<br><br>struct ContentView: View {<br>    @State private var isFlipped = false<br>    @Namespace private var namespace<br><br>    var body: some View {<br>        VStack {<br>            if isFlipped {<br>                Circle()<br>                    .fill(Color.blue)<br>                    .frame(width: 100, height: 100)<br>                    .matchedGeometryEffect(id: &quot;circle&quot;, in: namespace)<br>            } else {<br>                RoundedRectangle(cornerRadius: 10)<br>                    .fill(Color.red)<br>                    .frame(width: 200, height: 200)<br>                    .matchedGeometryEffect(id: &quot;rectangle&quot;, in: namespace)<br>            }<br>        }<br>        .onTapGesture {<br>            withAnimation {<br>                isFlipped.toggle()<br>            }<br>        }<br>    }<br>}<br><br>struct ContentView_Previews: PreviewProvider {<br>    static var previews: some View {<br>        ContentView()<br>    }<br>}</pre><h4>@NSApplicationDelegateAdaptor</h4><p>@NSApplicationDelegateAdaptor is a Swift property wrapper introduced in macOS 11 (Big Sur) that allows you to define a custom SwiftUI app delegate conforming to the NSApplicationDelegate protocol. This wrapper simplifies the integration of AppKit&#39;s NSApplicationDelegate with SwiftUI apps.</p><pre>import SwiftUI<br><br>@main<br>struct MyApp: App {<br>    @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate<br>    <br>    var body: some Scene {<br>        WindowGroup {<br>            ContentView()<br>        }<br>    }<br>}<br><br>class AppDelegate: NSObject, NSApplicationDelegate {<br>    func applicationDidFinishLaunching(_ notification: Notification) {<br>        print(&quot;Application did finish launching&quot;)<br>    }<br>    <br>    func applicationWillTerminate(_ notification: Notification) {<br>        print(&quot;Application will terminate&quot;)<br>    }<br>}</pre><h4>@ScaledMatric</h4><p>@ScaledMatric reads the user’s Dynamic Type setting and scales numbers up or down based on an original value you provide.</p><h4>@SceneStorage</h4><p>@SceneStorage is a property wrapper introduced in SwiftUI for managing the state of a view across different scenes in a multi-window or multi-device environment. It’s particularly useful for preserving the state of a view when it moves between scenes, such as when the user switches between different windows or devices.</p><pre>import SwiftUI<br><br>struct ContentView: View {<br>    @SceneStorage(&quot;isDarkModeOn&quot;) private var isDarkModeOn = false<br>    <br>    var body: some View {<br>        VStack {<br>            Toggle(&quot;Dark Mode&quot;, isOn: $isDarkModeOn)<br>                .padding()<br>            Text(&quot;Current mode: \(isDarkModeOn ? &quot;Dark&quot; : &quot;Light&quot;)&quot;)<br>                .padding()<br>        }<br>        .frame(maxWidth: .infinity, maxHeight: .infinity)<br>        .background(isDarkModeOn ? Color.black : Color.white)<br>        .foregroundColor(isDarkModeOn ? Color.white : Color.black)<br>    }<br>}<br><br>struct ContentView_Previews: PreviewProvider {<br>    static var previews: some View {<br>        ContentView()<br>    }<br>}</pre><h4>@UIApplicationDelegateAdaptor</h4><p>@UIApplicationDelegateAdaptor is a property wrapper introduced in iOS 14 and macOS 11 that allows you to provide a custom UIApplicationDelegate for your SwiftUI app. This property wrapper simplifies the integration of UIKit&#39;s UIApplicationDelegate with SwiftUI apps.</p><pre>import SwiftUI<br><br>@main<br>struct MyApp: App {<br>    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate<br>    <br>    var body: some Scene {<br>        WindowGroup {<br>            ContentView()<br>        }<br>    }<br>}<br><br>class AppDelegate: NSObject, UIApplicationDelegate {<br>    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -&gt; Bool {<br>        print(&quot;Application did finish launching&quot;)<br>        return true<br>    }<br>    <br>    func applicationWillTerminate(_ application: UIApplication) {<br>        print(&quot;Application will terminate&quot;)<br>    }<br>}</pre><h3>Storing temporary data</h3><p>When it comes to storing data in your app, the simplest property wrapper is <strong>@State</strong>. This is designed to store value types that are used locally by your view, so it’s great for storing integers, Booleans, and even local instances of structs.</p><p>In comparison, <strong>@Binding</strong> is used for simple data that you want to change, but is <em>not</em> owned by your view. As an example, think of how the built-in <strong>Toggle</strong> switch works: it needs to move between on and off states, but it doesn’t want to store that value itself so instead it has a binding to some external value that <em>we</em> own. So, our view has an <strong>@State</strong> property, and the <strong>Toggle</strong> has an <strong>@Binding</strong> property. And whenever our <strong>@State changes it notifies the </strong><strong>@Binding and in return it updates the Toggle button.</strong></p><p>For more advanced purposes — i.e., dealing with classes, or sharing data in many places — you should <em>not</em> use <strong>@State</strong> and <strong>@Binding</strong>. Instead, you should create your object somewhere using <strong>@StateObject</strong>, then use it in other views with <strong>@ObservedObject</strong>.</p><p>So, <strong>@State</strong> means simple value type data created and managed locally but perhaps shared elsewhere using <strong>@Binding</strong>, and <strong>@StateObject</strong> means reference type data created and managed locally, but perhaps shared elsewhere using something like <strong>@ObservedObject</strong>.</p><p>If you find yourself handing the same data from view to view to view, you’ll find the <strong>@EnvironmentObject</strong> property wrapper useful. This lets you read a reference type object from a shared environment, rather than passing it around explicitly.</p><p>The final state-based property wrapper is <strong>@Published</strong>, which is used <em>inside</em> your reference types to annotate the properties. Any property marked with <strong>@Published</strong> will cause its parent class to announce that a change has occurred, which in turn will cause any view observing that object to make any changes it needs.</p><h3>Storing long-term data</h3><p><strong>@AppStorage</strong> is a wrapper around <strong>UserDefaults</strong>. Every time you read or write a value from app storage, you’re actually reading or writing from <strong>UserDefaults</strong>.</p><p>The second is <strong>@SceneStorage</strong>, which is a wrapper around Apple’s state restoration APIs. State restoration is what allows an app to be closed and reloaded, and come back to the same state the user left off – it makes it look like our apps were always running, even though they were silently terminated.</p><p><strong>@AppStorage and </strong><strong>@SceneStorage are <em>not</em> secure and should <em>not</em> be used to store sensitive data.</strong> So, you might use <strong>@AppStorage</strong> to store global values such as “what is the user’s high score?”, and you might use <strong>@SceneStorage</strong> to store “what page is the user reading right now?”</p><p>The third data property wrapper is <strong>@FetchRequest</strong>, which is used to retrieve information from Core Data. This will automatically use whichever managed object context is in the environment, and update itself when the underlying data has changed.</p><h3>Reading environment data</h3><p><strong>@Environment</strong> is used to read a wide variety of data such as what trait collection is currently active, whether they are using a 2x or 3x screen, what timezone they are on, and more.</p><p><strong>@ScaledMetric</strong> is much simpler, and lets us adapt the size of our user interface based on a user’s Dynamic Type settings. For example, a box that is 100x100 points might look great using the system default size, but with <strong>@ScaledMetric</strong> it will automatically become 200x200 when a larger Dynamic Type setting is enabled.</p><h3>Referring to views</h3><p>SwiftUI provides the <strong>@Namespace</strong> property wrapper, which creates a new namespace for animations. Animation namespaces let us say “animate views with an ID of 5”, and all views in that namespace with the ID 5 will be animated.</p><p>You can share namespaces between views by using the property type <strong>Namespace.ID</strong> and injecting the <strong>@Namespace</strong> value from whichever view created it. This allows you to created matched geometry effect animations across views, rather than storing all the data in the current view.</p><h3>Application handling</h3><p>If you ever need access to the old <strong>UIApplicationDelegate</strong> and <strong>NSApplicationDelegate</strong> methods and notifications, you should use the <strong>@UIApplicationDelegateAdaptor</strong> and <strong>@NSApplicationDelegateAdaptor</strong> property wrappers respectively.</p><p>You provide these with the class of your app delegate, and they will make sure an instance is created and sent all appropriate notifications.</p><h3>Bonus;)</h3><p><strong>I want to make a new property owned by the current view.</strong> You should use <strong>@State</strong> for value types, and <strong>@StateObject</strong> for reference types.</p><p><strong>I want to refer to a value created elsewhere.</strong> You should use <strong>@Binding</strong> for value types, and either <strong>@ObservedObject</strong> or <strong>@EnvironmentObject</strong> for reference types.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d90b4b02faf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bridging the Gap: Integrating Native SwiftUI Views in Flutter]]></title>
            <link>https://medium.com/@afridi.khondakar/bridging-the-gap-integrating-native-swiftui-views-in-flutter-4c81828598ba?source=rss-3ee2b01f5cab------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c81828598ba</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[method-channel]]></category>
            <category><![CDATA[native-code]]></category>
            <category><![CDATA[platform-channel]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Khondakar Afridi]]></dc:creator>
            <pubDate>Sun, 10 Mar 2024 12:17:25 GMT</pubDate>
            <atom:updated>2024-03-10T12:19:38.414Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*0ZykNWXVp9CG1ZBC43ZS_g.png" /></figure><p>In this article, we’ll explore the exciting possibility of integrating native SwiftUI views into Flutter applications and discuss how to seamlessly call them.</p><h4>Why Integrate SwiftUI into Flutter?</h4><p>While Flutter is excellent for cross-platform development, there might be scenarios where utilizing native iOS components built with SwiftUI can be beneficial. For example, imagine a scenario where you’re developing a media-rich application in Flutter, and you want to provide users with a seamless picture-in-picture experience on iOS devices. SwiftUI, being native to iOS, is an ideal choice for implementing this feature. While there are packages which might support these features, but speaking from experience most, if not all of them are either compatible for android or iOS, or in some cases are super buggy.</p><h4>Integration:</h4><p>Lets start by creating our view in SwiftUI first. I will be using AVPlayer for the video player and a combination of other configurations to integrate the picture in picture mode/video player in SwiftUI. For reference, I will be using codes and snippets from my previous article where I developed a streaming video player app with picture in picture mode and background playback services, read more at: (<a href="https://medium.com/@afridi.khondakar/implementing-background-play-picture-in-picture-in-swiftui-building-a-video-streaming-app-with-141304b84728">SwiftUI — Picture in Picture</a>)</p><pre>import Foundation<br>import SwiftUI<br><br>// A SwiftUI view representing the player interface<br>struct PlayerView: View {<br>    // StateObject that manages the player controller and its state<br>    @StateObject var playerController = PlayerController()<br><br>    var body: some View {<br>        VStack(alignment: .center) {<br>            // Use GeometryReader to adapt to the available space<br>            GeometryReader { geometry in<br>                let parentWidth = geometry.size.width<br><br>                // Display loading message if the player is not initialized yet<br>                if playerController.player == nil {<br>                    Text(&quot;Loading&quot;)<br>                } else {<br>                    // Display VideoPlayer if the player is initialized<br>                    VideoPlayer(playerController: playerController)<br>                        .frame(width: parentWidth)<br>                }<br>            }<br>            .frame(height: 200)<br><br>            // Play and Pause buttons<br>            Button {<br>                playerController.playPlayer()<br>            } label: {<br>                Text(&quot;Play video&quot;)<br>            }<br><br>            Button {<br>                playerController.pausePlayer()<br>            } label: {<br>                Text(&quot;Pause video&quot;)<br>            }<br>        }<br>        // Initialize the player on view appear<br>        .onAppear {<br>            playerController.initPlayer(<br>                title: &quot;SomeTitle&quot;,<br>                link: &quot;https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4&quot;,<br>                artist: &quot;Khondakar Afridi&quot;,<br>                artwork: &quot;Artist&quot;<br>            )<br>        }<br>    }<br>}<br><br>// Preview for PlayerView<br>#if DEBUG<br>struct PlayerView_Previews: PreviewProvider {<br>    static var previews: some View {<br>        PlayerView()<br>    }<br>}<br>#endif</pre><p>Here we have developed a basic Video player with PIP mode using SwiftUI. Read more about it at: (<a href="https://medium.com/@afridi.khondakar/implementing-background-play-picture-in-picture-in-swiftui-building-a-video-streaming-app-with-141304b84728">SwiftUI — Picture in Picture</a>)</p><p>Now we need to refer back to this screen from Flutter itself. And to facilitate this communication between Flutter and native code, we will be using a platform channel. Lets start by defining a method to call the SwiftUI view from Flutter in your Dart code.</p><pre>// This class represents a SwiftUI Picture-in-Picture (PiP) view in Flutter.<br>class SwiftUIPipView extends StatelessWidget {<br>  // Constructor for the SwiftUIPipView, taking an optional key parameter.<br>  const SwiftUIPipView({super.key});<br><br>  // Build method to create the widget hierarchy.<br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      // Scaffold widget provides the basic structure of the screen.<br>      body: Container(<br>        // Container widget to hold the PiP view.<br>        color: Colors.white, // Set background color to white.<br>        width: Get.width, // Set width to the width of the screen.<br>        height: Get.height, // Set height to the height of the screen.<br>        child: Column(<br>          // Column widget to vertically align the child widgets.<br>          mainAxisAlignment: MainAxisAlignment.center, // Center the child widgets vertically.<br>          children: [<br>            SizedBox(<br>              // SizedBox widget to set a fixed height for the UiKitView.<br>              height: 400,<br>              child: UiKitView(<br>                // UiKitView to embed a native SwiftUI view.<br>                viewType: &#39;swiftui_integration&#39;, // Identifier for the native view.<br>                creationParams: {<br>                  &#39;link&#39;: &quot;video link&quot;,<br>                  &#39;duration&#39;: duration,<br>                }, // To send data from Flutter view to SwiftUI view<br>                onPlatformViewCreated: (id) {<br>                  // Callback when the native view is created.<br>                  // You can communicate with the Swift code here if needed.<br>                },<br>              ),<br>            )<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>The UiKitView widget here is a platform-specific widget used to embed native iOS views (UIKit views) within a Flutter app. It allows us to integrate iOS-specific UI components or screens directly into the Flutter application.</p><ul><li>viewType: This property specifies the identifier for the native view. In this case, it is set to ‘swiftui_integration’, indicating that the native view being embedded is associated with a Swift UI integration. Think of it as a KEY, connecting the 2 UIs.</li><li>onPlatformViewCreated: This property is a callback that gets triggered when the native view is created. It provides an opportunity for Flutter to communicate with the native code. In the provided code, as the comment suggests, you can perform Swift code communication within this callback if needed.</li></ul><pre>creationParams: {<br>  &#39;link&#39;: &quot;video link&quot;,<br>  &#39;duration&#39;: duration,<br>}</pre><p>We can use the creationParams to pass any args to the SwiftUI view, if required. Here we’re using it to pass the link of the video, as well as the duration of the video watched to SwiftUI player, so that we can resume playing the video from the same timeframe in the Picture in picture view.</p><p>We can now handle the invocation in Native Code by modifying the AppDelegate accordingly. We’ll be using the AppDelegate from the SwiftUI AVPlayer project, read more at: (<a href="https://medium.com/@afridi.khondakar/implementing-background-play-picture-in-picture-in-swiftui-building-a-video-streaming-app-with-141304b84728">SwiftUI — Picture in Picture</a>).</p><pre>// MARK: - AppDelegate<br><br>// The main application delegate responsible for initializing and configuring the Flutter application.<br><br>@UIApplicationMain<br>@objc class AppDelegate: FlutterAppDelegate {<br>    override func application(<br>        _ application: UIApplication,<br>        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?<br>    ) -&gt; Bool {<br>        // Register Flutter plugins and configure AVAudioSession for audio playback.<br>        <br>        GeneratedPluginRegistrant.register(with: self)<br>        <br>        let audioSession = AVAudioSession.sharedInstance()<br>        do {<br>            try audioSession.setCategory(.playback)<br>            try audioSession.setActive(true, options: [])<br>        } catch {<br>            print(&quot;Setting category to AVAudioSessionCategoryPlayback failed.&quot;)<br>        }<br>        <br>        // Register the Flutter native view factory with the given plugin name.<br>        <br>        weak var registrar = self.registrar(forPlugin: &quot;plugin-name&quot;)<br>        <br>        let factory = FLNativeViewFactory(messenger: registrar!.messenger())<br>        self.registrar(forPlugin: &quot;&lt;plugin-name&gt;&quot;)!.register(<br>            factory,<br>            withId: &quot;swiftui_integration&quot;)<br>        <br>        return super.application(application, didFinishLaunchingWithOptions: launchOptions)<br>    }<br>}<br><br>// MARK: - FLNativeViewFactory<br><br>// The Flutter native view factory responsible for creating the native views.<br><br>class FLNativeViewFactory: NSObject, FlutterPlatformViewFactory {<br>    private var messenger: FlutterBinaryMessenger<br>    <br>    init(messenger: FlutterBinaryMessenger) {<br>        self.messenger = messenger<br>        super.init()<br>    }<br>    <br>    func create(<br>        withFrame frame: CGRect,<br>        viewIdentifier viewId: Int64,<br>        arguments args: Any?<br>    ) -&gt; FlutterPlatformView {<br>        // Create and return a new FLNativeView instance.<br>        <br>        return FLNativeView(<br>            frame: frame,<br>            viewIdentifier: viewId,<br>            arguments: args,<br>            binaryMessenger: messenger)<br>    }<br>    <br>    public func createArgsCodec() -&gt; FlutterMessageCodec &amp; NSObjectProtocol {<br>        return FlutterStandardMessageCodec.sharedInstance()<br>    }<br>}<br><br>// MARK: - FLNativeView<br><br>// The Flutter native view responsible for integrating UIKit and SwiftUI.<br><br>class FLNativeView: NSObject, FlutterPlatformView {<br>    private var _view: UIView<br>    <br>    init(<br>        frame: CGRect,<br>        viewIdentifier viewId: Int64,<br>        arguments args: Any?,<br>        binaryMessenger messenger: FlutterBinaryMessenger?<br>    ) {<br>        // Extracting parameters from Flutter arguments, <br>        // these are the parameters that are send from the Flutter code, using<br>        // &quot;creationParams&quot; parameter.<br>        if let params = args as? [String: Any] {<br>            link = params[&quot;link&quot;] as? String<br>            if let durationMillis = params[&quot;duration&quot;] as? Int {<br>                duration = TimeInterval(durationMillis) / 1000.0<br>            }<br>        }<br>        _view = UIView()<br>        super.init()<br>        // Create the native view, either UIKit or SwiftUI.<br>        createNativeView(view: _view)<br>    }<br>    <br>    func view() -&gt; UIView {<br>        return _view<br>    }<br>    <br>    func createNativeView(view _view: UIView){<br>        // Create the native view for either UIKit or SwiftUI and add it to the Flutter view.<br>        <br>        // FOR UIKIT<br>        // Uncomment the following code for UIKit integration.<br>        /*<br>        _view.backgroundColor = UIColor.blue<br>        let nativeLabel = UILabel()<br>        nativeLabel.text = &quot;Native text from iOS&quot;<br>        nativeLabel.textColor = UIColor.white<br>        nativeLabel.textAlignment = .center<br>        nativeLabel.frame = CGRect(x: 0, y: 0, width: 180, height: 48.0)<br>        _view.addSubview(nativeLabel)<br>        */<br>        <br>        // FOR SWIFTUI<br>        let keyWindows = UIApplication.shared.windows.first(where: { $0.isKeyWindow}) ?? UIApplication.shared.windows.first<br>        let topController = keyWindows?.rootViewController<br>        <br>        let vc = UIHostingController(rootView: SwiftUIView())<br>        let swiftUiView = vc.view!<br>        swiftUiView.translatesAutoresizingMaskIntoConstraints = false<br>        <br>        topController?.addChild(vc)<br>        _view.addSubview(swiftUiView)<br>        <br>        NSLayoutConstraint.activate(<br>            [<br>                swiftUiView.leadingAnchor.constraint(equalTo: _view.leadingAnchor),<br>                swiftUiView.trailingAnchor.constraint(equalTo: _view.trailingAnchor),<br>                swiftUiView.topAnchor.constraint(equalTo: _view.topAnchor),<br>                swiftUiView.bottomAnchor.constraint(equalTo:  _view.bottomAnchor)<br>            ])<br>        <br>        vc.didMove(toParent: topController)<br>    }<br>}<br><br>// MARK: - FLPlugin<br><br>// The Flutter plugin responsible for registering the FLNativeViewFactory with the FlutterPluginRegistrar.<br><br>class FLPlugin: NSObject, FlutterPlugin {<br>    public static func register(with registrar: FlutterPluginRegistrar) {<br>        let factory = FLNativeViewFactory(messenger: registrar.messenger())<br>        registrar.register(factory, withId: &quot;&lt;platform-view-type&gt;&quot;)<br>    }<br>}</pre><p>Now that we have every thing setup, lets invoke/ call the SwiftUI view from flutter.</p><pre>class FlutterPipView extends StatelessWidget {<br>  const FlutterPipView({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: SizedBox(<br>        width: Get.width,<br>        height: Get.height,<br>        child: Column(<br>          mainAxisAlignment: MainAxisAlignment.center,<br>          children: [<br>            const Text(&quot;This is done in flutter&quot;),<br>            const SizedBox(<br>              height: 10,<br>            ),<br>            ElevatedButton(<br>              onPressed: () {<br>                if (Platform.isIOS) {<br>                  Get.to(<br>                    () =&gt; const SwiftUIPipView(),<br>                  );<br>                } else {<br>                  ScaffoldMessenger.of(context).showSnackBar(const SnackBar(<br>                    content: Text(&quot;Native swift code can only be run on iOS devices.&quot;),<br>                  ));<br>                }<br>              },<br>              child: const Text(&#39;PIP-SWIFTUI&#39;),<br>            )<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>And just like that, we have successfully implemented a native SwiftUI view into our flutter app!</p><p>Integrating native SwiftUI views into Flutter applications offers a unique blend of flexibility and performance. By following the steps outlined above, you can seamlessly combine the strengths of both frameworks, providing a more tailored and efficient solution for your cross-platform development needs. As the mobile development landscape continues to evolve, exploring such integrations becomes crucial for staying at the forefront of innovation and delivering exceptional user experiences.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c81828598ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Background play & Picture-in-Picture in SwiftUI: Building a Video Streaming App with…]]></title>
            <link>https://medium.com/@afridi.khondakar/implementing-background-play-picture-in-picture-in-swiftui-building-a-video-streaming-app-with-141304b84728?source=rss-3ee2b01f5cab------2</link>
            <guid isPermaLink="false">https://medium.com/p/141304b84728</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[background-service]]></category>
            <category><![CDATA[picture-in-picture]]></category>
            <category><![CDATA[avplayer]]></category>
            <dc:creator><![CDATA[Khondakar Afridi]]></dc:creator>
            <pubDate>Sun, 03 Mar 2024 13:33:14 GMT</pubDate>
            <atom:updated>2024-03-03T13:33:14.816Z</atom:updated>
            <content:encoded><![CDATA[<h3>Implementing Background play &amp; Picture-in-Picture in SwiftUI: Building a Video Streaming App with AVPlayer and SwiftUI</h3><p>Welcome to the comprehensive guide on mastering Picture-in-Picture (PiP) and background play in SwiftUI. Where I will walk you through the process of implementing background play/services and picture in picture video playback in an SwiftUI app using AVPlayer and SwiftUI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PO2r2sDZLEptcLXzKbA3FQ.png" /></figure><h3><strong>Overview:</strong></h3><ol><li>Setting Up the Project</li><li>Integrating AVPlayer</li><li>Implementing Picture-in-Picture</li><li>Enabling Background Play</li><li>Advanced Customization</li></ol><h3>Prerequisites</h3><p>Before diving into the implementation, make sure you have a basic understanding of SwiftUI, AVPlayer, and the overall structure of a SwiftUI app. Additionally, ensure that your project has the necessary permissions in the Info.plist file to access media files and network resources.</p><p>To get started, create a new SwiftUI project in Xcode.</p><h3>Project setup and enabling PiP mode.</h3><ul><li>Add background services/ permissions — Audio, AirPlay and Picture in Picture.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nXAadCRmnzm148Pv9mO5hQ@2x.png" /></figure><ul><li>Increase deployment target to at least iOS-14.2, PiP mode is only supported on or after iOS-14.2.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dlvnBbtM0FlPzflB41Lnsg.png" /></figure><h3>Integrating AVPlayer</h3><ul><li>Lets start by creating the PlayerController.<br>The <strong>PlayerController</strong> class is designed to handle video playback using the AVKit framework in a Swift application. It includes functionalities to set up an AVPlayer, configure metadata such as title, artist, and artwork, and manage player controls.</li></ul><pre>import Foundation<br>import AVKit<br><br>class PlayerController: ObservableObject {<br>    // MARK: - Published Properties<br><br>    // Published properties to trigger UI updates when changed<br>    @Published var playbackVideoLink: String = &quot;&quot;<br>    @Published var playbackTitle: String = &quot;&quot;<br>    @Published var playbackArtist: String = &quot;&quot;<br>    @Published var playbackArtwork: String = &quot;&quot;<br><br>    // MARK: - AVPlayer and AVPlayerViewController Properties<br><br>    var player: AVPlayer?<br>    var avPlayerViewController: AVPlayerViewController = AVPlayerViewController()<br><br>    // MARK: - Initialization and Setup<br><br>    func initPlayer(<br>        title: String,<br>        link: String,<br>        artist: String,<br>        artwork: String<br>    ) {<br>        // Initialize playback properties<br>        self.playbackTitle = title<br>        self.playbackArtist = artist<br>        self.playbackArtwork = artwork<br>        self.playbackVideoLink = link<br><br>        // Setup AVPlayer and AVPlayerViewController<br>        setupPlayer()<br>        setupAVPlayerViewController()<br>    }<br><br>    // MARK: - AVPlayer Setup<br><br>    private func setupPlayer() {<br>        // Initialize AVPlayer with the provided video link<br>        player = AVPlayer(url: URL(string: playbackVideoLink)!)<br><br>        // Set up metadata for the current item<br>        setupMetadata()<br>    }<br><br>    // Set up metadata for the current AVPlayerItem<br>    private func setupMetadata() {<br>        let title = AVMutableMetadataItem()<br>        title.identifier = .commonIdentifierTitle<br>        title.value = playbackTitle as NSString<br>        title.extendedLanguageTag = &quot;und&quot;<br><br>        let artist = AVMutableMetadataItem()<br>        artist.identifier = .commonIdentifierArtist<br>        artist.value = playbackArtist as NSString<br>        artist.extendedLanguageTag = &quot;und&quot;<br><br>        let artwork = AVMutableMetadataItem()<br>        setupArtworkMetadata(artwork)<br><br>        // Set external metadata for the current AVPlayerItem<br>        player?.currentItem?.externalMetadata = [title, artist, artwork]<br>    }<br><br>    // Set up artwork metadata based on UIImage<br>    private func setupArtworkMetadata(_ artwork: AVMutableMetadataItem) {<br>        if let image = UIImage(named: &quot;Artist&quot;) {<br>            if let imageData = image.jpegData(compressionQuality: 1.0) {<br>                artwork.identifier = .commonIdentifierArtwork<br>                artwork.value = imageData as NSData<br>                artwork.dataType = kCMMetadataBaseDataType_JPEG as String<br>                artwork.extendedLanguageTag = &quot;und&quot;<br>            }<br>        }<br>    }<br><br>    // MARK: - AVPlayerViewController Setup<br><br>    private func setupAVPlayerViewController() {<br>        // Assign AVPlayer to AVPlayerViewController<br>        avPlayerViewController.player = player<br>        avPlayerViewController.allowsPictureInPicturePlayback = true<br>        avPlayerViewController.canStartPictureInPictureAutomaticallyFromInline = true<br>    }<br><br>    // MARK: - Playback Control<br><br>    // Pause the AVPlayer<br>    func pausePlayer() {<br>        player?.pause()<br>    }<br><br>    // Play the AVPlayer<br>    func playPlayer() {<br>        player?.play()<br>    }<br>}</pre><p>For styling purposed refer to the following code blocks to setup the Notification Centre, Control Centre and Lock screen media player with the proper playback meta data.</p><pre>    // Set up metadata for the current AVPlayerItem<br>    private func setupMetadata() {<br>        let title = AVMutableMetadataItem()<br>        title.identifier = .commonIdentifierTitle<br>        title.value = playbackTitle as NSString<br>        title.extendedLanguageTag = &quot;und&quot;<br><br>        let artist = AVMutableMetadataItem()<br>        artist.identifier = .commonIdentifierArtist<br>        artist.value = playbackArtist as NSString<br>        artist.extendedLanguageTag = &quot;und&quot;<br><br>        let artwork = AVMutableMetadataItem()<br>        setupArtworkMetadata(artwork)<br><br>        // Set external metadata for the current AVPlayerItem<br>        player?.currentItem?.externalMetadata = [title, artist, artwork]<br>    }<br><br>    // Set up artwork metadata based on UIImage<br>    private func setupArtworkMetadata(_ artwork: AVMutableMetadataItem) {<br>        if let image = UIImage(named: &quot;Artist&quot;) {<br>            if let imageData = image.jpegData(compressionQuality: 1.0) {<br>                artwork.identifier = .commonIdentifierArtwork<br>                artwork.value = imageData as NSData<br>                artwork.dataType = kCMMetadataBaseDataType_JPEG as String<br>                artwork.extendedLanguageTag = &quot;und&quot;<br>            }<br>        }<br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*6pvTU7T4SvMAuJWPAvTjFg.png" /></figure><p>I’m using the “Artist” local asset for the cover image, from Assets.xcassets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UFRXJ4Rk3ROWfv7x10G-Iw.png" /></figure><ul><li>Configure the VideoPlayer. <br>The VideoPlayer struct is designed to integrate the PlayerController with SwiftUI by conforming to the UIViewControllerRepresentable protocol. It acts as a bridge between the AVPlayerViewController and SwiftUI, allowing the player to be used seamlessly within SwiftUI-based user interfaces.</li></ul><pre>import Foundation<br>import SwiftUI<br>import AVKit<br><br>// A SwiftUI view wrapper for an AVPlayerViewController<br>struct VideoPlayer: UIViewControllerRepresentable {<br>    // MARK: - Observed Object<br>    <br>    // ObservedObject that manages the underlying AVPlayer and its playback state<br>    @ObservedObject var playerController: PlayerController<br>    <br>    // MARK: - UIViewControllerRepresentable Protocol Methods<br>    <br>    // Update the AVPlayerViewController when SwiftUI view updates<br>    func updateUIViewController(_ uiViewController: AVPlayerViewController, context: Context) {<br>        // Update the view controller if needed<br>        // (e.g., handle updates when the underlying AVPlayer changes)<br>    }<br>    <br>    // Create and configure the AVPlayerViewController<br>    func makeUIViewController(context: Context) -&gt; AVPlayerViewController {<br>        return playerController.avPlayerViewController<br>    }<br>}</pre><ul><li>Finally the PlayerView-UI <br>The PlayerView struct defines a SwiftUI view that incorporates the PlayerController and VideoPlayer for displaying and controlling video playback. It includes buttons for playing and pausing the video and sets up the initial state of the video player.</li></ul><pre>import Foundation<br>import SwiftUI<br><br>// A SwiftUI view representing the player interface<br>struct PlayerView: View {<br>    // StateObject that manages the player controller and its state<br>    @StateObject var playerController = PlayerController()<br><br>    var body: some View {<br>        VStack(alignment: .center) {<br>            // Use GeometryReader to adapt to the available space<br>            GeometryReader { geometry in<br>                let parentWidth = geometry.size.width<br><br>                // Display loading message if the player is not initialized yet<br>                if playerController.player == nil {<br>                    Text(&quot;Loading&quot;)<br>                } else {<br>                    // Display VideoPlayer if the player is initialized<br>                    VideoPlayer(playerController: playerController)<br>                        .frame(width: parentWidth)<br>                }<br>            }<br>            .frame(height: 200)<br><br>            // Play and Pause buttons<br>            Button {<br>                playerController.playPlayer()<br>            } label: {<br>                Text(&quot;Play video&quot;)<br>            }<br><br>            Button {<br>                playerController.pausePlayer()<br>            } label: {<br>                Text(&quot;Pause video&quot;)<br>            }<br>        }<br>        // Initialize the player on view appear<br>        .onAppear {<br>            playerController.initPlayer(<br>                title: &quot;SomeTitle&quot;,<br>                link: &quot;https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4&quot;,<br>                artist: &quot;Khondakar Afridi&quot;,<br>                artwork: &quot;Artist&quot;<br>            )<br>        }<br>    }<br>}<br><br>// Preview for PlayerView<br>#if DEBUG<br>struct PlayerView_Previews: PreviewProvider {<br>    static var previews: some View {<br>        PlayerView()<br>    }<br>}<br>#endif</pre><h3>Enabling Background Play and Services</h3><ul><li>To enable the background services, it is crucial that we modify the AppDelegate and include the appropriate AudioSession settings.</li></ul><pre>import SwiftUI<br>import SwiftData<br>import AVKit<br><br>// The main entry point of the app<br>@main<br>struct Pip_PlayerApp: App {<br>    <br>    // Application delegate adaptor to set up the custom AppDelegate<br>    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate<br>    <br>    var body: some Scene {<br>        // Main app window content<br>        WindowGroup {<br>            ContentView()<br>        }<br>    }<br>}<br><br>// Custom AppDelegate to handle application lifecycle events<br>class AppDelegate: NSObject, UIApplicationDelegate {<br>    <br>    // This method is called when the application finishes launching<br>    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -&gt; Bool {<br>        <br>        // Configure the audio session for background audio and video services<br>        <br>        let audioSession = AVAudioSession.sharedInstance()<br>        <br>        do {<br>            // Set the audio session category to playback<br>            try audioSession.setCategory(.playback)<br>            <br>            // Activate the audio session<br>            try audioSession.setActive(true, options: [])<br>        } catch {<br>            // Handle errors related to audio session setup<br>            print(&quot;Setting category to AVAudioSessionCategoryPlayback failed.&quot;)<br>        }<br>        <br>        return true<br>    }<br>}</pre><p>And Tada, just like that we have a streaming video player, with picture in picture mode, background play and an interactive media player in Notification Centre, Control Centre and on the Lock Screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*A9i9VJC6t6ALIZVELZ5jRA.gif" /></figure><h3>Conclusion</h3><p>In this article, we’ve explored the process of creating a video player app with PiP mode using AVPlayer and SwiftUI. By structuring your code with the <strong>PlayerController</strong>, <strong>VideoPlayer</strong>, and <strong>PlayerView</strong>, you can easily manage the video playback and integrate advanced features like PiP mode.</p><p>Feel free to customize the UI, enhance the controls, and incorporate additional features to make your video player app even more user-friendly. SwiftUI provides a powerful and intuitive platform for creating immersive multimedia experiences, and with the right implementation, you can offer users a seamless and enjoyable video playback experience.</p><p>Get the full source code at — <a href="https://github.com/WorkWithAfridi/PiPPlayer-SWIFTUI">https://github.com/WorkWithAfridi/PiPPlayer-SWIFTUI</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=141304b84728" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>