<?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 Muhammad Adnan on Medium]]></title>
        <description><![CDATA[Stories by Muhammad Adnan on Medium]]></description>
        <link>https://medium.com/@ak187429?source=rss-12fbddea09ec------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*inIxsrYLUB9UWV6XNShsNQ.png</url>
            <title>Stories by Muhammad Adnan on Medium</title>
            <link>https://medium.com/@ak187429?source=rss-12fbddea09ec------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 21:34:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ak187429/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[Every innovation is an idea before it turns into reality]]></title>
            <link>https://medium.com/@ak187429/every-innovation-is-an-idea-before-it-turns-into-reality-6547e47ca23f?source=rss-12fbddea09ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/6547e47ca23f</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[i̇dea]]></category>
            <category><![CDATA[3d-rendering]]></category>
            <category><![CDATA[innovation]]></category>
            <dc:creator><![CDATA[Muhammad Adnan]]></dc:creator>
            <pubDate>Fri, 24 Jan 2025 18:44:16 GMT</pubDate>
            <atom:updated>2025-01-24T19:35:46.002Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*gPFwGjrTj8TxtPtsDTdvxA.png" /></figure><p>In this short blogpost, I’ll be discussing a bug that I faced while bringing a <a href="https://pub.dev/packages/interactive_3d">3D interactive model</a> through <a href="https://google.github.io/filament/">Filament Engine</a> to Flutter and a <strong>FANTASY IDEA</strong> that I don’t know is possible, is actually a solution? could be a solution? Or a fantasy for real, means a solution might be even simpler but I don’t know about it and this idea about it is a real fantasy 😄 but I believe <strong>“Every innovation is a real fantasy idea before it turns into reality”</strong>, anyways.</p><p>Let’s explore the bug first.</p><p>Actually what happens is, first I wrote a <a href="https://github.com/AdnanKhan45/model-viewer-android">native Android app</a>, configured SurfaceView with the ModelViewer coming from Filament, adjusted other rendering stuff and ran the app. It worked like a charm, going to background (paused) state and coming back to foreground (resumed) state doesn’t affect anything in <a href="https://github.com/AdnanKhan45/model-viewer-android">native Android app</a></p><p>But, when it comes to Flutter, I connected method &amp; event channels for passing data back and forth between Android native &amp; Flutter, in this case, the ByteBuffers of asset model and its resources, configured an Android view on native side and tried loading the 3D model there and guess what? it worked, as you saw in the Demo of the plugin but NOW going to background (paused) state, the run console of Flutter shows following logs:</p><pre>E/BufferQueueProducer(20604): [ImageReader-1344x2142f22m5–20604–0](id:507c00000002,api:1,p:1576,c:20604) dequeueBuffer: BufferQueue has been abandoned</pre><p>When I come back from background (paused) state to foreground (resumed) state, the view or area where the 3D model was rendered went black and it throws:</p><pre>E/SurfaceView(20604): Exception configuring surface<br>E/SurfaceView(20604): java.lang.IllegalStateException: Calling method on destroyed Engine<br>E/SurfaceView(20604):  at com.google.android.filament.Engine.getNativeObject(Engine.java:759)<br>E/SurfaceView(20604):  at com.google.android.filament.Engine.createSwapChain(Engine.java:391)<br>E/SurfaceView(20604):  at com.google.android.filament.Engine.createSwapChain(Engine.java:369)<br>E/SurfaceView(20604):  at com.google.android.filament.utils.ModelViewer$SurfaceCallback.onNativeWindowChanged(ModelViewer.kt:390)<br>E/SurfaceView(20604):  at com.google.android.filament.android.UiHelper.createSwapChain(UiHelper.java:578)<br>E/SurfaceView(20604):  at com.google.android.filament.android.UiHelper.-$$Nest$mcreateSwapChain(Unknown Source:0)<br>E/SurfaceView(20604):  at com.google.android.filament.android.UiHelper$1.surfaceCreated(UiHelper.java:413)<br>E/SurfaceView(20604):  at android.view.SurfaceView.updateSurface(SurfaceView.java:1006)<br>E/SurfaceView(20604):  at android.view.SurfaceView.lambda$new$0$android-view-SurfaceView(SurfaceView.java:160)<br>E/SurfaceView(20604):  at android.view.SurfaceView$$ExternalSyntheticLambda5.onPreDraw(Unknown Source:2)<br>E/SurfaceView(20604):  at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:1182)<br>E/SurfaceView(20604):  at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:3633)<br>E/SurfaceView(20604):  at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:2350)<br>E/SurfaceView(20604):  at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:9194)<br>E/SurfaceView(20604):  at android.view.Choreographer$CallbackRecord.run(Choreographer.java:1231)<br>E/SurfaceView(20604):  at android.view.Choreographer$CallbackRecord.run(Choreographer.java:1239)<br>E/SurfaceView(20604):  at android.view.Choreographer.doCallbacks(Choreographer.java:899)<br>E/SurfaceView(20604):  at android.view.Choreographer.doFrame(Choreographer.java:832)<br>E/SurfaceView(20604):  at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:1214)<br>E/SurfaceView(20604):  at android.os.Handler.handleCallback(Handler.java:942)<br>E/SurfaceView(20604):  at android.os.Handler.dispatchMessage(Handler.java:99)<br>E/SurfaceView(20604):  at android.os.Looper.loopOnce(Looper.java:201)<br>E/SurfaceView(20604):  at android.os.Looper.loop(Looper.java:288)<br>E/SurfaceView(20604):  at android.app.ActivityThread.main(ActivityThread.java:7884)<br>E/SurfaceView(20604):  at java.lang.reflect.Method.invoke(Native Method)<br>E/SurfaceView(20604):  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)<br>E/SurfaceView(20604):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)</pre><p>As per my understanding and research about native android development up until now is, I can somehow conclude that this happens because the PlatformView (Flutter embedded view) lifecycle conflicts with SurfaceView lifecycle where the same SurfaceView lifecycle works perfectly fine with a native Android Activity or Fragment lifecycle. It is the common behaviour of a SurfaceView that it destroys and recreates in such backgrounding and foregrounding situations but may cause problems with Flutter embedded PlatformView.</p><p>I can achieve this by launching a completely different android Activity in Flutter and deal with the model there, but that solution is then tied to app specific and I want to build something extendable that everyone can use.</p><h4><strong>The idea:</strong></h4><p>Now, let’s discuss that fantasy idea, so, what I’m thinking is if we could create something for flutter (a widget?) that is sync with an Activity lifecycle and is a composable widget in Flutter widget tree? Because we have a PlatformView to embed it in Flutter view and then use it to display native Maps and this is composable in Flutter widget tree, if we could have something else that would work the way I’m thinking would be something great I believe. I don’t know if my assumption is right or wrong, but I think this could be a solution if there were not any.</p><p>If you’re an experienced Flutter developer, Android Developer, or iOS Developer I’d love to see your genuine feedback, because this is the only thing we improve after having some from people.</p><h4><strong>Ending:</strong></h4><p>I’m not an experienced Android developer, but I’m actively working on this bug, but if you’re experienced and you know what actually has happened wrong after having a look at the code, your contribution would be highly appreciated. I’ll add you as a contributor to this plugin if you found a solution and raised a PR.</p><p>Connect with me <a href="https://www.linkedin.com/in/muhammad-adnan-developer/">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6547e47ca23f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What’s new in Flutter 3.19 — Flutter latest release]]></title>
            <link>https://medium.com/@ak187429/whats-new-in-flutter-3-19-flutter-latest-release-a2b94c464105?source=rss-12fbddea09ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2b94c464105</guid>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[google-gemini-ai]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Muhammad Adnan]]></dc:creator>
            <pubDate>Sun, 18 Feb 2024 12:03:38 GMT</pubDate>
            <atom:updated>2024-02-18T12:03:38.206Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>What’s new in Flutter 3.19 — Flutter latest release</strong></h3><h4>Empowering App Development with Google Gemini API, Impeller Improvements, &amp; Windows Arm64 support in Flutter.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YrDqF8E3A1sCq1AGtcn_Lg.png" /></figure><p>After 3 months, the Flutter team finally stepped forward from <strong>“3.16”</strong> towards <strong>“3.19”</strong> stable release bringing so many improvements and new features in hand. <strong>In this blogpost we will try to learn and understand the latest things from visual and code examples</strong>. So, before it gets too late let’s dive in.</p><p>So, According to our friendly <a href="https://medium.com/@kevinchisholm"><strong>Kevin Chisholm</strong></a>, Flutter 3.19 brings a new Dart SDK for Gemini, a widget enabling developers to add fine-grained control to widget animations, a rendering boost with updates to Impeller, tooling to help implement deep links, Windows Arm64 support and so much more!</p><p>Watch the video or continue reading the blogpost.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FVAPulJIFQyw%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DVAPulJIFQyw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FVAPulJIFQyw%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d17e892a1d21b5400b559351b4d547d/href">https://medium.com/media/9d17e892a1d21b5400b559351b4d547d/href</a></iframe><h3><strong>AI integration into Dart SDK</strong></h3><p><strong>“The Google AI Dart SDK” </strong>and its currently in beta version, This enables you to build generative AI features into your Dart or Flutter app, powered by Gemini, Google’s latest family of AI models. You can utilize this <a href="https://pub.dev/packages/google_generative_ai"><strong>google_generative_ai</strong></a> package in the <a href="https://pub.dev/"><strong>pub_dev</strong></a> to integrate ChatBot functionality in your flutter app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2UDhUjzKq74fJVC8PupkGg.png" /></figure><p>The approach to this is very simple, using that package, a simple string prompt, and provide it to the in-built <strong>generateContent()</strong> method, and there you go. In your flutter app you can take this prompt from a text field and after it’s been submitted, call the <strong>generateContent()</strong> method and display the generated content as an AI response to build your own Text Generating ChatBot.</p><p>In order to see the following Flutter ChatBot using <a href="https://pub.dev/packages/google_generative_ai"><strong>google_generative_ai</strong></a> package, code example in action copy and paste it directly to the <a href="https://dartpad.dev/">DartPad</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f7e51c78193fbc5a911ed1670719183/href">https://medium.com/media/4f7e51c78193fbc5a911ed1670719183/href</a></iframe><h3><strong>Framework improvements &amp; features</strong></h3><h4><strong>Scrolling improvements</strong></h4><p>Previously, dragging with two fingers would actually double the scroll speed compared to using a single finger. This behavior didn’t align with native platform expectations, potentially causing confusion.</p><p><strong>Flutter 3.19</strong> steps in to fix this by making scrolling agnostic to the number of fingers used by configuring default <strong>ScrollBehavior</strong> with <strong>MultiTouchDragStrategy.latestPointer</strong>. This means you’ll get the same smooth, predictable scrolling speed regardless of whether you’re using one, two, or even more fingers.</p><p>But fear not, <strong>customization is still king in Flutter!</strong> If you preferred the old behavior, you can easily opt back in by configuring the <strong>ScrollBehavior</strong> using the <strong>MultiTouchDragStrategy.sumAllPointers</strong> option. For more info see <a href="https://docs.flutter.dev/release/breaking-changes/multi-touch-scrolling">migration guide</a>.</p><p>Other improvements on scrolling includes:</p><ul><li><strong>SingleChildScrollView</strong> <strong>and ReorderableList:</strong> Numerous bug fixes address reported crashes and unexpected behavior, ensuring these widgets scroll smoothly and reliably.</li><li><strong>Two-Dimensional Scrolling</strong>: An issue where dragging or tapping during ongoing scrolling would lead to unexpected behavior has been resolved, resulting in a more intuitive and responsive experience.</li></ul><h4><strong>Flutter AnimationStyle widget</strong></h4><p>This powerful tool, championed by community member <a href="https://github.com/TahaTesser">@TahaTesser</a>, empowers you to override the default animation behavior in various widgets like <strong>MaterialApp</strong>, <strong>ExpansionTile</strong>, and <strong>PopupMenuButton</strong>.</p><p>Here is an example where popup menu curve and transition duration is overridden:</p><pre>popUpAnimationStyle: AnimationStyle(<br>  curve: Easing.emphasizedAccelerate,<br>  duration: Durations.medium4,<br>),</pre><p>Set AnimationStyle.noAnimation to disable animation.</p><pre>   return MaterialApp(<br>      themeAnimationStyle: AnimationStyle.noAnimation,</pre><p>Checkout this <a href="https://github.com/flutter/flutter/pull/138721">pull request</a> for more info on AnimationStyle widget.</p><h4><strong>SegmentedButton.styleFrom static method</strong></h4><p>The Flutter framework introduces a new update to the <strong>SegmentedButton</strong> widget, a feature that underscores the framework’s commitment to consistency and ease of use across its UI component library. This update, contributed by Flutter community member <a href="https://github.com/AcarFurkan"><strong>@AcarFurkan</strong></a>, enriches the <strong>SegmentedButton</strong> with a new method: <strong>SegmentedButton.styleFrom</strong>. This addition harmonizes the <strong>SegmentedButton</strong> with other button types within Flutter, offering developers a familiar and streamlined way to customize button styles.</p><p>Below is the example of <strong>SegmentedButton.styleFrom</strong> static method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H0iTav7aWwk-IAt243v_dA.png" /></figure><h4><strong>Switch.adaptive constructor</strong></h4><p>In the latest Flutter 3.19 release, an intriguing update has been introduced to enhance cross-platform UI consistency and native aesthetics: the <strong>Adaptive Switch</strong>. This update is particularly noteworthy for developers aiming to deliver a seamless user experience across iOS, macOS and other platforms without leaning heavily on the Cupertino library for Apple-like UI elements. The <strong>Adaptive Switch</strong> is a Flutter widget designed to automatically adjust its appearance to match the native look and feel of the platform it runs on.</p><p>Below is the example of <strong>Switch.adaptive</strong> constructor in flutter:</p><pre>Switch.adaptive(<br>  value: _isSwitched,<br>  onChanged: (bool newValue) {<br>    setState(() {<br>      _isSwitched = newValue;<br>    });<br>  },<br>)</pre><h4>SemanticsProperties accessibility identifier</h4><p><strong>Semantics</strong> refers to the meaning or interpretation of something. In UI development, semantics pertains to conveying the meaning and purpose of UI elements to users and assistive technologies.</p><p>The new accessibility identifier added to <strong>SemanticsProperties</strong> is a game-changer for enhancing the accessibility of Flutter applications. It provides a unique identifier for each semantic node in the native accessibility hierarchy, bridging a crucial gap in accessibility features offered by Flutter.</p><p>On Android, the accessibility identifier is manifested as <strong>resource-id</strong> in the accessibility hierarchy, while on iOS, it sets the <strong>UIAccessibilityElement.accessibilityIdentifier</strong>. This deep integration with native platform accessibility features ensures that Flutter apps can leverage the existing screen readers and accessibility tools effectively, providing a seamless experience for users with disabilities.</p><h4>Implementing accessibility identifier</h4><pre>Semantics(<br>  child: YourWidget(),<br>  properties: SemanticsProperties(<br>    accessibilityIdentifier: &#39;your_unique_identifier_here&#39;,<br>  ),<br>)</pre><p>In this snippet, <strong>YourWidget</strong> is wrapped in a <strong>Semantics</strong> widget, where you specify the <strong>accessibilityIdentifier</strong> within the <strong>SemanticsProperties</strong>. This identifier should be unique to ensure that accessibility tools and testing frameworks can precisely target the semantic node.</p><h4>MaterialStatesController enhancing access to text widget state</h4><p>There’s a new feature that introduces a <strong>statesController</strong> property to <strong>TextField</strong> and <strong>TextFormField</strong> for handling <strong>MaterialState</strong> changes through a <strong>MaterialStatesController</strong>, it represents a significant advancement in how developers can interact with the state of text fields. This feature would allow for more dynamic responsiveness in UI components based on their state (e.g., focused, hovered, pressed).</p><p>Here’s an example of <strong>MaterialStatesController</strong>.</p><figure><img alt="MaterialStateController example image" src="https://cdn-images-1.medium.com/max/1024/1*XIy9R7OMSQJz9K9j_H_WbA.gif" /></figure><p>In order to see the following <strong>MaterialStatesController</strong> code example in action, copy and paste it directly to the <a href="https://dartpad.dev/">DartPad</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11407e68e69c0f14807c7497622bc763/href">https://medium.com/media/11407e68e69c0f14807c7497622bc763/href</a></iframe><h3><strong>Flutter Engine Android OpenGL</strong></h3><p>As always, Flutter this time too, brings performance improvements by updating the Flutter engine. The key points below highlights Flutter Engine Android OpenGL improvements:</p><ul><li><strong>Almost all Android devices supported: </strong>Thanks to the focus on OpenGL, Impeller now covers nearly all Android devices, extending its reach beyond Vulkan’s 77% share.</li><li><strong>MSAA for sharper visuals:</strong> The addition of Multisample Anti-Aliasing (MSAA) ensures smoother text and graphics, enhancing the visual quality of your Flutter apps.</li><li><strong>Feature parity on the horizon:</strong> While a few features like custom shaders and full external texture support are still in progress, Impeller is rapidly approaching complete functionality on both Vulkan and OpenGL backends.</li></ul><h3><strong>Android improvements</strong></h3><h4><strong>Flutter deep linking validator</strong></h4><p>A <strong>deep linking validator</strong> has been added in Flutter 3.19 for android. Deep linking is when you’re browsing a website on your phone, and you click a link that takes you directly to a specific page in a mobile app. That’s deep linking, But sometimes, setting up deep linking can be tricky and frustrating.</p><p>This is where the new <strong>Deep Link Validator</strong> comes in. It’s like a helpful assistant that checks if your deep linking setup is working correctly. No more guessing or struggling!</p><p>The current version focuses on Android specifically. It basically looks at a file called <strong>“assetlinks.json”</strong>. This file tells the system how your app handles deep link</p><p><strong>To use that Deep Link Validator</strong></p><ol><li>Open Flutter DevTools, which is a handy debugging tool for Flutter apps.</li><li>Click on the “Deep Links” tab.</li><li>Import your Flutter project with deep links set up.</li><li>The Validator checks your <strong>“assetlinks.json”</strong> file and tells you if everything is configured correctly.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UxR6eItS_HF47GNrw0UMMA.png" /></figure><h4><strong>Android default share button</strong></h4><p>The default Share button on text fields and views was previously missing from Android, but now it’s added in this release as part of the ongoing effort to ensure all the default context menu buttons are available on each platform.</p><figure><img alt="Default share button in Flutter Android image" src="https://cdn-images-1.medium.com/max/1024/1*N-y1LrYR3GWcnu_13z26hA.png" /></figure><h3><strong>iOS improvements</strong></h3><h4>Flutter iOS native fonts</h4><ul><li><strong>More natural text spacing:</strong> Flutter now aligns with Apple’s design guidelines, using a tighter spacing for larger fonts instead of the previously used, wider spacing. This creates a more compact and visually balanced appearance that’s consistent with native iOS apps.</li><li><strong>Enhanced readability:</strong> While tighter spacing might sound concerning, remember that Apple’s guidelines factor in mobile viewing distances. This subtle adjustment improves readability for larger text sizes, ensuring your content remains clear and accessible.</li><li><strong>Default behavior change:</strong> This improvement is now the default behavior for Flutter apps on iOS.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ttlNJlwXny22foKJqMGSaw.png" /></figure><h3><strong>Conclusion</strong></h3><p>There are more updates and improvements on DevTools, Windows Arm64 support, and some platforms are now deprecated in Flutter. In order to get familiar with everything checkout either <a href="https://medium.com/flutter/whats-new-in-flutter-3-19-58b1aae242d2#:~:text=Today%20we%20present%20you%20with,support%20and%20so%20much%20more!"><strong>Kevin Chisholm’s blogpost</strong></a> on Medium or <a href="https://docs.flutter.dev/release/release-notes/release-notes-3.19.0"><strong>latest release notes</strong></a><strong> </strong>on Flutter 3.19.</p><p>At the end, a <strong>very big thanks</strong> to the intelligent flutter official team and the hardworking community members who’s proving us right for choosing flutter for app development and as a professional career choice.</p><p>Thanks for being in touch with me until now, follow me in order to be updated with comprehensive flutter latest updates.</p><p>Let’s connect:</p><p>LinkedIn: <a href="https://www.linkedin.com/in/muhammad-adnan-23bb8821b/">https://www.linkedin.com/in/muhammad-adnan-23bb8821b/</a></p><p>GitHub: <a href="https://github.com/AdnanKhan45">https://github.com/AdnanKhan45</a></p><p>Instagram: <a href="https://www.instagram.com/dev.adnankhan/">https://www.instagram.com/dev.adnankhan/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2b94c464105" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter 3.13 — framework improvements]]></title>
            <link>https://medium.com/@ak187429/flutter-3-13-framework-improvements-41be37e925d8?source=rss-12fbddea09ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/41be37e925d8</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[flutterdevelopmentcompany]]></category>
            <dc:creator><![CDATA[Muhammad Adnan]]></dc:creator>
            <pubDate>Sat, 19 Aug 2023 11:11:17 GMT</pubDate>
            <atom:updated>2023-08-19T11:11:17.274Z</atom:updated>
            <content:encoded><![CDATA[<h3>Flutter 3.13 — framework improvements</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EuCX-6kNnC8Srk3YwBuZEg.png" /></figure><p>Flutter just releases new stable version 3.13, with tons of improvements &amp; features. Let’s dive in — and explore together along with code examples.</p><h3>Framework improvements</h3><p>In flutter framework they made several improvements to Material framework including:</p><ol><li>Platform adaptability</li><li>Customization options</li><li>New features &amp; capabilities</li></ol><h3>Character recognition TextField in iOS</h3><p>The on iOS TextField will now provide an automatic capability to the users to see an option to use the device camera to recognise characters and insert them into the text field</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*J-fzkm7jc2ORDimcTWRPxg.gif" /></figure><h3>Platform adaptive dialog</h3><p>A new constructor has been added to the <strong>AlertDialog</strong> widget, along with the adaptive function called <strong>showAdaptiveDialog</strong>, which display Material or Cupertino dialog that depends upon the current platform you’re using.</p><p>You can implement adaptive dialog using this code snippet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*soE8Kz-CJvCddWUE.png" /></figure><p><strong>AlertDialog.adaptive()</strong> uses <strong>AlertDialog()</strong><em> </em>on Android.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*U2i5mcqmBp8HJ90i.png" /></figure><p>and in iOS it uses <strong>CupertinoAlertDialog()</strong> internally.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WTQQe5lITvsphXPK.png" /></figure><h3>CupertinoDatePicker new mode</h3><p>Flutter team added a new mode monthYear to the CupertinoDatePicker which looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9ZjEzC9GdsFOk5Hb.png" /></figure><p>You can create your own using:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E4gdBGNbhKZSs_3O.png" /></figure><h3>CheckedStyle radio on iOS</h3><p>A new property has been added to the <strong>CupertinoRadio</strong> widget in flutter this allows the <strong>Radio.adaptive </strong>and <strong>RadioListTile.adaptive</strong> widgets to control whether they use checkmark style or the default behaviour.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZlebOx4gL2SXwF6y.png" /></figure><p>You can implement <strong>CupertinoRadio</strong> it using this code snippet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I6brNDBWjIkKVSdq.png" /></figure><p>You can implement <strong>Radio.adaptive</strong> it using this code snippet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kIwO37ziWn9eRqda.png" /></figure><p>Also you can implement <strong>RadioListTile.adaptive</strong> it using this code snippet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PlRIZuP8dMcyUdN5.png" /></figure><h3>Customization options for Material widgets</h3><ul><li>Using error widget now you can customise error widget that is shown for text fields when aren’t validated.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*z6-rrcHqiynpT-Hz.png" /></figure><p>You can implement it using this code snippet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1rc7XM-1aZ1d9Q86.png" /></figure><ul><li>Now we are allowed to add tooltips for Segment Buttons.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FgY0Vov2jTDW19_-.png" /></figure><p>You can implement it using this code snippet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EJ4MRbLnLx5kpQkC.png" /></figure><ul><li>You can now align tabs using the property alignment from TabBar widget.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ix9JM-akO-1_FKiD.png" /></figure><p>You can implement it using this code snippet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/0*2rumSOdZSVm5wjP-.png" /></figure><ul><li>Now we are also allowed to add the gap between <strong>ExpansionPanel</strong> with <strong>materialGapSize</strong> property.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QEqDQL7KN2rtu6dx.png" /></figure><p>You can implement it using this code snippet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UUU8MYDgMkeRRLgZ.png" /></figure><ul><li>For the switch button we can now customise <strong>trackOutlineWidth</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yB4tP8WS6hcYnbt3.png" /></figure><p>You can implement it using this code snippet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wwvofy6xGavNYThI.png" /></figure><ul><li>In NavigationDrawer we are now allowed to control the title padding using the property <strong>titlePadding</strong> of NavigationDrawer.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ReyAU4d_RYBHl5TK.png" /></figure><p>You can implement it using this code snippet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*HFjEUksP7y2zoLK8.png" /></figure><ul><li>You can also now customize the colour for chips in different states.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-jA1F6fGVPOUP3ET.png" /></figure><ul><li>Elevated chips has been added to Material 3. that includes <strong>FilterChip.elevated</strong>, <strong>ChoiceChip.elevated</strong>,and <strong>ActionChip.elevated</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QGrLps_Wk3i_P_DM.png" /></figure><p>So that was some customisation for Material Widgets in this new release flutter 3.13.</p><h3>onSubmitted property SearchBar</h3><p>The <strong>onSubmitted</strong> property of the <strong>SearchBar</strong> widget allows you to specify a function that will be called when the user presses the Done button on the keyboard. This function can be used to perform any action you want, such as submitting the search query to a server or opening a new screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*T89W93XCSGGm4s_R.png" /></figure><h3>AppLifeCycleListener</h3><p>AppLifecycleListener class was <a href="https://github.com/flutter/flutter/pull/123274">added</a> for listening to changes in the application lifecycle</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ohI5D84XVPReVbOS.png" /></figure><h3>TwoDimensional scrolling foundation</h3><p>The Flutter team has released the foundation for building widgets that scroll in two dimensions. This means that developers can now create widgets that can be scrolled in both the vertical and horizontal directions.</p><p>The new classes that are available for building two-dimensional scrolling widgets are:</p><ul><li><a href="https://master-api.flutter.dev/flutter/widgets/ChildVicinity-class.html"><strong>ChildVicinity</strong></a>: This class represents the relative position of a child in a two-dimensional scrolling widget.</li><li><a href="https://master-api.flutter.dev/flutter/widgets/TwoDimensionalChildDelegate-class.html"><strong>TwoDimensionalChildDelegate</strong></a>: This class is similar to the SliverChildDelegate class, but it is designed for two-dimensional scrolling widgets.</li><li><a href="https://master-api.flutter.dev/flutter/widgets/TwoDimensionalScrollView-class.html"><strong>TwoDimensionalScrollView</strong></a>: This class is an abstract base class for two-dimensional scrolling widgets.</li><li><a href="https://master-api.flutter.dev/flutter/widgets/RenderTwoDimensionalViewport-class.html"><strong>RenderTwoDimensionalViewport</strong></a>: This class is responsible for laying out the children of a two-dimensional scrolling widget.</li></ul><p>The Flutter team has also added some new interactions for two-dimensional scrolling widgets, including diagonal scrolling, see this <a href="https://master-api.flutter.dev/flutter/widgets/DiagonalDragBehavior.html"><strong>DiagonalDragBehaviour</strong></a>.</p><p>Flutter intelligent team is still working on two dimensional scrolling and they said such scrolling behaviour will be available soon on the package <strong>two_dimensional_scrollables</strong>. Until that you can take a feel from this example of two dimensional scrolling <a href="https://dartpad.dev/?id=4424936c57ed13093eb389123383e894">here on DartPad</a>.</p><h3>New slivers</h3><p>Flutter 3.13 brought us new set of slivers for dealing with new scrolling effects.</p><p><a href="https://master-api.flutter.dev/flutter/widgets/SliverMainAxisGroup-class.html"><strong>SliverMainAxisGroup</strong></a> : This sliver allows you to arrange multiple slivers together in the main axis. This can be used to create sticky headers, where the header sliver remains visible even as the other slivers scroll below it.</p><p>• <a href="https://master-api.flutter.dev/flutter/widgets/SliverCrossAxisGroup-class.html"><strong>SliverCrossAxisGroup</strong></a> : This sliver allows you to arrange multiple slivers together in the cross axis. This can be used to create side-by-side slivers, such as a list of images or a grid of buttons.</p><p>• <a href="https://master-api.flutter.dev/flutter/widgets/SliverConstrainedCrossAxis-class.html"><strong>SliverConstrainedCrossAxis</strong></a> : This sliver allows you to specify the amount of space that its child slivers are given in the cross axis. This can be used to create a layout where the child slivers are given different amounts of space.</p><p>• <a href="https://master-api.flutter.dev/flutter/widgets/SliverCrossAxisExpanded-class.html"><strong>SliverCrossAxisExpanded</strong></a> : This sliver ensures that its child slivers are given the same amount of space in the cross axis. This can be used to create a uniform layout for side-by-side slivers.</p><p>• <a href="https://master-api.flutter.dev/flutter/widgets/DecoratedSliver-class.html"><strong>DecoratedSliver</strong></a> : This sliver allows you to decorate a sliver with a Decoration. This can be used to add a background, border, or other decoration to a sliver.</p><p>Take a look <a href="https://dartpad.dev/?id=6e2b7245063001576a3a83adb23f1121">on this DartPad</a> example where you can see these Slivers in action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/0*Y1gzVwWXMbRCv4vu.png" /></figure><h3>IconButton isSelected</h3><p>This is an accessibility feature. If the isSelected property was null so the IconButton will behave as a normal button but if is specified and its selectedIcon is also specified this will make your app more accessible. But remember this will only work when you have useMaterial3 true in your MaterialApp.</p><p>You can implement it using:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mSyNkRfMEJ3yMgD1.png" /></figure><h3>Conclusion</h3><p>There are more improvements on Flutter apps performance, platforms, DevTools and Games in flutter 3.13. For more info watch <a href="https://youtu.be/Wq83PdOkzow">my video on YouTube</a> or head over to <a href="https://medium.com/flutter/whats-new-in-flutter-3-13-479d9b11df4d">Kevin Chisholm blog post</a> on medium.</p><p>Flutter 3.13 is available in stable, and also includes <a href="https://medium.com/dartlang/a1f4b3a7cdda/">Dart 3.1</a>. To get started with these newest updates, all it takes is a <a href="https://docs.flutter.dev/release/upgrade">flutter upgrade</a></p><p>To see the full list of PRs for this release head on over the <a href="https://docs.flutter.dev/release/release-notes">release notes and change log</a> section for this release.</p><p>See you soon! until that Happy Fluttering 💙.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41be37e925d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Keys in Flutter — Dive Deep]]></title>
            <link>https://medium.com/etechviral/keys-in-flutter-dive-deep-8996c1b6086a?source=rss-12fbddea09ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/8996c1b6086a</guid>
            <category><![CDATA[googleio]]></category>
            <category><![CDATA[flutterio]]></category>
            <category><![CDATA[google-developer-expert]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[google]]></category>
            <dc:creator><![CDATA[Muhammad Adnan]]></dc:creator>
            <pubDate>Wed, 26 Jul 2023 13:40:55 GMT</pubDate>
            <atom:updated>2025-06-25T07:01:01.170Z</atom:updated>
            <content:encoded><![CDATA[<h3>Keys in Flutter — Dive Deep</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zvybhNrow2lZhdHw_K_u1Q.png" /></figure><p>Did you ever use keys to unlock a door ? I know the answer, is, <strong>“YES”</strong>. Today we will use keys to unlock Flutter widgets. You may have definitely seen this poor Key object, every time when you create a stateless or stateful widget.</p><figure><img alt="Key Object — Keys in Flutter" src="https://cdn-images-1.medium.com/max/1024/1*EKHBGwwlJ4f-drhX43YJpQ.png" /></figure><p>But, what that <strong>“THING”</strong> key actually means? is that any secret key to unlock a door, sorry I mean a <strong>“widget”</strong>? Exactly. Key in flutter is used to uniquely identify widgets in the widget tree and helps flutter keep track of them when they are added, removed, or rearranged in a user interface.</p><p>Watch Video or continue reading</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FGIXTi6-N1Mc%3Fstart%3D249%26feature%3Doembed%26start%3D249&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DGIXTi6-N1Mc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FGIXTi6-N1Mc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fb23d68544add4faf93e3b8817c825b/href">https://medium.com/media/9fb23d68544add4faf93e3b8817c825b/href</a></iframe><h3>When do we use keys ?</h3><p>Well, most of the time we don’t, but they can be used to preserve state when widgets move around in the widget tree.</p><figure><img alt="ReorderableListView — Keys in Flutter" src="https://cdn-images-1.medium.com/max/793/1*CIfqiLCs4wKUVHCag0m8wQ.gif" /></figure><p>In this example, of a simple todo app, reordering the todo based on the priority, and remove when it’s done, <strong>the keys here are very important</strong>. Here, when items are reordered, Flutter needs to determine which TodoItem widget need to be updated with new position. The unique keys of each TodoItem widgets enables Flutter to recognize that each TodoItem has its own identity. Since each TodoItem widget has a unique key, Flutter can efficiently update the positions of the widgets in the widget tree, maintaining individual states during reordering. This prevents state loss and ensures that the TodoItem remain their correct state even after the reordering.</p><p>And that’s it, that’s all what you need to know when to use keys.</p><p><strong>But “we’re confused developers, we cannot get sigh! unitl we reach to the deep of a anything we’re exploring and understand what’s actually happening under the hood”</strong></p><blockquote>Be confused, it’s where you begin to learn new things — S.C Lourie</blockquote><h3>Keys under the hood</h3><p>To understand keys under the hood look at this very simple app below, where we have 2 count values, and a “swap” button. “And you definitely know what will happens when is clicked 😄”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*I_0hJpuyNL4Zq79d2E2uIQ.gif" /></figure><p>And here’s the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/918a539bf14f97a6164d5b19ae1dfe89/href">https://medium.com/media/918a539bf14f97a6164d5b19ae1dfe89/href</a></iframe><p>In the code, we have a stateful widget <strong>NumbersApp</strong> which constructs 2 stateless widgets of StatefulNumber, in the Column children. And when the swap Elevated button is tapped, it swap between two numbers. and it works fine, BUT the magic really starts to happen when we change the StatefulNumber to the StatefulNumber.</p><pre>  @override<br>  void initState() {<br>    children = [<br>      StatefulNumber(),<br>      StatefulNumber(),<br>    ];<br>    super.initState();<br>  }</pre><p>This time the number will be stored in the state of the stateful StatefulNumber.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*Rbwseb40Hzt2iYN5ktkN-Q.gif" /></figure><p>We’re firing off the swap button like a gun trigger but no swaps seems to be happening.</p><p>But if we add UniqueKey() to each StatefulNumber widgets, everything starts working as it was before.</p><pre>@override<br>  void initState() {<br>    children = [<br>      StatefulNumber(key: UniqueKey()),<br>      StatefulNumber(key: UniqueKey()),<br>    ];<br>    super.initState();<br>  }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*RD0v9vGUtfUO0sFqAT0w7w.gif" /></figure><p><strong>Note: in case of dealing with stateless widgets we don’t need any kind of keys, but instead we directly deal with type and perform necessary updates for swapping.</strong></p><p>However, there are some cases where you might want to use keys with stateless widgets. For example, if you are using a stateless widget in a list, you might want to use a key to track the position of the widget in the list. This can be useful if you need to update the widget’s state based on its position in the list.</p><p>In general, you should only use keys with stateless widgets if you need to track the widget’s identity or position. If you don’t need to do either of these things, then you can safely omit the key.</p><p>Now I’m going to reveal a cutest face of flutter under the hood, which could form goose bumps on newbie flutter devs. But hey! you don’t need to worry because <strong>“I’m here”</strong> to explain everything, Yes, almost <strong>“EVERYTHING”</strong>.</p><p><strong>Happy Trees Day.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/185/1*kt4fIXliWGd9mSOO8y56Ww.gif" /></figure><p>Oh, sorry that’s too much! I was about to show you this structure you can see below:</p><figure><img alt="Flutter Tree — Keys in Flutter" src="https://cdn-images-1.medium.com/max/1024/1*c98k6VGes6gEjLcwwshBQg.png" /></figure><p>If this sound abstract to you, then you might have missed something. Such as learning <strong>“how flutter render widgets”</strong> ? But there’s no need to worry, you can either watch <a href="https://youtu.be/Wz8dLNtMcbQ">my video</a> on <strong>YouTube</strong> or read <a href="https://medium.com/@ak187429/how-flutter-works-under-the-hood-519b2441fb6a">my blog post </a>on <strong>Medium</strong>.</p><h4>In case of stateless widgets</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OO8AxofjbM68EK05sChwpw.png" /></figure><p>So, now I assume you know what is tree structure and how flutter use it to render widgets, Let’s start from where we had Stateless widgets for swapping. <strong>Flutter</strong> builds the corresponding elements for each widget in the widget tree and this tree is called an element tree.</p><p><strong>Widgets</strong> are itself immutable, and are just configurations that how the UI should look like, and the corresponding <strong>Elements</strong> are responsible for keeping the information about the specific type of widget and reference to children elements same as we have in the widget tree.</p><p>And to lookup additional information, the <strong>Elements</strong> in the <strong>Element</strong> <strong>tree</strong> references to the original widgets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4JQOVsJZ-dVUxqMH7xWRlw.png" /></figure><p>When the widgets swaps, <strong>Flutter</strong> <strong>framework</strong> checks through <strong>Element</strong> tree, It starts checking in our case the <strong>Column</strong> <strong>Element</strong> and then move to it’s children, here the element tree will call this method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bY2MvQ_MfSJmA0K3aO-bnw.png" /></figure><p>Checking for the type and the keys, to accordingly update <a href="https://api.flutter.dev/flutter/rendering/RenderObject-class.html"><strong>renderObjects</strong></a> to display a new updated result on the UI, in this case we don’t have any keys so it will ignore keys, and the widget that is just swapped is of same type, then it will check the same for the second child, and nothing was destroyed and recreated but just little updates happens when the swap button was clicked.</p><h4>In case of statelful widgets</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2h12n8TweCogIacNy9k4FQ.png" /></figure><p>Now, everything remain the same but in case of <strong>stateful widgets</strong>, we will introduce a pair of <strong>state</strong> with each element. And this time the number is stored in the state, instead of the widget itself. So when the widgets swaps, again<strong> </strong>canUpdate method was called. And the process starts from the <strong>Column</strong> <strong>Element</strong> to it’s children and checks for the types and keys and yet we don’t have keys again so it doesn’t matter in this case also, so it checks first child, type is same <strong>“Yes”</strong> for the second child <strong>“Absoloutely”.</strong></p><p><strong>Note: Flutter framework uses the Elemet tree and it’s corresponding state to determine what to display on the UI, so in our case the state remain unchanged and we didn’t get any result on swap on the UI, which means our widgets didn’t swapped properly.</strong></p><h4>In case of statelful widgets with keys</h4><p>This time, if we add UniqueKey() to each <strong>stateful widgets</strong> (StatefulNumber), and swaps the widgets, again the canUpdate() method knows its job. The process starts, for the parent widget everything remain the same, and for the children looking for the runtimeTypes yes both are the same without any doubt… BUT wait, the keys aren’t same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KTjEXc3kX7Y7OKkGeMomaQ.png" /></figure><p>So, in that case what flutter does is to deactivate the elements references, and again starts checking for the correct match, for the Column again everything remain the same, and the first child widget doesn’t match because this is the one because of which the references were deactivated on swap, now the <strong>flutter</strong> <strong>framework</strong> will looks for other non-matched children for the element with a corresponding key, so yes it gots the key matched and updates it’s reference to the corresponding key widget, and the same for the other child.</p><p>So, becuase of keys, when swap happens we got what we expected to see on the screen.</p><h3>where to specify keys?</h3><p>Keep in mind, always put keys at the outermost stateful widget that you want to preserve state for. This is because keys are used by <strong>Flutter</strong> to identify individual widgets in a widget tree, and if you only put a key on a child widget, <strong>Flutter</strong> will not be able to track the state of the parent widget.</p><p>And if you think we’re talking about the state of our first stateful widget that we have for swap, So, its, not like that. Because, when we wrap StatefulNumber widgets having UniqueKey in their constructor with a Container widget.</p><pre>@override<br>void initState() {<br>  children = [<br>   Container(child: StatefulNumber(key: UniqueKey())),<br>   Container(child: StatefulNumber(key: UniqueKey())),<br>  ];<br>  super.initState();<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*VzPrYnpp6upG4tzOUIMEhA.gif" /></figure><p>now if we swap the widgets, now it’s generating random numbers on each swap, what’s wrong with this?</p><p>Well, Let’s look at the tree structure.</p><p>So, initially our widget tree looks something like this with the Container added on top of the StatefulNumber widgets within the keys in their constructor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XmR9BMccMi9RX107y1UBnA.png" /></figure><p>Now when we swap two StatefulNumber widgets, the <strong>Flutter</strong> <strong>element-to-widget matching algorithm,</strong> looks at one level of the tree at the time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tTRBgSk0IVR_pbEeWoGS1w.png" /></figure><p>in that first level of the children everything mateches correctly, and in the second level , the widgets key didn’t match, and the element connection is deactivated.</p><p><strong>Because when you use a local key in a child widget, it will not be used to match the widget to an element in the parent widget. This is because Flutter only looks for keys that match in the same level of the tree.</strong></p><p>And, flutter framework didn’t find the StatefulNumber element at that level with that key value.</p><p>As a result, when you rebuild, the Containerwidget will be recreated, and the UniqueKey of the StatefulNumber widget will be different. This is why the numbers start generating randomly when you add the Container widget.</p><p>And same thing will happen for the other child.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ss4Xr2rZSGgDw9aY9y03g.png" /></figure><p>Now adding the keys to the level of the Container widget, this will solve our problem. This time, as flutter looks at one level of the tree at the time and notice where’s the problem, so everything works perfectly in this case and smoothly the swap happens same as previously happened.</p><h3>Types of keys</h3><p>Flutter has several different kinds of keys which can be used according the data we’re preserving.</p><h4>Unique Keys</h4><p>When you have a situation where you have collection of widgets and you want to ensure each widget must distinct from each other, You can use unique key.</p><p>The unique key is also used in our example app beacause we don’t have any constant data in our widgets. And while constructing widgets we didn’t know what the generated number would be.</p><h4>Object Keys</h4><p>When dealing with more complex combination of data, such as with a social media feed app where each post is represented by a Post object and users can like, comment, and share posts, it’s important to efficiently maintain the state of individual posts, and update the UI correctly when new posts are added, existing posts are modified, or the feed is refreshed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tYOgPfBcZGr5EDV8A-uuYA.png" /></figure><p>In this scenario, ObjectKey() uniquely identifies each post in the feed, even if objects have the same description, number of likes, and other fields. The ObjectKey makes each post different from others.</p><h4>Value Keys</h4><p>It is useful when the identity of the object is not based on its memory reference like the ObjectKey, but on a specific attribute or property of the object. for example in the Todo App, let’s say we want the text of todo item must be unique and different from others, so here we can use a ValueKey because the text is a value, an attribute of the Todo object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XIVwqzFYSdIeuq9Oes0Cmg.png" /></figure><h4>Global Keys</h4><p>The GlobalKey is a key that allows you to access the state and properties of a specific widget from anywhere in your application, not just its parent.</p><p>such as in cases involving form validation or managing state in a complex widget tree. We need a global key.</p><p>For example We want to perform form validation and display error messages for each field. To achieve this, we’ll use GlobalKey to access the form&#39;s state and validate its fields from different parts of the app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eHGbpSlLqjU39JE9IBSqYw.png" /></figure><h4>PageStorage Keys</h4><p>PageStorage Keys are the special keys that are used to persist the user scroll location.</p><h3>Summary</h3><p>The type of key that you use will depend on the specific situation. If you need to uniquely identify a widget and preserve its state, then you should use a UniqueKey. If you need to uniquely identify a widget based on its object identity, then you should use an ObjectKey. If you need to uniquely identify a widget based on its value, then you should use a ValueKey. And if you need to uniquely identify a widget globally, then you should use a GlobalKey. And finally use PageStorageKeywhen you want to persist user scroll location in a scrollable view.</p><p>Learn everything about Flutter at → <a href="https://flutter.dev/">https://flutter.dev</a></p><p>Let’s connect:</p><p>LinkedIn: <a href="https://www.linkedin.com/in/muhammad-adnan-23bb8821b/">https://www.linkedin.com/in/muhammad-adnan-23bb8821b/</a></p><p>GitHub: <a href="https://github.com/AdnanKhan45">https://github.com/AdnanKhan45</a></p><p>Instagram: <a href="https://www.instagram.com/dev.adnankhan/">https://www.instagram.com/dev.adnankhan/</a></p><p>YouTube: <a href="https://youtube.com/@eTechViral">https://youtube.com/@eTechViral</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8996c1b6086a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/etechviral/keys-in-flutter-dive-deep-8996c1b6086a">Keys in Flutter — Dive Deep</a> was originally published in <a href="https://medium.com/etechviral">ETechViral</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn how Flutter render widgets]]></title>
            <link>https://medium.com/@ak187429/how-flutter-works-under-the-hood-519b2441fb6a?source=rss-12fbddea09ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/519b2441fb6a</guid>
            <category><![CDATA[rendering]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[widgets-in-flutter]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[google]]></category>
            <dc:creator><![CDATA[Muhammad Adnan]]></dc:creator>
            <pubDate>Sun, 09 Jul 2023 14:11:18 GMT</pubDate>
            <atom:updated>2023-07-09T15:17:36.624Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K_ZU_FxAVr6XburvRUQQ9g.png" /></figure><p>If you have ever worked with other frameworks, and then you become a Flutter guy. There might always be a question in your head that <strong>“how flutter rendering is so fast?”</strong>. You’ll be leaving this blog post reading the last line with a statement in mind “<strong>Oh that is why flutter renders so fast”</strong>. Do you want to know how everything is done under the hood? Next line is waiting for you to read. Let’s go for it.</p><p>Watch the video or continue reading blog post.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FWz8dLNtMcbQ%3Fstart%3D92%26feature%3Doembed%26start%3D92&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DWz8dLNtMcbQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FWz8dLNtMcbQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/28af27aac2b8082d9aec6f3099861094/href">https://medium.com/media/28af27aac2b8082d9aec6f3099861094/href</a></iframe><p>I’m going to tell you a short story which you may definitely have heard in your flutter development journey.</p><p><strong>“Everything in Flutter is a Widget”.</strong></p><p>And which is undeniably true, <strong>“Everything in Flutter is a Widget”</strong>. But as you walk with flutter, our friend <a href="https://docs.flutter.dev/dash"><strong>Dash</strong></a> will tell you, hey! Look at this in the <a href="https://flutter.dev/">documentation</a> of flutter is saying:</p><p><strong>“Widget is an immutable description of a part of a user interface”.</strong></p><p>Oh wait, are you serious? How are UI Widgets immutable ? Yes, they are immutable as in Widget implementation see the <strong><em>@immutable</em></strong>.</p><figure><img alt="Widget class" src="https://cdn-images-1.medium.com/max/1024/1*7pCWFD3HY1CwnvtA3vhkFA.png" /></figure><p>Now, you might say well, if widgets are immutable. Then how does flutter manage the state of UI ? How does it actually represent any changes ?</p><figure><img alt="How gif" src="https://cdn-images-1.medium.com/max/220/1*Kq_Sa-R5XJfRbRpOTaSzFQ.gif" /></figure><p>Let me tell you, flutter has the concept of <strong>trees</strong>. It does not have only one single widget tree. But there is something more than just a widget tree.</p><p>Flutter uses 3 parallel trees for rendering, which together and contribute to the performance of Flutter apps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e4JNijI6T53ClJ797TNXDQ.png" /></figure><p>Let’s decode these trees.</p><h4><strong>Widget Tree (configure)</strong></h4><p>A widget in a widget tree represents the UI structure and configuration. In flutter we declaratively define and configure widgets, meaning that we decide how they are going to look like on the UI and they are hierarchically forming a Widget Tree, divided into parent and children.</p><h4><strong>Element Tree (manage)</strong></h4><p>An element is a corresponding Widget’s Element in the element tree created by flutter framework. An Element is Instantiation of a Widget at a particular location in the tree. A mutable piece of the tree. It manages updates, changes of the UI, and controls everything. You can think of it, it’s managing the life cycle of widgets.</p><h4><strong>Render Object Tree (paint)</strong></h4><p>A render object in Render Object Tree is responsible for the final painting of widgets on the UI. It defines how elements are visually represented on the screen. It handles layout, painting, size, and hit testing.</p><p>These three concepts, configure, manage, and paint. They map really nicely into the separation of concern that flutter has between Widgets, Elements, and RenderObjects.</p><h4><strong>Example Tree</strong></h4><p>Now, you know what each tree job is, the <strong>Widget Tree</strong> just describes how the UI should look based on the current state, the <strong>Element</strong> Tree responsible for handling updates and lifecycle, and finally The <strong>Render Object Tree</strong> is responsible for the final painting.</p><p>Let’s look at an example:</p><pre>Padding(<br>   padding: EdgeInsets.all(10),<br>   child: Text(&quot;Hello World&quot;),<br> );</pre><p>This is a really simple example of Padding, all it does is to give padding to its child Text widget.</p><p>Let’s see how it is going to look in tree format.</p><figure><img alt="Padding Example Tree" src="https://cdn-images-1.medium.com/max/1024/1*Mq3Z_QGWqynx0a13ZUYtfg.png" /></figure><h4><strong>Let’s dive deep (and see how trees are actually created)</strong></h4><p>We have again a super simple app which runs and results in a simple “Hello World” on the screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bA80r_-lggmQYvYaIb2CAw.png" /></figure><p>Initially the trees look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wIhG7TnaPXyV8wqYCT_ZhA.png" /></figure><p>In flutter, when an app starts in the <strong>main()</strong> function, it calls the <strong>runApp(app)</strong> with a widget, making it the root of the widget tree. Then the next thing happens is, the widget asks the framework to create the element, then finally the element then asks the framework to create the render object for the final painting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8BWEylyQeqaDUUTBDIIm0Q.png" /></figure><p>We have a <strong>LeafRenderObjectElement</strong> and that is the name of the element for the <strong>Text</strong> or a <strong>RichText</strong> widget, and we have a <strong>RenderParagraph</strong> which is the name of Render Object for the same <strong>Text</strong> and <strong>RichText</strong>.</p><p><strong>Note: Different widget might have different names of Elements and their Render Objects.</strong></p><p>Now, the final tree structure will looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ydmT6jO8KapfQzGsTsj5gQ.png" /></figure><p>Now, you might still be asking yourself, why do we have three trees while one can easily be acceptable and doing so much work for getting a small thing on the screen? So.</p><h4><strong>The magic starts to happen (when things changes)</strong></h4><p>What if the state changes in the trees? And the text inside the Text widget changes ? What would happen with the three parallel trees?</p><p>Let’s see one more example:</p><p>Here, we run the <strong>runApp</strong> twice just for testing and then what happens is the first runApp creates the first Text widget and the second <strong>runApp</strong> creates a new Text widget with different text. And after running we see the second text on the screen, but how is it actually rendered ?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9M7evWnUKEoaKMOAilj9MA.png" /></figure><p>So let’s go examine the widget tree and see what has happened when it was rendering.</p><p>When the first <strong>runApp</strong> was called, we got the first app Text rendered on the UI. And the 2nd <strong>runApp</strong> is called, a new widget pops up on to the root, and now the flutter framework will be like “what I’m gonna do in this situation? I already have created <strong>elements</strong> and <strong>renderObjects</strong>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*T1g8-Wd-mclDrWQGjbG4eQ.png" /></figure><p>So this time the flutter framework is not going to destroy and recreate anything, but elements and renderObjects will do some work around and look what I can reuse and what I can replace?</p><p>In that case, the framework will call <strong>canUpdate()</strong> method first, which is comparing <strong>oldWidget</strong> with <strong>newWidget</strong> based on their <strong>runtimeType</strong> and keys.</p><p><strong>Note: we’re not dealing with the keys, so it doesn’t matter in case of keys.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GWZ7qevQYyFamgIuNHtP9w.png" /></figure><p>If the <strong>runtimeType</strong> was the same, the widget will be replaced with the same widget. Then, Element will call this <strong>updateRenderObject()</strong> method which is similar to above <strong>createRenderObject()</strong> but the only difference is that it is taking the existing values and updating the values inside it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zu3cVRYOMu1lHVExIRZQzQ.png" /></figure><p>After the <strong>updateRenderObject()</strong> has been called on <strong>RenderParagraph</strong> the Text widget content will be updated and rendered on the screen. And the tree structure will become:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BJsZpLRYN8HFuQQ7F6qOmQ.png" /></figure><p>But what if the <strong>runtimeType</strong> was not the same? Yes, correct, it will destroy the existing Widget and recreate it from scratch. Because two different widgets with different <strong>runtimeTypes</strong> have different <strong>Elements</strong> and <strong>RenderObjects</strong>, they cannot be replaced and reused but will be destroyed and recreated.</p><h4><strong>Did you see that?</strong></h4><p>We were not destroying and recreating the whole tree but we’re swapping immutable widgets with one another and so updating the UI, and that is the secret behind the performant apps and fast rendering in flutter <strong><em>“and that is why we have parallel trees”</em></strong>. We do not destroy anything but instead perform reconciliation comparing oldWidget with newWidget based on their runtimeTypes and keys and… accordingly updating the widgets.</p><h4><strong>Code Example</strong></h4><p>This is a very simple app, where we have a stateful widget with a boolean switch and 3 getters (<strong>firstTree</strong>, <strong>secondTree</strong>, and a <strong>button</strong>). When the button is tapped it switches between the trees and in both trees for now we have the same widgets (<strong>Row</strong>, <strong>Text</strong>, <strong>SizedBox</strong>) but the only difference is the Text content is different.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ee4970c491b6e2b242daf585bd084a5/href">https://medium.com/media/6ee4970c491b6e2b242daf585bd084a5/href</a></iframe><p>Run the app and Run the <strong>Flutter DevTools</strong> for examining the widget tree.</p><p>Go to the tab <strong>Flutter Inspector</strong> and click the Row in the <strong>Widget Tree</strong> on the Left tab, and click the <strong>Widget Details Tree</strong> on the Right tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c6wFTuU8k9Y8DIf_KZyTuA.png" /></figure><p>On right tab, you will find every widget has a render object id represented as <strong>renderObject#ab123 </strong>something like that.</p><p>When we first run the app <strong>widget tree details</strong> looks something like this:</p><p><strong>Note: “Dart is awesome ❤” text content.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qozy6z6Citfj0WFOnbzhyA.png" /></figure><p>Next, when switch button was clicked, it looks like this now:</p><p><strong>See: “Dart is awesome ❤” is changed to “Flutter is awesome ❤”.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_tosbT_GVWQkH9-m8pMUUw.png" /></figure><p>If you compare two image’s <strong>renderObject</strong> ids, you will find <strong>NO DIFFERENCE</strong>. Everything is the same as it was before, which means nothing is destroyed, not recreated but just replaced and some updates take place.</p><p><strong>What if?</strong> We change the second tree’s <strong>SizedBox</strong> to a <strong>Padding</strong> ? like this:</p><pre>Widget get secondTree =&gt; Row(<br> mainAxisAlignment: MainAxisAlignment.center,<br> children: [<br>   Text(&quot;Dart is awesome &lt;3&quot;, style: TextStyle(fontSize: 35),),<br>   Padding(padding: EdgeInsets.only(right: 10),),<br> ],<br>);</pre><p>Now, restart the app and refresh the <strong>Widget Tree</strong> and, you will see the <strong>Widget Details Tree</strong> like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t1voA-LECuut5SvfMiLapw.png" /></figure><p>The <strong>SizedBox</strong> widget is completely destroyed and a new <strong>Padding</strong> widget is created with a different <strong>renderObject id</strong>. Because again, both widgets are different and thus, have different Element and Render Objects which cannot be replaced and reused but rather can be recreated after being destroyed.</p><p>Now what do you think? If we click back on the switch button what will happen? Absolutely right! This time the Padding widget will be destroyed and a new SizedBox will be created with a different renderObject id.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*crFw7zLhmtzqFkODlBEQEQ.png" /></figure><p>And make sure you take a look at other widgets such as Text and Row both have the same renderObject ids. <strong>AND THAT IS HOW EVERYTHING HAPPENS <em>“UNDER THE HOOD”</em></strong><em>.</em></p><h4><strong>Conclusion</strong></h4><p>In conclusion, Flutter’s fast rendering capabilities can be attributed to its efficient management of the three parallel trees: Widget Tree, Element Tree, and Render Object Tree. Understanding how these trees interact and contribute to the performance and because of these trees Flutter can efficiently update and replace immutable widgets when some changes occur, without the need for full tree reconstruction.</p><p>With this understanding, you can now appreciate why Flutter’s rendering is so fast, enabling you to build performant and delightful user experiences.</p><p>Let’s connect:</p><p>LinkedIn: <a href="https://www.linkedin.com/in/muhammad-adnan-23bb8821b/">https://www.linkedin.com/in/muhammad-adnan-23bb8821b/</a></p><p>GitHub: <a href="https://github.com/AdnanKhan45">https://github.com/AdnanKhan45</a></p><p>Instagram: <a href="https://www.instagram.com/dev.adnankhan/">https://www.instagram.com/dev.adnankhan/</a></p><p>YouTube: <a href="https://youtube.com/@eTechViral">https://youtube.com/@eTechViral</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=519b2441fb6a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Schedule Cloud Functions with Cloud Tasks (Event Scheduling) Part 2]]></title>
            <link>https://medium.com/@ak187429/schedule-cloud-functions-with-cloud-tasks-event-scheduling-part-2-2d22a5fcab80?source=rss-12fbddea09ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d22a5fcab80</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[cloud-tasks]]></category>
            <category><![CDATA[event-schedule]]></category>
            <category><![CDATA[google-cloud]]></category>
            <dc:creator><![CDATA[Muhammad Adnan]]></dc:creator>
            <pubDate>Tue, 13 Jun 2023 17:55:40 GMT</pubDate>
            <atom:updated>2023-06-13T18:07:13.477Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*eE5U9mejMeG3ZgJr4RwCjg.png" /></figure><p>Hey, welcome to <strong>Part 2</strong> of Scheduling Cloud Function with Cloud Tasks. I hope you have read my first article. If not, it will be hard for you to figure out code and other stuff here. I would recommend reading the <strong>first one</strong> where we step by step go through each and every little thing related to <strong>Cloud Tasks</strong>, from initial understanding and setting up, to final handling security issues we have covered everything, so make sure you check that out.</p><p><a href="https://medium.com/@ak187429/enablschedule-cloud-functions-with-cloud-tasks-for-document-ttl-part-1-2c110f0576cd"><strong>Link to first article</strong></a><strong>.</strong></p><p>In this article I will assume you know everything that we learned in <a href="https://medium.com/@ak187429/enablschedule-cloud-functions-with-cloud-tasks-for-document-ttl-part-1-2c110f0576cd"><strong>Part 1</strong></a>. So let’s get started.</p><h4><strong>The problem</strong></h4><p>Build an event scheduling system that will respond in UI to show an event box in different areas of the app, when the status of the event changes at the scheduled times.</p><h4><strong>Event model</strong></h4><p>In event model we’re going to have some fields that will be <strong>“startEventTime”</strong>, <strong>“endEventTime”</strong>, <strong>“eventStatus”</strong>, and ofcourse an <strong>“eventId”.</strong></p><h4><strong>Event Status Changes Scenario</strong></h4><p>create string constants <strong>“inProgress”</strong>, <strong>“started”</strong>, <strong>“almostStarted”</strong>, <strong>“ended”</strong>, <strong>“canceled”</strong> in your app, that will be the statuses of the event. By utilizing statuses write some get methods of the database you’re using it could be Firestore, and show them up on the specified status of the event.</p><p>Event status will be updated to <strong>“almostStarted”</strong> when there’s 30 minutes remaining from starting the event and same for others when <strong>“started”</strong> and <strong>“ended”</strong>. And if no Cloud Task has been dispatched yet the status will be <strong>“inProgress”</strong>. And ofcourse, you are right, you can cancel the event 😀.</p><p>You can show up events on different areas of your app by running a <strong>“where”</strong> query in firestore and say where the<strong> “eventStatus”</strong> isEqualTo <strong>“started”</strong> show all the started events here, and also same for other event status.</p><p>Code example in Flutter:</p><pre>Stream&lt;List&lt;EventEntity&gt;&gt; getStartedEvents() {<br>   final eventCollection = fireStore.collection(events);<br>   return eventCollection.where(“eventStatus”, isEqualTo: “started”).snapshots().map((querySnapshot) =&gt; querySnapshot.docs.map((e) =&gt; EventModel.fromSnapshot(e).toList());<br>}</pre><h4><strong>When event is created</strong></h4><p>When event is created in the events collection, with the specified <strong>startEventTime</strong> and <strong>endEventTime</strong>. We will schedule 3 tasks in the queue for a single event. First task in the queue will be dispatched 30 minutes before starting the event, and will update the <strong>eventStatus</strong> to almostStarted. Second task in the queue will be dispatched when the event is finally <strong>started</strong>, and will update the eventStatus to started. And the same for <strong>endEventTime</strong> when end time arrives.</p><h3><strong>Back to Cloud Functions</strong></h3><p>I’m assuming again you have everything set up, if not, you might definitely have missed <a href="https://medium.com/@ak187429/enablschedule-cloud-functions-with-cloud-tasks-for-document-ttl-part-1-2c110f0576cd"><strong>Part 1</strong></a> so I’d recommend reading this<strong> </strong>then it will be easy for you to figure out what is going on here.</p><h4><strong>Event Scheduling OnCreate Trigger</strong></h4><p>Import these:</p><pre>import * as functions from &#39;firebase-functions&#39;<br>import * as admin from &#39;firebase-admin&#39;<br>const { CloudTasksClient } = require(&#39;@google-cloud/tasks&#39;)<br>import { OAuth2Client } from “google-auth-library”;</pre><p>Initialize Firebase admin:</p><pre>admin.initializeApp()</pre><p>We will again start from the onCreateEvent trigger.</p><pre>export const onCreateEvent = functions.firestore.document(&#39;/events/{eventId}&#39;).onCreate(async snapshot =&gt; {<br><br>    // Access event data<br>    const event = snapshot.data(); <br>    const eventId = snapshot.id;<br><br>    // Get start and end time in milliseconds<br>    const start = event.startEventTime.toMillis();<br>    const end = event.endEventTime.toMillis();<br><br>   // Configure queue<br>    const project = JSON.parse(process.env.FIREBASE_CONFIG!).projectId;<br>    const location = `us-central1`;<br>    const queue = ‘my-scheduler’;<br>    const tasksClient = new CloudTasksClient();<br><br>    await createTasks(tasksClient, project, location, queue, eventId, start, end);<br><br>});   <br><br>// function for scheduling tasks<br>async function createTasks(tasksClient: any, project: any, location: any, queue: any, eventId: any, start: any, end: any) {<br><br>    const thirtyMinutesBeforeStart = start - 30 * 60 * 1000;<br>    const payload = { eventId };<br>    const taskName = “projects/${project}/locations/${location}/queues/{queue}/tasks”;<br>    const serviceAccountEmail = “SERVICE_ACCOUNT_EMAIL_HERE”;<br>    <br>    // Define Tasks to Create<br><br>    const almostStartedTask {<br>        name: `${taskName}/almostStartedTask-${eventId}-${start}`,<br>        httpRequest: {<br>           httpMethod: “POST”,<br>           url: `https://${location}/${project}.cloudfunctions.net/updateEventCallback?eventId=${eventId}&amp;status=almostStarted`,<br>           body: Buffer.from(JSON.stringify(payload)).toString(base64),<br>          headers: { ‘Content-Type’: application/json },<br>          oidcToken: {<br>             serviceAccountEmail,<br>             audience: `https://{location}/${project}.cloudfunctions.net/updateEventCallback`,<br>          },<br>       },<br>       scheduleTime: { seconds: Math.floor(thirtyMinutesBeforeStart / 1000) },<br>    };<br><br><br>    const startedTask {<br>        name: `${taskName}/startedTask-${eventId}-${start}`,<br>        httpRequest: {<br>           httpMethod: “POST”,<br>           url: `https://${location}/${project}.cloudfunctions.net/updateEventCallback?eventId=${eventId}&amp;status=started`,<br>           body: Buffer.from(JSON.stringify(payload)).toString(base64),<br>          headers: { ‘Content-Type’: application/json },<br>          oidcToken: {<br>             serviceAccountEmail,<br>             audience: `https://{location}/${project}.cloudfunctions.net/updateEventCallback`,<br>          },<br>       },<br>       scheduleTime: { seconds: Math.floor(start / 1000) },<br>    };<br><br><br>    const endedTask {<br>        name: `${taskName}/endedTask-${eventId}-${start}`,<br>        httpRequest: {<br>           httpMethod: “POST”,<br>           url: `https://${location}/${project}.cloudfunctions.net/updateEventCallback?eventId=${eventId}&amp;status=ended`,<br>           body: Buffer.from(JSON.stringify(payload)).toString(base64),<br>          headers: { ‘Content-Type’: application/json },<br>          oidcToken: {<br>             serviceAccountEmail,<br>             audience: `https://{location}/${project}.cloudfunctions.net/updateEventCallback`,<br>          },<br>       },<br>       scheduleTime: { seconds: Math.floor(end / 1000) },<br>    };<br><br><br>    // Create Tasks<br><br>    await tasksClient.createTasks({ parent: tasksClient.queuePath(project, location, queue), task: almostStartedTask });<br><br>    await tasksClient.createTasks({ parent: tasksClient.queuePath(project, location, queue), task: startedTask });<br><br>    await tasksClient.createTasks({ parent: tasksClient.queuePath(project, location, queue), task: endedTask });<br>}</pre><p>That was it for the onCreate trigger, having this done when the event is created this onCreate trigger will be triggered and will schedule 3 events which will execute on their specified time.</p><p>Next, we need an <strong>updateEventCallback</strong> HTTP trigger to implement, let’s also go through it.</p><p><strong>Note: </strong>You must have a service account created, with certain roles that are in the<strong> </strong><a href="https://medium.com/@ak187429/enablschedule-cloud-functions-with-cloud-tasks-for-document-ttl-part-1-2c110f0576cd"><strong>Part 1</strong></a> of this article.</p><pre>export const updateEventCallback = functions.https.onRequest(async (req, res) =&gt; {<br>   <br>   const project = json.parse(process.env.FIREBASE_CONFIG!).projectId;<br>   const location = ‘us-central1’;<br><br>   // access the headers &gt; authorization of the request<br>    const authorizationHeader = req.headers.authorization;<br><br>  // check if authorization header is not null<br>   if(!authorizationHeader) {<br>      res.status(401).send(“unauthorized token”);<br>      return;<br>   }<br><br>   // if authorizationHeader is not null access the token<br>    const token = authorizationHeader.split(‘ ’)[1];<br><br>   // verify ID token<br>    try {<br>      await verifyIdToken(token, location, project);<br>    } catch (error) {<br>      console.log(error);<br>      res.status(401).send(“Unauthorized token”);<br>      return;<br>    }<br><br>   // access query params<br>    const eventId = req.query.eventId as string;<br>    const status = req.query.status as string;<br>   // update event status<br>    await admin.firestore().collection(“events”).doc(eventId).update({ eventStatus: status });<br><br>});</pre><p>Also if you want to generate notifications on status changes you can do likewise, after updating the status in the <strong>updateEventCallback</strong> you can do something like this:</p><pre>   ...<br>   // update event status<br>    await admin.firestore().collection(“events”).doc(eventId).update({ eventStatus: status });<br><br>   // get event<br>    const eventDocRef = await admin.firestore().collection(“events”).doc(eventId).get();<br>    const eventData = eventDocRef.data();<br><br>   if(eventData) { <br>     // here access event necessary fields of events<br>     // such as eventName, the participants of event<br>     // also the eventStatus<br><br>     // and loop through the event participants list<br>     // and inside the loop body check if the current<br>     // updated status was “started” or “ended”, and<br>     // generate notification accordingly.<br><br>   }<br><br>});</pre><p>Make sure you have this method to verify token:</p><pre>async function verifyIdToken(token: string, location: any, project: any) {<br>   const client = new OAuth2Client();<br>   const ticket = await client.verifyIdToken({<br>       idToken: token,<br>       audience: “https://${location}-${project}.cloudfunctions.net/updateEventCallback”,<br>   });<br><br>   return ticket.getPayload();<br>}</pre><p>With this done, we have successfully scheduled an event, which will notify users according to status changes when the scheduled time arrives of the task in the Cloud Tasks queue.</p><h4><strong>What if we want to update event time?</strong></h4><p>Remember? From <strong>Part 1</strong>, I said there’s no built-in method to update the event time but you have to delete the tasks from the queue and recreate them. So let’s do it.</p><pre>export const eventUpdateTime = functions.firestore.document(“/events/${eventId}”).onUpdate(async (change, context) =&gt; {<br><br>   const eventBeforeUpdate = change.before.data();<br>   const eventAfterUpdate = change.after.data();<br><br>   const startTimeBefore = eventBeforeUpdate.startEventTime.toMillis();<br>   const endTimeBefore = eventBeforeUpdate.endEventTime.toMillis();<br>   const startTimeAfter = eventAfterUpdate.startEventTime.toMillis();<br>   const endTimeAfter = eventAfterUpdate.endEventTime.toMillis();<br><br>   if(startTimeBefore !== startTimeAfter || endTimeBefore !== endTimeAfter) {<br>    // access eventId<br>     const eventId = eventAfterUpdate.eventId; <br>     <br>   // access queue info<br>   const project = JSON.parse(process.env.FIREBASE_CONFIG!).projectId;<br>   const location = ‘us-central1’;<br>   const queue = “my-scheduler”;<br>   const tasksClient = new CloudTasksClient();<br><br>   // actual queue path<br>   const parent = tasksClient.queuePath(project, location, queue);<br>   // list tasks<br>   const tasks = await tasksClient.listTasks({ parent }); <br><br>   // Iterate over tasks to find and delete the ones associated with updated event<br><br>   for(const task of tasks[0]) {<br>     if(task.name.includes(eventId)) {<br>        await tasksClient.deleteTask({ name: task.name });<br>        console.log(`Task ${task.name} was deleted.`);<br>     }<br>   }<br><br>   // call the createTasks method to reschedule the tasks according to the startEventTime and endEventTime fields updated.<br><br>   const start = eventAfterUpdate.startEventTime.toMillis();<br>   const end = eventAfterUpdate.endEventTime.toMillis();<br>   <br>   await createTasks(tasksClient, project, location, queue, eventId, start, end);<br>  }<br><br>});</pre><h4><strong>What if we want to cancel event?</strong></h4><p>It’s pretty simple, check the condition on status changes to “canceled” and delete all the tasks from the queue containing that specific eventId as well as event from the collection. Cancelation is described already in the previous article <strong>Part 1</strong>.</p><h4><strong>What about security?</strong></h4><p>What?? Security is already done, what kind of security now you’re talking about? Calm down, I’m just joking 😀.</p><h3><strong>Remember this</strong></h3><p>Security should never be an afterthought when orchestrating your tasks schedules. It’s crucial to create robust security rules that cap the understanding duration according to your specific needs. But why, you ask?</p><p><strong>Consider a scenario:</strong> a rogue user schedules events far into the future. These events, then, languish in your tasks queue indefinitely. This is not merely an irritating inconvenience, but a genuine issue to tackle.</p><p><strong>Cloud Tasks has an inbuilt safety mechanism;</strong> tasks cannot be scheduled for more than 30 days. Yet if we, the developers, unwarily allow users in our app to schedule tasks beyond this timeframe, we’re inviting trouble. Without strict security rules, the events will attempt to register beyond the 30 days limit, causing an error or even potentially disrupting the entire task queue system.</p><p>So, my fellow coders, the power lies in your hands. With right security rules, you can ensure smooth sailing — or, in our case, smooth scheduling. Remember, <strong>the longevity of a task in a queue is a lot like a perfectly steeped cup of tea</strong> — it needs to be just right.</p><h3><strong>Conclusion</strong></h3><p>I provided everything along with a clear explanation of how each method is going to execute and what job it is going to complete. But I’m not sure what are the requirements of your app, so feel free to modify the code according to your app’s requirement. If you found this article useful, share it with other learners and let me know your experience in the comment section. Don’t forget to clap.</p><p>Follow me on:</p><p>LinkedIn: <a href="https://www.linkedin.com/in/muhammad-adnan-23bb8821b/">https://www.linkedin.com/in/muhammad-adnan-23bb8821b/</a></p><p>GitHub: <a href="https://github.com/AdnanKhan45">https://github.com/AdnanKhan45</a></p><p>Instagram: <a href="https://www.instagram.com/dev.adnankhan/">https://www.instagram.com/dev.adnankhan/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d22a5fcab80" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Schedule Cloud Functions with Cloud Tasks (for Document TTL) Part 1]]></title>
            <link>https://medium.com/@ak187429/enablschedule-cloud-functions-with-cloud-tasks-for-document-ttl-part-1-2c110f0576cd?source=rss-12fbddea09ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c110f0576cd</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[google-cloud-functions]]></category>
            <category><![CDATA[google-cloud]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[cloud-tasks]]></category>
            <dc:creator><![CDATA[Muhammad Adnan]]></dc:creator>
            <pubDate>Tue, 13 Jun 2023 17:50:38 GMT</pubDate>
            <atom:updated>2023-06-25T07:06:18.607Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9StDA037LYaLKZL8zmYELw.png" /></figure><p>Ready to step into the future of automation? Let’s dive into the world where <strong>Cloud Tasks</strong> and <strong>Firestore</strong> TTL (Time to Live) blend together, simplifying your work and boosting your productivity. This journey is all about unlocking the potential of Google Cloud’s tools to automate tasks, manage your Firestore documents more effectively, and ensure timely execution of functions. Let’s get started on this exciting journey together.</p><figure><img alt="Let’s Get Started" src="https://cdn-images-1.medium.com/max/220/1*IXzLa32ZshCqB6MzIDsWPA.gif" /></figure><p>This article is divided into <strong>2 parts</strong>, and in this first part we will make <strong>Firestore</strong> document TTL along with the step by step setting up and understanding each and every little thing while also taking care of the security issues. In the 2nd part we will build an event scheduling system that automatically notifies users according to time scheduled on event status changes.</p><p><strong>Hey Reader: </strong>The article can be long because there’s a lot to learn, so take your coffee and let’s get started 😚.</p><h3><strong>Breaking Free from Polling Limitations</strong></h3><p>Periodic polling can only take us so far. Sure you could rely on scheduled functions to run at regular intervals, scanning through a custom-built scheduler to determine if any pending tasks are due. But here’s the thing — it comes with a host of downsides that might leave you yearning for a more elegant and efficient solution.</p><ul><li><strong>First</strong>, you have to invest valuable time and effort in constructing that scheduler, meticulously describing the work that needs to be done when. It’s an additional layer of complexity that could be avoided.</li><li><strong>Second</strong>, scheduled functions have their limitations, they can execute as frequently as once per minute, which means you might experience delays of up to a minute — a delay that might be simply unacceptable for time-sensitive operations.</li></ul><p>And let’s not forget about unnecessary overhead. With periodic polling, you end up paying for repeated functions invocations and scheduler queries that might ultimately yield no actual work to be done. It’s an inefficient use of resources.</p><ul><li>Picture a reservation system that grants users a strict 15-minute window to complete a reservation. Once that elapses, the system needs to terminate the incomplete reservation and free up it for others.</li><li>Or imagine a thrilling game that challenges players to conquer a level within 2.5 minutes, enforcing a time limit to prevent cheating.</li><li>And what about a lively quiz game that demands lightning-fast answers within a 10-second countdown before moving to the next question.</li></ul><p>For these scenarios and more, relying on scheduled functions just won’t cut it. You need a solution that is cost-effective and flexible, capable of delivering the precision and control your application demands.</p><h3><strong>That’s where the Cloud Tasks comes in</strong></h3><p>By leveraging <a href="https://cloud.google.com/tasks/docs/"><strong>Cloud Tasks</strong></a>, you can efficiently schedule the invocation of a “callback” function exactly when follow-up work needs to be executed. It’s a smarter, more streamlined approach that eliminates the need for unnecessary repetition and empowers you to optimize both cost and performance.</p><p>The process of Cloud Tasks is simple and straightforward. Begin by creating a queue that suits your needs, and if desired customize its configuration to optimize performance. Once your queue is set up, it’s time to add Tasks using the provided SDK. Each task can be tailored to your requirements, allowing you to define an HTTP request with a payload that precisely outlines the work that needs to be executed. Think of it as a future callback mechanism, where the designated HTTP function eagerly awaits instructions on what action to take when the scheduled time arrives.</p><p><strong>Note:</strong> Make sure to check out Cloud Task <a href="https://cloud.google.com/tasks/docs/quotas"><strong>limitations and quota limits</strong></a> for better understanding with Cloud Tasks.</p><h4><strong>Cloud Tasks working flow</strong></h4><p>I’ll assume you are already familiar with the Cloud Functions and <strong>Typescript</strong> for better understanding the code we’re going to write for scheduling. Here’s one diagram for clarification on how Cloud Tasks is going to work with Cloud Functions.</p><figure><img alt="Cloud Tasks working flow with Cloud Functions" src="https://cdn-images-1.medium.com/max/1024/1*9StDA037LYaLKZL8zmYELw.png" /></figure><h4><strong>Set up Cloud Tasks</strong></h4><p>Cloud Tasks require billing before using it in your project. So you need to complete the billing process and then you will be allowed to use Cloud Tasks in your project. <a href="https://cloud.google.com/tasks/pricing"><strong>Here</strong></a> is the breakdown of the pricing of Cloud Tasks (it’s cheap, you can schedule 1 million tasks for free every month).</p><p>First of all, <a href="https://console.cloud.google.com/apis/library/cloudtasks.googleapis.com/"><strong>Enable the Cloud Tasks API</strong></a> in the Cloud Console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1JPV5_8OGligqbX1OTUyuw.png" /></figure><p>You can follow the documentation to <a href="https://cloud.google.com/tasks/docs/creating-queues"><strong>create queue</strong></a>. You will also need to have the <a href="https://cloud.google.com/sdk/docs/install"><strong>gcloud CLI installed</strong></a> also configured with your Firebase project.</p><p>You just need this line to run and create a named queue. I will name the queue <strong>“my-scheduler”</strong>:</p><pre>$ gcloud tasks queues create my-scheduler</pre><p>If gcloud gives you a warning, you can ignore it as long as your output statement includes the queue was created.</p><h4><strong>Start with writing functions</strong></h4><p>With Cloud Tasks set up, you can now use it in your function code. Cloud Tasks provides a client SDK for node so install it with npm by running the command below.</p><pre>$ npm install @google-cloud/tasks</pre><p>Now, let’s import all of the Firebase modules as well as the newly added <strong>@google-cloud/tasks </strong>module. And make sure to import it with the JavaScript require syntax.</p><pre>import * as functions from &#39;firebase-functions&#39;<br>import * as admin from &#39;firebase-admin&#39;<br>const { CloudTasksClient } = require(&#39;@google-cloud/tasks&#39;)<br>admin.initializeApp()</pre><p>With this done now first we will cover the first scenario by making a Firestore document TTL and then to tackle the event scheduling system. Let’s face it.</p><p><strong>Hey Reader: </strong>You might be tired, make sure you take a break and get fresh before diving into actual code 😀.</p><h4><strong>Firestore document TTL using Cloud Tasks and Cloud Functions.</strong></h4><p>Let’s start by defining an <a href="https://firebase.google.com/docs/functions/firestore-events?gen=2nd#function_triggers"><strong>Firebase Firestore onCreate Trigger</strong></a> function that will be invoked when a document is created in for example “events” collection.</p><pre>export const onCreateEvent = functions.firestore.document(&quot;/events/{eventId}&quot;).onCreate(async snapshot =&gt; {<br>    // here goes the scheduling code.<br>});</pre><p>Now, we will look at when the user wants to expire the document. Having this in mind we will introduce two additional fields that will specify the expiration time of the document, these fields can be your document fields if you are implementing the same scenario in your app. <strong>expireSeconds</strong> and <strong>expireTime</strong> will be two fields where <strong>expiresSeconds</strong> will store the current time in seconds and <strong>expiresTime</strong> will store exact current time in timestamp. So will express these two methods inside the <strong>onCreateEvent</strong> function.</p><pre>const data = snapshot.data() as { expireSeconds: number, expireTime: admin.firestore.timestamp };<br>const { expireSeconds, expireTime } = data;</pre><p>Next, I will store the expiration time in seconds in a variable and some conditions accordingly.</p><pre>// This is local variable for storing expirationAtSeconds<br>let expirationAtSeconds: number | undefined<br><br>// Extract expiration time based on provided fields<br>if(expireSeconds) {<br>   if(expireSeconds &gt; 0) {<br>       expirationAtSeconds = Date.now() / 100 + expireSeconds;<br>   }<br>} else if (expireTime) {<br>   expirationAtSeconds = expireTime.seconds;<br>}<br><br>// If not time is set for the document we will return<br>if(expirationAtSeconds == undefined) {<br>   return;<br>}</pre><p>After having the <strong>expirationAtSeconds</strong> let’s do some configuration for the task queue.</p><pre>const project = json.parse(process.env.FIREBASE_CONFIG!).projectId;<br>const location = ‘us-central1’;<br>const queue = ‘my-scheduler’;</pre><p>Now with the help of Cloud Task SDK provide an acceptable path to the queue.</p><pre>const taskClient = new CloudTaskClient();<br>const queuePath: string = taskClient.queuePath(project, location, queue);</pre><p>Last but not the least, let’s finally configure the URL to the callback function and a payload to deliver, and one last thing the name for the task which will later help us in canceling the task.</p><pre>const url = `https://${location}-${project}.cloudfunctions.net/schedulerCallback?eventId=${snapshot.id}`;<br>const payload = { snapshot.id };<br>const taskName = `projects/${project}/locations/${location}/queues/${queue}/tasks`;</pre><p>You might be thinking why the <strong>taskName</strong> is so long, and why only this ? can’t it be an arbitrary or simple name?</p><p>Well, creating cloud tasks with names must follow a <strong>hierarchical naming scheme</strong> which allows cloud tasks to uniquely identify tasks across multiple projects, locations and queues. You can create tasks with arbitrary or simple names but it would create a conflict and make it impossible for Cloud Tasks to determine which task to execute.</p><p>By requiring that tasks names include <strong>project ID</strong>, <strong>location</strong>, and <strong>queue</strong>, Cloud Tasks ensures that each task has a unique name and can be executed without conflict.</p><p>Now, let’s build an configuration for the Cloud Task:</p><pre>const task = {<br>   name: `${taskName}/myTask-${snapshot.id}-${expireSeconds}`,<br>   httpRequest: {<br>     httpMethod: ‘POST’,<br>     url: url,<br>     body: Buffer.from(JSON.stringify(payload)).toString(‘base64’),<br>     headers: { ‘Content-Type’: ‘application/json’ }<br>  },<br>   scheduleTime: {<br>     seconds: expirationAtSeconds<br>  }<br>}</pre><p>To the task configuration, we provide:</p><ul><li><strong>Unique name:</strong> which contains snapshot.id or eventId and expireSeconds to be unique from all the other tasks in the queue.</li><li><strong>scheduleTime:</strong> for scheduling the task that will later execute at the provided <strong>expirationAtSeconds</strong>.</li><li><strong>httpRequest:</strong> we make an HTTP request to the given url and pass the JSON content body with the contents of the payload.</li></ul><p><strong>Note</strong>: the encoding base64 is just required by Cloud Task API. The function will still receive the raw stringified JSON.</p><p>Finally, I will just enqueue the task to the queue.</p><pre>await tasksClient.createTask({ parent: queuePath, task })</pre><p>And… we’re done with the first cloud function <strong>onCreateEvent</strong>.</p><p>Now we need to write an HTTP callback function that would be invoked by Cloud Tasks at the right time.</p><pre>export const schedulerCallback = functions.https.onRequest(async (req, res) =&gt; {<br>   // accessing the eventId that we sent over HTTP POST request as a query param.<br>   const eventId = req.query.eventId as string;<br>   try {<br>      await admin.firestore().collection(“events”).doc(eventId).delete();<br>   } catch(e) {<br>      console.log(e);<br>      res.status(500).send(e);<br>   }<br>});</pre><p>In the function above we pull that eventId that we sent as a query param in the http request. And using that eventId we delete that document from the events collection. Make sure you include both <strong>expireTime</strong> and <strong>expireSeconds</strong> fields in your cloud firestore document according to the requirements of your project.</p><p><strong>Finally: </strong>we are done with our first job by making a firestore document TTL. It was easy, right? I knew that 😀.</p><h4><strong>Canceling scheduled tasks</strong></h4><p>This can also be one scenario, if the user wants to cancel the already scheduled task. It is also pretty simple, let’s face it.</p><ul><li>Include one more field like <strong>expireTime</strong> and <strong>expireSeconds</strong>. And name it <strong>expirationStatus</strong> This must be of type string.</li><li>Use Firebase Cloud Firestore <strong>onUpdate</strong> trigger to look for <strong>expirationStatus</strong> and accordingly delete/remove the task.</li></ul><p>If the <strong>expirationStatus</strong> task was updated to “canceled”, use the queue path to cancel the task.</p><p>As I said earlier, to include <strong>expireTime</strong> and <strong>expireSeconds</strong> fields in your cloud firestore document, make sure you include <strong>expirationStatus</strong> also according to your project requirements. And from your app simply call the regular update method of Cloud Firestore on the event document to update the <strong>expirationStatus</strong> to “canceled”. And then your onUpdate trigger will look something like this:</p><pre>export const onUpdateEventCancel functions.firestore.document(“/events/{eventId}”).onUpdate(async change =&gt; {<br>   const eventBeforeUpdate = change.before.data();<br>   const eventAfterUpdate = change.after.data();<br><br>   // check if event is canceled<br>   if(eventBeforeUpdate.expirationStatus !== eventAfterUpdate.eventAfterUpdate &amp;&amp; eventAfterUpdate.expirationStatus === ‘canceled’) {<br>   const project = json.parse(process.env.FIREBASE_CONFIG!).projectId;<br>   const location = ‘us-central1’;<br>   const queue = ‘my-scheduler’;<br>   const taskClient = new CloudTasksClient();<br><br>   // task details<br>   const eventId = eventAfterUpdate.eventId;<br>   const expireSeconds = eventAfterUpdate.expireSeconds;<br>   <br>   // taskName<br>   const taskName = ‘projects/${project}/locations/${location}/queues/${queue}/tasks/task-${eventId}-${expireSeconds}’;<br><br>   await taskClient.deleteTask({ name: taskName });<br><br> }<br>});</pre><p><strong>Note</strong>: If you want to update the task in the queue, there’s no built-in method for that, but instead you need to delete and recreate the task in the queue.</p><p>Also you can store the <strong>taskName</strong> in the firestore and can directly cancel the task using that name. But for that you need a little more code in the onCreate trigger.</p><p>In the end of the onCreate trigger do something like this:</p><pre>. . .  <br>const [ response ] = await tasksClient.createTask({ parent: queuePath, task });<br><br>const taskName = { response.name };<br><br>await admin.firestore().collection(“events”).doc(eventId).update({ taskName: taskName });<br>. . .</pre><p>For that make sure you also have a <strong>taskName</strong> field in your event document.</p><p>Next your <strong>onUpdateEventCancel</strong> trigger will look something like this:</p><pre>export const onUpdateEventCancel functions.firestore.document(“/events/{eventId}”).onUpdate(async change =&gt; {<br>   const eventBeforeUpdate = change.before.data();<br>   const eventAfterUpdate = change.after.data();<br><br>   // check if event is canceled<br>   if(eventBeforeUpdate.expirationStatus !== eventAfterUpdate.eventAfterUpdate &amp;&amp; eventAfterUpdate.expirationStatus === ‘canceled’) {<br><br>   const taskClient = new CloudTasksClient();<br>   await taskClient.deleteTask({ name: eventAfterUpdate.taskName });<br><br>  }<br>});</pre><p><strong>Great Job: </strong>You have successfully completed TTL stuff and canceling tasks — I know this time it was a bit terrible, taking some rest may relax your neurons 😀.</p><h3><strong>Wait a second, what about security?</strong></h3><p>You might be rubbing your chin, thinking: “This is awesome, but won’t it allow just about anyone to erase my documents if they figure out my URL and payload pattern for the callback function?” The answer, surprisingly, is yes. As is, the Firebase CLI launches HTTP functions that anyone with internet access can invoke. But fear not, this potential issue has a solution.</p><p>And that is, we need to make some changes in both the task configuration and the function to use a service account to authenticate the function invoker. Here will require some advanced configuration that will not be visible on the Firebase console.</p><p>First create a service account by going to <a href="https://console.cloud.google.com/iam-admin/">IAM &amp; Admin</a> &gt; Service Accounts. On the top menu you will see <strong>CREATE SERVICE ACCOUNT</strong>. Name your service account and go for <strong>CREATE AND CONTINUE</strong>. In the second step give the following roles to the service accounts (Cloud Function Invoker, Cloud Tasks Enqueuer, and Service Account Token Creator) and you are done with the service account.</p><p>Next, on <strong>IAM &amp; Admin</strong> come to the first tab named <strong>IAM</strong>. Grant access and in the first field “New principals” add your service account there and grant the above roles to it and save it.</p><p>You can read about <a href="https://cloud.google.com/functions/docs/securing/managing-access-iam"><strong>IAM for Cloud Functions</strong></a><strong>.</strong></p><h4><strong>Modify onCreateEvent trigger for security</strong></h4><p>After having your service account with certain roles it’s time to dive into code again and protect our HTTP request from outside access by authenticating the function invoker with the service account.</p><pre>export const onCreateEvent = functions.firestore.document(&quot;/events/{eventId}&quot;).onCreate(async snapshot =&gt; {<br>    ...<br>    <br>    // include this in the onCreateTrigger<br>    const serviceAccountEmail = “SERVICE_ACCOUNT_EMAIL_HERE”;<br><br>    // configure the task<br>    const task {<br>     ...<br>     headers: { ‘Content-Type’: ‘application/json’ }<br>   }<br>   oidcToken: {<br>     serviceAccountEmail,<br>     audience: “https://${location}-${project}.cloudfunctions.net/schedulerCallback&quot;<br>   }<br>    ...<br> }<br>    ...<br>});</pre><p>In the code above, we modify the onCreate event trigger by adding one field of <strong>serviceAccountEmail</strong>. And we configure the task object by adding one more field oidcToken and we pass the <strong>serviceAccountEmail</strong> and audience the same http trigger url which leads to the <strong>schedulerCallback</strong>. Other code will remain the same.</p><p>Let’s break down the above code and let’s see what it does.</p><p>We will use <strong>serviceAccountEmail</strong> to authenticate the function invoker with that <strong>serviceAccountEmail</strong>. And the <strong>audience</strong> is specified the same as the service URL (excluding query params) and this field is used to specify the intended recipient of the JWT, and this is used as a form of access control. Using the service’s URL as an audience helps to ensure that the token is used for the right service, and prevents the token from being misused to access other services.</p><p>After you have set up the service account and the configured task with the <strong>oidcToken</strong>, every time the onCreateEvent trigger fires and a task is created, Google Cloud Tasks receives the instructions on who should make the HTTP request and where it should be sent.</p><p>When the scheduled time arrives and the task is about to be dispatched, the service account specified <strong>serviceAccountEmail</strong> field is used to generate an OpenID Connect (OIDC) token. This token claims about the identity of the service account, including the audience claim that matches your Cloud Function’s URL.</p><p>The OIDC token is sent as part of the HTTP request’s <strong>Authorization header</strong> when the task is fully dispatched. When your Cloud Function receives the request, it can validate the token to ensure that the request is authenticated and authorized. It verifies the audience claim matches its own URL, confirming that the token was intended for this service.</p><h4><strong>Modify schedulerCallback for security</strong></h4><p>First of all, run this command to install the google-auth-library. We will use it to verify ID token.</p><pre>npm install google-auth-library</pre><p>Next go to the <strong>index.ts</strong> and import this:</p><pre>import { OAuth2Client } from “google-auth-library”;</pre><p>Then, create an asynchronous function that will verify the ID token.</p><pre>async function verifyToken(token: string, location: any, project: any) {<br>   const client = new OAuth2Client();<br>   const ticket = await client.verifyIdToken({<br>       idToken: token,<br>       audience: “https://${location}-${project}.cloudfunctions.net/schedulerCallback”,<br>   });<br><br>   return ticket.getPayload();<br>}</pre><p><strong>Note: </strong>Make sure you pass the <strong>audience</strong> the same as you passed previously in the oidcToken within the task object.</p><p>Now, let’s go for modifying the <strong>schedulerCallback</strong> so that every time a call is made to <strong>schedulerCallback</strong> function it will verify an id token, if it was from the accurate service account it will verify it and will allow the request to further execute and delete the document, but if it was with wrong service account and don’t have a token of authorization token in the headers it will send a response of <strong>“unauthorized token”</strong>.</p><p>The <strong>schedulerCallback</strong> function will become:</p><pre>export const schedulerCallback = functions.https.onRequest(async (req, res) =&gt; {<br>   // add the projectID and location<br>   const project = json.parse(process.env.FIREBASE_CONFIG!).projectId;<br>   const location = ‘us-central1’;<br>   const eventId = req.query.eventId as string;<br><br>   // access the headers &gt; authorization of the request<br>    const authorizationHeader = req.headers.authorization;<br><br>  // check if authorization header is not null<br>   if(!authorizationHeader) {<br>      res.status(401).send(“unauthorized token”);<br>      return;<br>   }<br><br>   // if authorizationHeader is not null access the token<br>    const token = authorizationHeader.split(‘ ’)[1];<br><br>   // verify ID token<br>    try {<br>      await verifyIdToken(token, location, project);<br>    } catch (error) {<br>      console.log(error);<br>      res.status(401).send(“Unauthorized token”);<br>      return;<br>    }<br><br>   // delete document<br>   try {<br>      await admin.firestore().collection(“events”).doc(eventId).delete();<br>   } catch(e) {<br>      console.log(e);<br>      res.status(500).send(e);<br>   }<br>});</pre><p>Phew! That was quite the security sprint, wasn’t it? <strong>But just like an arduous marathon, the euphoria of crossing the finish line makes it all worthwhile</strong>. Now, we have TTL documents with secure deletion, and good night sleep free from security worries.</p><p>Before we part ways, there’s one more thing to remember. Security is a never ending journey and must be a part of your application’s DNA. Make sure you frequently revisit, review, and revise your security strategies. You are the guardian of the Firestore kingdom. WIth knowledge and foresight, you can protect it from any potential invasions.</p><p>In the world of code, every line is a new adventure. Today, we’ve journeyed through TTL documents, cancellations, and security issues. And in the 2nd part of this article we will thoroughly go through the event scheduling system using Cloud Tasks so never miss out.</p><p><a href="https://medium.com/@ak187429/schedule-cloud-functions-with-cloud-tasks-event-scheduling-part-2-2d22a5fcab80"><strong>See you there</strong></a>.</p><p>Let’s connect:</p><p>LinkedIn: <a href="https://www.linkedin.com/in/muhammad-adnan-23bb8821b/">https://www.linkedin.com/in/muhammad-adnan-23bb8821b/</a></p><p>GitHub: <a href="https://github.com/AdnanKhan45">https://github.com/AdnanKhan45</a></p><p>Instagram: <a href="https://www.instagram.com/dev.adnankhan/">https://www.instagram.com/dev.adnankhan/</a></p><h3><strong>Final Code:</strong></h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a653bd2c5f273d8d6a8907927c881f2/href">https://medium.com/media/0a653bd2c5f273d8d6a8907927c881f2/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c110f0576cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[clean Instagram Clone Clean Architecture — Part 10]]></title>
            <link>https://medium.com/@ak187429/clean-instagram-clone-clean-architecture-part-10-6ac50e6ba74c?source=rss-12fbddea09ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ac50e6ba74c</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Muhammad Adnan]]></dc:creator>
            <pubDate>Wed, 31 Aug 2022 07:23:23 GMT</pubDate>
            <atom:updated>2022-11-25T04:18:56.995Z</atom:updated>
            <content:encoded><![CDATA[<h3>Instagram Clone Clean Architecture — Part 10</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HyhddZRXM6D2FmObgKgMhg.png" /></figure><p>The time we have waited so far is finally here, in this part we will finally be calling the methods in our UI and you’ll see all the code up until know we wrote in action.</p><p>This is just single part of this series. Checkout all the other parts <a href="https://etechviral.com/blogs/">here</a><strong> </strong>and learn to build<strong> </strong>clean and maintainable apps.</p><p><strong>Note: </strong>In our sign up page, we also have to upload profile image of user. If you are familiar with <strong>Firebase</strong> we upload our files and images in <strong>Cloud Storage</strong>. That is separate topic and we will cover it individually in the next part.</p><p>First move to your main.dart and change it from:</p><pre>MaterialApp(<br>  debugShowCheckedModeBanner: <em>false</em>,<br>  title: &quot;Instagram Clone&quot;,<br>  darkTheme: ThemeData.dark(),<br>  onGenerateRoute: OnGenerateRoute.<em>route</em>,<br>  initialRoute: &quot;/&quot;,<br>  routes: {<br>    &quot;/&quot;: (context) {<br>      <em>return </em>MainScreen();<br>    }<br>  },<br>),</pre><p>To:</p><pre>MaterialApp(<br>  debugShowCheckedModeBanner: <em>false</em>,<br>  title: &quot;Instagram Clone&quot;,<br>  darkTheme: ThemeData.dark(),<br>  onGenerateRoute: OnGenerateRoute.<em>route</em>,<br>  initialRoute: &quot;/&quot;,<br>  routes: {<br>    &quot;/&quot;: (context) {<br>      <em>return </em>BlocBuilder&lt;AuthCubit, AuthState&gt;(<br>        builder: (context, authState) {<br>          <em>if </em>(authState <em>is </em>Authenticated) {<br>            <em>return </em>MainScreen(uid: authState.uid,);<br>          } <em>else </em>{<br>            <em>return </em>SignInPage();<br>          }<br>        },<br>      );<br>    }<br>  },<br>),</pre><p>We have Bloc Builder and Bloc Listener.</p><p><strong>Bloc Builder:</strong></p><p>The <strong>Bloc Builder</strong> is used when we want to draw a widget based on what is the current state.</p><p><strong>Bloc Listener:</strong></p><p>The <strong>Bloc Listener</strong> is keep listening to the new changes in state and do not return a widget.</p><p>In the code above using <strong>Bloc Builder</strong> we’re checking if our <strong>AuthState</strong> is <strong>Authenticated</strong>, so return the <strong>MainScreen()</strong> widget otherwise return <strong>SignInPage()</strong> widget.</p><p><strong>Notice: </strong>The <strong>MainScreen()</strong> accepts uid argument. Go to <strong>MainScreen()</strong> and create a final field and pass it in the constructor of Main Screen <strong>StatefulWidget</strong>. We will use this current user id later in this page.</p><pre><em>class </em>MainScreen <em>extends </em>StatefulWidget {<br>  <em>final </em>String uid;<br>  <em>const </em>MainScreen({Key? key, <em>required this</em>.uid}) : <em>super</em>(key: key);</pre><p>With this wrap your <strong>Material App</strong> with <strong>MultiBlocProvider</strong> which accepts list of <strong>BlocProviderSingleChildWidget</strong>. In this list requests to the Cubits from their registered types which are located in the injection container.</p><pre>MultiBlocProvider(<br>  providers: [<br>    BlocProvider(create: (_) =&gt; di.sl&lt;AuthCubit&gt;()..appStarted(context)),<br>    BlocProvider(create: (_) =&gt; di.sl&lt;CredentialCubit&gt;()),<br>    BlocProvider(create: (_) =&gt; di.sl&lt;UserCubit&gt;()),<br>    BlocProvider(create: (_) =&gt; di.sl&lt;GetSingleUserCubit&gt;()),<br>  ],<br>  child: MaterialApp(<br>    ...</pre><p>User is our first priority so we request to all the user cubits inside the injection container they will be called when our app starts and as they are factory methods so will give us the new instance each time.</p><p><strong>Notice: </strong>I called the <strong>appStarted(context)</strong> methods from our <strong>AuthCubit</strong> this is because, this <strong>appStarted</strong> is the method which ensure if the user is sign in or not.</p><p>Now if you hot restart your application you will see sign in page on your emulator. This is because our user is unauthenticated and the Bloc Builder draw the widget based on the current state (UnAuthenticated State).</p><p><strong>Sign Up Page:</strong></p><p>Go to sign_up_page and convert stateless widget to stateful widget. Now you need to add some controllers (TextEditingController) and pass them in the forms (FormContainerWidget).</p><p>Down below the state do this:</p><pre>TextEditingController _emailController = TextEditingController();<br>TextEditingController _usernameController = TextEditingController();<br>TextEditingController _passwordController = TextEditingController();<br>TextEditingController _bioController = TextEditingController();<br><br>bool _isSigningUp = <em>false</em>;</pre><p><strong>Notice:</strong> This _isSigningUp Boolean variable will be used when to show circular progress indicator when the user is signing up.</p><p>Also not forget to dispose these controllers.</p><pre>@override<br><br><em>void </em>dispose() {<br>  _emailController.dispose();<br>  _passwordController.dispose();<br>  _bioController.dispose();<br>  _usernameController.dispose();<br>  <em>super</em>.dispose();<br><br>}</pre><p>Now search for <strong>ButtonContainerWidget()</strong> with the text <strong>“Sign Up”.</strong> You will found <strong>onTapListener</strong> there, simply call the method here <strong>_signUpUser().</strong></p><pre>ButtonContainerWidget(<br>  color: blueColor,<br>  text: &quot;Sign Up&quot;,<br>  onTapListener: () {<br>    _signUpUser();<br>  },<br>),</pre><p>Implement this method:</p><pre><em>void </em>_signUpUser() {<br>  setState(() {<br>    _isSigningUp = <em>true</em>;<br>  });<br><br>  BlocProvider.<em>of</em>&lt;CredentialCubit&gt;(context).signUpUser(<br>      user: UserEntity(<br>        email: _emailController.text,<br>        password: _passwordController.text,<br>        bio: _bioController.text,<br>        username: _usernameController.text,<br>        totalPosts: 0,<br>        totalFollowing: 0,<br>        followers: [],<br>        totalFollowers: 0,<br>        profileUrl: &quot;&quot;,<br>        website: &quot;&quot;,<br>        following: [],<br>        name: &quot;&quot;,<br>      )<br>  ).then((value) =&gt; _clear());<br>}<br><br>_clear() {<br>  setState(() {<br>    _usernameController.clear();<br>    _bioController.clear();<br>    _emailController.clear();<br>    _passwordController.clear();<br>    _isSigningUp = <em>false</em>;<br>  });<br>}</pre><p><strong>Notice: </strong>We don’t pass the <strong>uid</strong>, this is because it is handled in the backend. Also Notice the <strong>_isSigningUp</strong> variable when the method is called it becomes true by <strong>setState</strong> and later in the clear method it become false in <strong>setState</strong> when the process end, through this variable we will control when and where to show circular progress indicator.</p><p>Right after the button container widget check if the variable is true show some text with indicator otherwise an empty container widget.</p><pre>ButtonContainerWidget(<br>  color: blueColor,<br>  text: &quot;Sign Up&quot;,<br>  onTapListener: () {<br>    _signUpUser();<br>  },<br>),</pre><pre>sizeVer(10),<br>_isSigningUp == <em>true </em>? Row(<br>  mainAxisAlignment: MainAxisAlignment.center,<br>  children: [<br>    Text(&quot;Please wait&quot;, style: TextStyle(color: primaryColor, fontSize: 16, fontWeight: FontWeight.<em>w400</em>),),<br>    sizeHor(10),<br>    CircularProgressIndicator()<br>  ],<br>) : Container(width: 0, height: 0,),</pre><p>Now separate the body of Scaffold in a separate method.</p><pre>_bodyWidget(){...}</pre><p>And pass this body widget in the scaffold body like:</p><pre>Scaffold(<br>    backgroundColor: backGroundColor,<br>    body: _bodyWidget()<br><br>);</pre><p>Now wrap the body with the Bloc Consumer.</p><p><strong>Bloc Consumer:</strong></p><p>The Bloc Consumer is the mix up between Bloc Builder and Bloc Listener. This is used when we want to draw something based on the current state and want to execute some actions depending on the new arriving state.</p><p>In the code below we execute two actions in listener first if the state is Credential Success then call the method from <strong>AuthCubit</strong> <strong>loggedIn()</strong> which means pass the <strong>uid</strong> in the <strong>Authenticated</strong> state, second if there is some failure show toast. In the builder we again call the bloc builder to check again if the Authenticated state has <strong>uid</strong> if so, move user to <strong>MainScreen</strong> otherwise keep it on the same page.</p><pre>Scaffold(<br>    backgroundColor: backGroundColor,<br>    body: BlocConsumer&lt;CredentialCubit, CredentialState&gt;(<br>      listener: (context, credentialState) {<br>        <em>if </em>(credentialState <em>is </em>CredentialSuccess) {<br>          BlocProvider.<em>of</em>&lt;AuthCubit&gt;(context).loggedIn();<br><br>        }<br>        <em>if </em>(credentialState <em>is </em>CredentialFailure) {<br>          toast(&quot;Invalid Email and Password&quot;);<br>        }<br>      },<br><br>      builder: (context, credentialState) {<br>        <em>if </em>(credentialState <em>is </em>CredentialSuccess) {<br>          <em>return </em>BlocBuilder&lt;AuthCubit, AuthState&gt;(<br>            builder: (context, authState) {<br>              <em>if </em>(authState <em>is </em>Authenticated) {<br>                <em>return </em>MainScreen(uid: authState.uid);<br>              } <em>else </em>{<br>                <em>return </em>_bodyWidget();<br>              }<br>            },<br>          );<br>        }<br>        <em>return </em>_bodyWidget();<br>      },<br>    )</pre><p>Congrats 🎉 test your sign up page and you are good to go.</p><p><strong>Sign In Page:</strong></p><p>Sign in page will not be that much different but only one method will be different.</p><p>First copy the controllers from Sign up Page not all but only two (email and password) also dispose them.</p><p>Now Search for the <strong>ButtonContainerWidget</strong> and in the <strong>onTapListener</strong> call the <strong>_signInUser()</strong> method.</p><p>Implement it then:</p><pre><em>void </em>_signInUser() {<br>  setState(() {<br>    _isSigningIn = <em>true</em>;<br>  });<br><br>  BlocProvider.<em>of</em>&lt;CredentialCubit&gt;(context).signInUser(<br>    email: _emailController.text,<br>    password: _passwordController.text,<br>  ).then((value) =&gt; _clear());<br>}<br><br>_clear() {<br>  setState(() {<br>    _emailController.clear();<br>    _passwordController.clear();<br>    _isSigningIn = <em>false</em>;<br>  });<br>}</pre><p><strong>Notice: </strong>Here the <strong>_isSigningIn</strong> variable is same, copy the code from Sign up Page, right after the <strong>ButtonContainerWidget</strong>; and paste it in Sign in Page in the same place. Only change the name of the variable.</p><p>Lastly separate the body widget and copy the code from Sign up Page and paste it everything will remain the same.</p><p>Congrats 🎉 test your sign in page and you are good to go.</p><p><strong>Logout User:</strong></p><p>Go to Profile Page and come to bottom you will see bottom modal sheet there. Wrap the text widget “Logout” with <strong>InkWell</strong> and call this <strong>onTap</strong> method:</p><pre>InkWell(<br>  onTap: () {<br>    BlocProvider.<em>of</em>&lt;AuthCubit&gt;(context).loggedOut();<br>    Navigator.<em>pushNamedAndRemoveUntil</em>(context, PageConst.<em>signInPage</em>, (route) =&gt; <em>false</em>);<br>  },<br>  child: Text(<br>    &quot;Logout&quot;,<br>    style: TextStyle(fontWeight: FontWeight.<em>w500</em>, fontSize: 16, color: primaryColor),<br>  ),</pre><p>Congrats 🎉 test the logout button and you are good to go.</p><p><strong>Load User data from Firestore Database:</strong></p><p><strong>Load Single User on MainScreen:</strong></p><p>If you remember, we created the <strong>getSingleUser</strong> to get the current single user. Go to <strong>MainScreen()</strong> and wrap the <strong>Scaffold</strong> with Bloc Builder and pass the <strong>GetSingleUserCubit </strong>and <strong>GetSingleUserState</strong>, and check if the state is <strong>GetSingleUserLoaded</strong> then retrieve the current single user from the state and save it in a variable.</p><pre>BlocBuilder&lt;GetSingleUserCubit, GetSingleUserState&gt;(<br>  builder: (context, getSingleUserState) {<br>    <em>if </em>(getSingleUserState <em>is </em>GetSingleUserLoaded) {<br>      <em>final </em>currentUser = getSingleUserState.user;<br>      <em>return </em>Scaffold(<br>        backgroundColor: backGroundColor,<br>        bottomNavigationBar: CupertinoTabBar(<br>          backgroundColor: backGroundColor,<br>          items: [<br>            BottomNavigationBarItem(icon: Icon(MaterialCommunityIcons.<em>home_variant</em>, color: primaryColor), label: &quot;&quot;),<br>            BottomNavigationBarItem(icon: Icon(Ionicons.<em>md_search</em>, color: primaryColor), label: &quot;&quot;),<br>            BottomNavigationBarItem(icon: Icon(Ionicons.<em>md_add_circle</em>, color: primaryColor), label: &quot;&quot;),<br>            BottomNavigationBarItem(icon: Icon(Icons.<em>favorite</em>, color: primaryColor), label: &quot;&quot;),<br>            BottomNavigationBarItem(icon: Icon(Icons.<em>account_circle_outlined</em>, color: primaryColor), label: &quot;&quot;),<br>          ],<br>          onTap: navigationTapped,<br>        ),<br>        body: PageView(<br>          controller: pageController,<br>          children: [<br>            HomePage(),<br>            SearchPage(),<br>            UploadPostPage(),<br>            ActivityPage(),<br>            ProfilePage()<br>          ],<br>          onPageChanged: onPageChanged,<br>        ),<br>      );<br>    }<br>    <em>return </em>Center(child: CircularProgressIndicator(),);<br>  },<br>);</pre><p>After doing this, if you hot restart your application you will see circular progress indicator on your emulator.</p><p>To avoid this in the same page (MainScreen), in the <strong>initState</strong> call the <strong>getSingleUser</strong> method from the <strong>GetSingleUserCubit</strong> and pass the <strong>uid</strong> inside.</p><pre>@override<br><br><em>void </em>initState() {<br>  BlocProvider.<em>of</em>&lt;GetSingleUserCubit&gt;(context).getSingleUser(uid: widget.uid);<br>  pageController = PageController();<br>  <em>super</em>.initState();<br>}</pre><p>Now the indicator will be gone.</p><p>Only last thing to show up current user data from firestore database in the profile page.</p><p>Go to Profile Page create a final field <strong>UserEntity</strong> and pass it in the constructor.</p><pre><em>class </em>ProfilePage <em>extends </em>StatelessWidget {<br>  <em>final </em>UserEntity currentUser;<br>  <em>const </em>ProfilePage({Key? key, <em>required this</em>.currentUser}) : <em>super</em>(key: key);</pre><p>You will see compile time error in <strong>MainScreen()</strong> page. Now in the list of pages one of them Profile Page require <strong>currentUser</strong> (UserEntity) as we got the current user from <strong>GetSingleUserCubit</strong> and is stored in a variable <strong>currentUser</strong> so pass it simply in here.</p><pre>PageView(<br>  controller: pageController,<br>  children: [<br>    HomePage(),<br>    SearchPage(),<br>    UploadPostPage(),<br>    ActivityPage(),<br>    ProfilePage(currentUser: currentUser,)<br>  ],<br>  onPageChanged: onPageChanged,<br>),</pre><p>That was it for the Main Screen.</p><p><strong>Profile Page:</strong></p><p>Access all the data from the UserEntity in the profile page by removing all the dummy data.</p><p><strong>profile_page.dart</strong></p><pre><em>class </em>ProfilePage <em>extends </em>StatelessWidget {<br>  <em>final </em>UserEntity currentUser;<br>  <em>const </em>ProfilePage({Key? key, <em>required this</em>.currentUser}) : <em>super</em>(key: key);<br><br>  @override<br><br>  Widget build(BuildContext context) {<br>    <em>return </em>Scaffold(<br>      backgroundColor: backGroundColor,<br>      appBar: AppBar(<br>        backgroundColor: backGroundColor,<br>        title: Text(&quot;${currentUser.username}&quot;, style: TextStyle(color: primaryColor),),<br>        actions: [<br>          Padding(<br>            padding: <em>const </em>EdgeInsets.only(right: 10.0),<br>            child: InkWell(<br>            onTap: () {<br>              _openBottomModalSheet(context);<br>            },child: Icon(Icons.<em>menu</em>, color: primaryColor,)),<br>          )<br>        ],<br>      ),<br>      body: Padding(<br>        padding: <em>const </em>EdgeInsets.symmetric(horizontal: 10.0, vertical: 10),<br>        child: SingleChildScrollView(<br>          child: Column(<br>            crossAxisAlignment: CrossAxisAlignment.start,<br>            children: [<br>              Row(<br>                mainAxisAlignment: MainAxisAlignment.spaceBetween,<br>                children: [<br>                  Container(<br>                    width: 80,<br>                    height: 80,<br>                    decoration: BoxDecoration(<br>                      color: secondaryColor,<br>                      shape: BoxShape.circle<br>                    ),<br>                  ),<br>                  Row(<br>                    children: [<br>                      Column(<br>                        children: [<br>                          Text(&quot;${currentUser.totalPosts}&quot;, style: TextStyle(color: primaryColor, fontWeight: FontWeight.<em>bold</em>),),<br>                          sizeVer(8),<br>                         Text(&quot;Posts&quot;, style: TextStyle(color: primaryColor),)<br>                        ],<br>                      ),<br>                      sizeHor(25),<br>                      Column(<br>                        children: [<br>                          Text(&quot;${currentUser.totalFollowers}&quot;, style: TextStyle(color: primaryColor, fontWeight: FontWeight.<em>bold</em>),),<br>                          sizeVer(8),<br>                          Text(&quot;Followers&quot;, style: TextStyle(color: primaryColor),)<br>                        ],<br>                      ),<br>                      sizeHor(25),<br>                      Column(<br>                        children: [<br>                          Text(&quot;${currentUser.totalFollowing}&quot;, style: TextStyle(color: primaryColor, fontWeight: FontWeight.<em>bold</em>),),<br>                          sizeVer(8),<br>                          Text(&quot;Following&quot;, style: TextStyle(color: primaryColor),)<br>                        ],<br>                      )<br>                    ],<br>                  )<br>                ],<br>              ),<br>              sizeVer(10),<br>              Text(&quot;${currentUser.name == &quot;&quot;? currentUser.username : currentUser.name}&quot;, style: TextStyle(color: primaryColor,fontWeight: FontWeight.<em>bold</em>),),<br>              sizeVer(10),<br>              Text(&quot;${currentUser.bio}&quot;, style: TextStyle(color: primaryColor),),<br>              sizeVer(10),<br>              GridView.builder(itemCount: 32, physics: ScrollPhysics(), shrinkWrap: <em>true</em>,gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3, crossAxisSpacing: 5, mainAxisSpacing: 5), itemBuilder: (context, index) {<br>                <em>return </em>Container(<br>                  width: 100,<br>                  height: 100,<br>                  color: secondaryColor,<br>                );<br>              })<br>            ],<br>          ),<br>        ),<br>      )<br>    );<br>  }<br>}</pre><p><strong>Solution Code:</strong></p><p>GitHub: <a href="https://github.com/AdnanKhan45">https://github.com/AdnanKhan45</a>/instagram-app-clone</p><p><strong>Conclusion:</strong></p><p>We’ve successfully called all the methods in our UI. In the next part we will learn about Firebase Cloud Storage and also to edit user profile. That will be the last part of user and then we will go for the next steps. In order to not miss the upcoming video be sure to subscribe to eTechViral and hit the bell Icon to make sure you get notified whenever new video is uploaded.</p><p>Website: <a href="https://www.etechviral.com/">https://www.etechviral.com</a></p><p>YouTube: <a href="https://www.youtube.com/channel/UCO6gMNHYhRqyzbskNh4gG_A">https://www.youtube.com/channel/UCO6gMNHYhRqyzbskNh4gG_A</a></p><p>eTechViral Instagram: <a href="https://www.instagram.com/etechviral/">https://www.instagram.com/etechviral/</a></p><p>Have any Questions? Find me on:</p><p>GitHub: <a href="https://github.com/AdnanKhan45">https://github.com/AdnanKhan45</a></p><p>LinkedIn: <a href="https://www.linkedin.com/in/adnan-khan-23bb8821b/">https://www.linkedin.com/in/adnan-khan-23bb8821b/</a></p><p>Instagram: <a href="https://www.instagram.com/dev.adnankhan">https://www.instagram.com/dev.adnankhan</a></p><p>Twitter: <a href="https://twitter.com/Adnan54M">https://twitter.com/Adnan54M</a></p><p>Facebook: <a href="https://web.facebook.com/profile.php?id=100011793480431">https://web.facebook.com/profile.php?id=100011793480431</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ac50e6ba74c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[instaInstagram Clone Clean Architecture — Part 9]]></title>
            <link>https://medium.com/@ak187429/instainstagram-clone-clean-architecture-part-9-98c30f7f2dd9?source=rss-12fbddea09ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/98c30f7f2dd9</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[dependency-inversion]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <dc:creator><![CDATA[Muhammad Adnan]]></dc:creator>
            <pubDate>Mon, 22 Aug 2022 15:43:11 GMT</pubDate>
            <atom:updated>2022-08-30T14:05:06.560Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Instagram Clone Clean Architecture — Part 9</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Usxg9yzpypNNmWQmzbJnLQ.png" /></figure><p>We’re almost done with our app user methods, and app architecture. We got small pieces of code in out app which is separated according to the principle of the <strong>Clean Architecture</strong>. Now before going forward and utilize them in UI we must notice one thing. We have many classes and are decoupled from its dependencies, and accepting these dependencies through the constructor. But we somehow, have to pass in them.</p><p><strong>Dependency Injection:</strong></p><figure><img alt="injection" src="https://cdn-images-1.medium.com/max/512/1*MC7zR1u2LbFQ2mjKKT9rEw.png" /></figure><p>Almost, every class has some dependencies, if look at the <strong>FirebaseRepositoryImpl</strong> and also <strong>FirebaseRemoteDataSourceImpl</strong>. There are multiple service locators but we will use <a href="https://pub.dev/packages/get_it">get_it</a> in this series, this is a simple service locator for Dart and Flutter, and can be used instead of <strong>InheritedWidget</strong> and <strong>Provider</strong>.</p><p>So far we’ve created many classes, we will go over all of them, from top <strong>Presentation Logic Holders</strong> (<strong>Cubits</strong>) to the downward <strong>Remote Data Sources</strong>.</p><figure><img alt="clean architecture structure" src="https://cdn-images-1.medium.com/max/1024/1*XVk_LR1z1I7TgKw01o3q-g.png" /></figure><p>Let’s create an initial setup in a new file and name it <strong>injection_container</strong>. This file will be located in the <strong>lib</strong> directory. Basic structure of our file will look something like this.</p><p><strong>Injection_container.dart</strong></p><pre><em>import </em>&#39;package:get_it/get_it.dart&#39;;<br> <br> <em>final </em>sl = GetIt.<em>instance</em>;<br> <br> Future&lt;<em>void</em>&gt; init() <em>async </em>{<br>   <em>// Cubits<br> <br>   // Use Cases<br> <br>   // Repository<br> <br>   // Remote Data Source<br><br>   // Externals<br> </em>}</pre><p>This <strong>init()</strong> method will be called when our app starts from main.dart inside this<strong> init()</strong> all the classes and contracts will be registered and subsequently also injected using the singleton instance of <strong>GetIt</strong> stored inside the <strong>sl </strong>(which is shortened of service locator).</p><p>The get_it package provide creating singletons and factory instances and many other methods. In this article we’re only going to touch the <strong>registerFactory</strong>, <strong>registerSingleton </strong>and <strong>registerLazySingleton</strong>. As you can see the first comment Cubits, first we’re going to register Cubits.</p><p><strong>Register Factory:</strong></p><figure><img alt="factory" src="https://cdn-images-1.medium.com/max/512/1*O4vC4UOOUf9A_oWIMb9fLw.png" /></figure><p>Factory registration provide new instance of the class after each call to it. And this is a good way of registering View Models or in our case Cubits. The process of registration is pretty much simple. GetIt class has call() method, very similar to our use cases have call() method</p><p><strong>Injection_container.dart</strong></p><pre><em>// Cubits<br><br></em>sl.registerFactory(<br>      () =&gt; AuthCubit(<br>    signOutUseCase: sl.call(),<br>    isSignInUseCase: sl.call(),<br>    getCurrentUidUseCase: sl.call(),<br>  ),<br>);</pre><p>By using type inference, the sl.call() will determine which object should pass in the constructor argument. You are right! This can become possible when the type is also registered. It’s clear now we also should register the use cases.</p><p><strong>Note: </strong>Presentation logic holders should not be registered as singletons. Because your app do have multiple pages like our app Instagram have multiple pages, when we navigate between pages, we probably want to do some clean up like closing streams. Like when we navigate from one page to the next we closed one opened stream and when we back to the same page we want new instance of Cubit to rebuild it.</p><p>In case if we use singletons and navigate between pages, we will be using closed streams when we back to the same page instead of creating the new instance with opened Stream.</p><p>Because the get_it singletons create one instance, cache it and use it throughout the lifetime of the app. It do not create new instance.</p><p>Finally by registering all the Cubits injection_container.dart will looks something like this:</p><p><strong>Injection_container.dart</strong></p><pre><em>// Cubits<br> </em>sl.registerFactory(<br>   () =&gt; AuthCubit(<br>     signOutUseCase: sl.call(),<br>     isSignInUseCase: sl.call(),<br>     getCurrentUidUseCase: sl.call(),<br>   ),<br> );<br> <br> sl.registerFactory(<br>       () =&gt; CredentialCubit(<br>         signUpUseCase: sl.call(),<br>         signInUserUseCase: sl.call(),<br>   ),<br> );<br> <br> sl.registerFactory(<br>       () =&gt; UserCubit(<br>         updateUserUseCase: sl.call(),<br>         getUsersUseCase: sl.call()<br>   ),<br> );</pre><p><strong>Register Singletons:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*DofTXyZMvAAknuMxTJLuqQ.png" /></figure><p>As mentioned earlier we’ve two kind of singletons. That are registerSingleton and registerLazySingleton. The difference between them is the regular <strong>non-lazy</strong> singleton is registered immediately after the app starts, while the <strong>lazy</strong> singleton is only registered when it’s requested as a dependency for some other class.</p><p><strong>Cubit Dependencies:</strong></p><p>In our app we will use registerLazySingleton to register our Cubit’s dependencies which are Use Cases. These lazy singletons will create only one instance and will use it throughout lifetime of the app. These registrations will go down below the Use Cases comment.</p><p>After registration of all the Use Cases our injection container will look like this:</p><p><strong>Injection_container.dart</strong></p><pre><em>// Use Cases<br><br></em>sl.registerLazySingleton(() =&gt; SignOutUseCase(repository: sl.call()));<br><br>sl.registerLazySingleton(() =&gt; IsSignInUseCase(repository: sl.call()));<br><br>sl.registerLazySingleton(() =&gt; GetCurrentUidUseCase(repository: sl.call()));<br><br>sl.registerLazySingleton(() =&gt; SignUpUseCase(repository: sl.call()));<br><br>sl.registerLazySingleton(() =&gt; SignInUserUseCase(repository: sl.call()));<br><br>sl.registerLazySingleton(() =&gt; UpdateUserUseCase(repository: sl.call()));<br><br>sl.registerLazySingleton(() =&gt; GetUsersUseCase(repository: sl.call()));<br><br>sl.registerLazySingleton(() =&gt; CreateUserUseCase(repository: sl.call()));<br><br>sl.registerLazySingleton(() =&gt; GetSingleUserUseCase(repository: sl.call()));</pre><p><strong>Register Repository:</strong></p><figure><img alt="repository" src="https://cdn-images-1.medium.com/max/512/1*vY9NBJ0HpB2OsmYNISaUGQ.png" /></figure><p>To register the Repository we will again use registerLazySingleton, and if you notice this FirebaseRepository is an abstract class or a contract and cannot be instantiated but instead we will instantiate its Implementation of repository. This can become possible by specifying the type parameter on the registerLazySingleton method.</p><pre><em>// Repository<br> </em>sl.registerLazySingleton&lt;FirebaseRepository&gt;(() =&gt; FirebaseRepositoryImpl(remoteDataSource: sl.call()));</pre><p><strong>Register Data Sources:</strong></p><p>As the <strong>FirebaseRepositoryImpl </strong>has dependency <strong>remoteDataSource </strong>we also should register that type.</p><pre><em>// Remote Data Source<br> </em>sl.registerLazySingleton&lt;FirebaseRemoteDataSource&gt;(() =&gt; FirebaseRemoteDataSourceImpl(firebaseFirestore: sl.call(), firebaseAuth: sl.call()));</pre><p>After registration of Firebase Repository and Remote Data Source the code will look like:</p><pre><em>// Repository<br> <br> </em>sl.registerLazySingleton&lt;FirebaseRepository&gt;(() =&gt; FirebaseRepositoryImpl(remoteDataSource: sl.call()));<br> <br> <em>// Remote Data Source<br> </em>sl.registerLazySingleton&lt;FirebaseRemoteDataSource&gt;(() =&gt; FirebaseRemoteDataSourceImpl(firebaseFirestore: sl.call(), firebaseAuth: sl.call()));</pre><p><strong>External Dependencies:</strong></p><figure><img alt="external" src="https://cdn-images-1.medium.com/max/512/1*9CRh3nPXp9hTSKdkWfqyow.png" /></figure><p>We’ve come all the way down from Presentation Logic Holders (Cubits) to the 3rd party libraries. Now we need to register the FirebaseFirestore and FirebaseAuth also. This last one will be a bit different from all of the registration above.</p><p>First you need to take the instance of them and then register as lazy singleton.</p><p><strong>Injection_container.dart</strong></p><pre><em>// Externals<br> <br> final </em>firebaseFirestore = FirebaseFirestore.<em>instance</em>;<br> <em>final </em>firebaseAuth = FirebaseAuth.<em>instance</em>;<br> <br> sl.registerLazySingleton(() =&gt; firebaseFirestore);<br> sl.registerLazySingleton(() =&gt; firebaseAuth);</pre><p><strong>Finishing up:</strong></p><p><strong>Go to &gt; main.dart</strong> and initialize that <strong>init()</strong> method same as we did for firebase.</p><pre><em>import </em>&#39;injection_container.dart&#39; <em>as </em>di;</pre><pre>Future main() <em>async </em>{<br>   WidgetsFlutterBinding.<em>ensureInitialized</em>();<br>   <em>await </em>Firebase.<em>initializeApp</em>();<br>   <em>await </em>di.init();<br>   runApp(MyApp());<br> }</pre><p><strong>Solution Code:</strong></p><p><strong>injection_container.dart</strong></p><pre><em>import </em>&#39;package:cloud_firestore/cloud_firestore.dart&#39;;<br> <em>import </em>&#39;package:firebase_auth/firebase_auth.dart&#39;;<br> <em>import </em>&#39;package:get_it/get_it.dart&#39;;<br> <em>import </em>&#39;package:instagram_clone_app/features/data/data_sources/remote_data_source/remote_data_source.dart&#39;;<br> <em>import </em>&#39;package:instagram_clone_app/features/data/data_sources/remote_data_source/remote_data_source_impl.dart&#39;;<br> <em>import </em>&#39;package:instagram_clone_app/features/data/repository/firebase_repository_impl.dart&#39;;<br> <em>import </em>&#39;package:instagram_clone_app/features/domain/repository/firebase_repository.dart&#39;;<br> <em>import </em>&#39;package:instagram_clone_app/features/domain/usecases/firebase_usecases/user/create_user_usecase.dart&#39;;<br> <em>import </em>&#39;package:instagram_clone_app/features/domain/usecases/firebase_usecases/user/get_current_uid_usecase.dart&#39;;<br> <em>import </em>&#39;package:instagram_clone_app/features/domain/usecases/firebase_usecases/user/get_single_user_usecase.dart&#39;;<br> <em>import </em>&#39;package:instagram_clone_app/features/domain/usecases/firebase_usecases/user/get_users_usecase.dart&#39;;<br> <em>import </em>&#39;package:instagram_clone_app/features/domain/usecases/firebase_usecases/user/is_sign_in_usecase.dart&#39;;<br> <em>import </em>&#39;package:instagram_clone_app/features/domain/usecases/firebase_usecases/user/sign_in_user_usecase.dart&#39;;<br> <em>import </em>&#39;package:instagram_clone_app/features/domain/usecases/firebase_usecases/user/sign_out_usecase.dart&#39;;<br> <em>import </em>&#39;package:instagram_clone_app/features/domain/usecases/firebase_usecases/user/sign_up_user_usecase.dart&#39;;<br> <em>import </em>&#39;package:instagram_clone_app/features/domain/usecases/firebase_usecases/user/update_user_usecase.dart&#39;;<br> <em>import </em>&#39;package:instagram_clone_app/features/presentation/cubit/auth/auth_cubit.dart&#39;;<br> <em>import </em>&#39;package:instagram_clone_app/features/presentation/cubit/credentail/credential_cubit.dart&#39;;<br> <em>import </em>&#39;package:instagram_clone_app/features/presentation/cubit/user/get_single_user/get_single_user_cubit.dart&#39;;<br> <em>import </em>&#39;package:instagram_clone_app/features/presentation/cubit/user/user_cubit.dart&#39;;<br> <br> <em>final </em>sl = GetIt.<em>instance</em>;<br> <br> Future&lt;<em>void</em>&gt; init() <em>async </em>{<br>   <em>// Cubits<br>   </em>sl.registerFactory(<br>     () =&gt; AuthCubit(<br>       signOutUseCase: sl.call(),<br>       isSignInUseCase: sl.call(),<br>       getCurrentUidUseCase: sl.call(),<br>     ),<br>   );<br> <br>   sl.registerFactory(<br>         () =&gt; CredentialCubit(<br>           signUpUseCase: sl.call(),<br>           signInUserUseCase: sl.call(),<br>     ),<br>   );<br> <br>   sl.registerFactory(<br>         () =&gt; UserCubit(<br>           updateUserUseCase: sl.call(),<br>           getUsersUseCase: sl.call()<br>     ),<br>   );<br> <br>   sl.registerFactory(<br>         () =&gt; GetSingleUserCubit(<br>         getSingleUserUseCase: sl.call()<br>     ),<br>   );<br> <br>   <em>// Use Cases<br>   </em>sl.registerLazySingleton(() =&gt; SignOutUseCase(repository: sl.call()));<br>   sl.registerLazySingleton(() =&gt; IsSignInUseCase(repository: sl.call()));<br>   sl.registerLazySingleton(() =&gt; GetCurrentUidUseCase(repository: sl.call()));<br>   sl.registerLazySingleton(() =&gt; SignUpUseCase(repository: sl.call()));<br>   sl.registerLazySingleton(() =&gt; SignInUserUseCase(repository: sl.call()));<br>   sl.registerLazySingleton(() =&gt; UpdateUserUseCase(repository: sl.call()));<br>   sl.registerLazySingleton(() =&gt; GetUsersUseCase(repository: sl.call()));<br>   sl.registerLazySingleton(() =&gt; CreateUserUseCase(repository: sl.call()));<br>   sl.registerLazySingleton(() =&gt; GetSingleUserUseCase(repository: sl.call()));<br>   <em>// Repository<br> <br>   </em>sl.registerLazySingleton&lt;FirebaseRepository&gt;(() =&gt; FirebaseRepositoryImpl(remoteDataSource: sl.call()));<br> <br>   <em>// Remote Data Source<br>   </em>sl.registerLazySingleton&lt;FirebaseRemoteDataSource&gt;(() =&gt; FirebaseRemoteDataSourceImpl(firebaseFirestore: sl.call(), firebaseAuth: sl.call()));<br> <br> <br>   <em>// Externals<br> <br>   final </em>firebaseFirestore = FirebaseFirestore.<em>instance</em>;<br>   <em>final </em>firebaseAuth = FirebaseAuth.<em>instance</em>;<br> <br>   sl.registerLazySingleton(() =&gt; firebaseFirestore);<br>   sl.registerLazySingleton(() =&gt; firebaseAuth);<br> }</pre><p><strong>main.dart</strong></p><pre>Future main() <em>async </em>{<br>   WidgetsFlutterBinding.<em>ensureInitialized</em>();<br>   <em>await </em>Firebase.<em>initializeApp</em>();<br>   <em>await </em>di.init();<br>   runApp(MyApp());<br> }}</pre><p><strong>Conclusion:</strong></p><p>Dependency injection is a programming technique that makes a class independent of its dependencies. It achieves that by decoupling the usage of an object from its creation. In the next article we’ll finally go for calling the methods in our UI and will see all the code we’ve done so far in action. In order to not miss the upcoming video be sure to subscribe to eTechViral and hit the bell Icon to make sure you get notified whenever new video is uploaded.</p><p>Website: <a href="https://www.etechviral.com/">https://www.etechviral.com</a></p><p>YouTube: <a href="https://www.youtube.com/channel/UCO6gMNHYhRqyzbskNh4gG_A">https://www.youtube.com/channel/UCO6gMNHYhRqyzbskNh4gG_A</a></p><p>eTechViral Instagram: <a href="https://www.instagram.com/etechviral/">https://www.instagram.com/etechviral/</a></p><p>Have any Questions? Find me on:</p><p>GitHub: <a href="https://github.com/AdnanKhan45">https://github.com/AdnanKhan45</a></p><p>LinkedIn: <a href="https://www.linkedin.com/in/adnan-khan-23bb8821b/">https://www.linkedin.com/in/adnan-khan-23bb8821b/</a></p><p>Instagram: <a href="https://www.instagram.com/dev.adnankhan">https://www.instagram.com/dev.adnankhan</a></p><p>Twitter: <a href="https://twitter.com/Adnan54M">https://twitter.com/Adnan54M</a></p><p>Facebook: <a href="https://web.facebook.com/profile.php?id=100011793480431">https://web.facebook.com/profile.php?id=100011793480431</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98c30f7f2dd9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Instagram Clone Clean Architecture — Part 8]]></title>
            <link>https://medium.com/@ak187429/instagram-clone-clean-architecture-part-8-a38a0543cde9?source=rss-12fbddea09ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/a38a0543cde9</guid>
            <category><![CDATA[bloc]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[cubit]]></category>
            <category><![CDATA[androidev]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <dc:creator><![CDATA[Muhammad Adnan]]></dc:creator>
            <pubDate>Fri, 19 Aug 2022 16:22:43 GMT</pubDate>
            <atom:updated>2022-08-19T16:22:43.879Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Instagram Clone Clean Architecture — Part 8</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A7httiItUIYt3zzljSZugw.png" /></figure><p>Every developer in this universe write code, but it sounds really nice when someone says this developer writes clean code. As flutter framework got only Dart language to write UI code and also business logic, so everything become messy when both UI code and business logic mix up.</p><p><strong>Question: </strong>How do we can stop our code from being messy?</p><p><strong>Note:</strong> We’re already using Clean Architecture for separation of concern but this situation is different.</p><p><strong>Answer: </strong>There comes our Bloc library but we will use its lighter version Cubit which removes bunch of boilerplate code, Cubit not required any kind of package to add but its comes with the package <strong>flutter_bloc</strong> of version 6.0.0 or above.</p><p><strong>Don’t know what is Bloc?</strong></p><p><strong>Bloc</strong> is well-known and established state management library for flutter, which promotes <strong>immutability</strong> and has one of the best ecosystems of <strong>supporting packages</strong> and documentation built around it.</p><p><strong>Don’t know what is Cubit?</strong></p><p><strong>Cubit</strong> is lightweight state management solution. It is subset of the bloc package that does not rely on events and instead uses methods to emit new states. Every <strong>Cubit</strong> requires an initial state which will be the state of the Cubit before emit has been called.</p><p><strong>Bloc</strong></p><p>If you’ve used the bloc in past you may be familiar with this diagram.</p><figure><img alt="bloc architecture" src="https://cdn-images-1.medium.com/max/800/1*V_TQw6xQSCdLj7elNoGVwg.png" /></figure><p>This Bloc architecture self-explained. Let’s understand it, In Bloc we’ve Events and States and Bloc itself.</p><p><strong>·</strong> <strong>Event:</strong> Events tell bloc to do something, Triggered button click, method call etc.</p><p><strong>·</strong> <strong>State:</strong> States represent the info to be processed by any widget, Initial, Loading, Loaded and Failure State etc.</p><p><strong>·</strong> <strong>Bloc:</strong> All the business logic take place inside the Bloc, It accept events, perform the logic and output states.</p><p>In General: We’ve events (click, trigger, call) and states (initial, loading, loaded etc.) Bloc accept events perform the logic and output a specific state.</p><p><strong>Cubit</strong></p><p>If you’ve used the cubit in past you may be familiar with this diagram.</p><figure><img alt="cubit architecture" src="https://cdn-images-1.medium.com/max/800/1*4nruMaeNKUBy_p5X9QyLag.png" /></figure><p>This Cubit architecture is also self-explained. Let’s understand it, in cubit we’ve States and Cubit itself.</p><p>· <strong>State:</strong> States represent the info to be processed by any widget, Initial, Loading, Loaded and Failure State etc.</p><p><strong>·</strong> <strong>Cubit: </strong>Cubit exposes direct functions and outputs appropriate states.</p><p>In General: We’ve States (Initial, Loading, Loaded and Failure), Cubit directly take functions and emits an appropriate state.</p><p><strong>Create Directories:</strong></p><p><strong>Go to &gt; presentation &gt; cubit</strong> and create 3 directories, <strong>user</strong>, <strong>credential</strong> and <strong>auth</strong>. Now create cubit class inside all of them with specific names.</p><figure><img alt="directories" src="https://cdn-images-1.medium.com/max/320/1*8emQvVYKGbUVg7-lJ9Jolw.png" /></figure><p>If you’re using <strong>Android Studio</strong> install a plugin of <strong>Bloc</strong>.</p><p><strong>Go to File &gt; Settings &gt; Plugins &gt;</strong> Market Place install <strong>Bloc</strong>.</p><p>If you’re using <strong>VS Code</strong> install and extension of <strong>Bloc</strong>.</p><p>After creating <strong>Cubit Classes</strong> your directories will look something like this:</p><figure><img alt="cubit directories structure" src="https://cdn-images-1.medium.com/max/363/1*VGdvCaL3H1cnvBqhOjwYvQ.png" /></figure><p><strong>Auth Cubit:</strong></p><p><strong>auth_state.dart</strong></p><pre><em>part of </em>&#39;auth_cubit.dart&#39;;<br> <br> <em>abstract class </em>AuthState <em>extends </em>Equatable {<br>   <em>const </em>AuthState();<br> }<br> <em>class </em>AuthInitial <em>extends </em>AuthState {<br>   @override<br>   List&lt;Object&gt; <em>get </em>props =&gt; [];<br> }<br> <em>class </em>Authenticated <em>extends </em>AuthState {<br>   <em>final </em>String uid;<br>   Authenticated({<em>required this</em>.uid});<br>   @override<br>   List&lt;Object&gt; <em>get </em>props =&gt; [uid];<br> }<br> <em>class </em>UnAuthenticated <em>extends </em>AuthState {<br>   @override<br>   List&lt;Object&gt; <em>get </em>props =&gt; [];<br> }</pre><p><strong>auth_cubit.dart</strong></p><pre><em>import </em>&#39;package:bloc/bloc.dart&#39;;<br><em>import </em>&#39;package:equatable/equatable.dart&#39;;<br><em>import </em>&#39;package:flutter/cupertino.dart&#39;;<br><em>import </em>&#39;package:instagram_clone_app/features/domain/usecases/firebase_usecases/user/get_current_uid_usecase.dart&#39;;<br><em>import </em>&#39;package:instagram_clone_app/features/domain/usecases/firebase_usecases/user/is_sign_in_usecase.dart&#39;;<br><em>import </em>&#39;package:instagram_clone_app/features/domain/usecases/firebase_usecases/user/sign_out_usecase.dart&#39;;<br><br><em>part </em>&#39;auth_state.dart&#39;;<br><br><em>class </em>AuthCubit <em>extends </em>Cubit&lt;AuthState&gt; {<br>  <em>final </em>SignOutUseCase signOutUseCase;<br>  <em>final </em>IsSignInUseCase isSignInUseCase;<br>  <em>final </em>GetCurrentUidUseCase getCurrentUidUseCase;<br><br>  AuthCubit({<em>required this</em>.signOutUseCase, <em>required this</em>.isSignInUseCase, <em>required this</em>.getCurrentUidUseCase}) : <em>super</em>(AuthInitial());<br><br><br><br>  Future&lt;<em>void</em>&gt; appStarted(BuildContext context) <em>async </em>{<br><br>    <em>try </em>{<br>      bool isSignIn = <em>await </em>isSignInUseCase.call();<br>      <em>if </em>(isSignIn == <em>true</em>) {<br><br>        <em>final </em>uid = <em>await </em>getCurrentUidUseCase.call();<br>        emit(Authenticated(uid: uid));<br>      } <em>else </em>{<br>        emit(UnAuthenticated());<br>      }<br>    } <em>catch</em>(_) {<br>      emit(UnAuthenticated());<br>    }<br>  }<br><br>  Future&lt;<em>void</em>&gt; loggedIn() <em>async </em>{<br>    <em>try </em>{<br>      <em>final </em>uid = <em>await </em>getCurrentUidUseCase.call();<br>      emit(Authenticated(uid: uid));<br>    } <em>catch</em>(_) {<br>      emit(UnAuthenticated());<br>    }<br>  }<br><br>  Future&lt;<em>void</em>&gt; loggedOut()<em>async </em>{<br>    <em>try </em>{<br>      <em>await </em>signOutUseCase.call();<br>      emit(UnAuthenticated());<br>    } <em>catch </em>(_) {<br>      emit(UnAuthenticated());<br>    }<br>  }<br>}</pre><p><strong>Credential Cubit:</strong></p><p><strong>credential_state.dart</strong></p><pre>part of &#39;credential_cubit.dart&#39;;<br> <br> abstract <em>class </em>CredentialState <em>extends </em>Equatable {<br>   <em>const </em>CredentialState();<br> }<br> <br> <em>class </em>CredentialInitial <em>extends </em>CredentialState {<br>   @override<br>   List&lt;Object&gt; get props =&gt; [];<br> }<br> <br> <em>class </em>CredentialLoading <em>extends </em>CredentialState {<br>   @override<br>   List&lt;Object&gt; get props =&gt; [];<br> }<br> <br> <em>class </em>CredentialSuccess <em>extends </em>CredentialState {<br>   @override<br>   List&lt;Object&gt; get props =&gt; [];<br> }<br> <br> <em>class </em>CredentialFailure <em>extends </em>CredentialState {<br>   @override<br>   List&lt;Object&gt; get props =&gt; [];<br> }</pre><p><strong>credential_cubit.dart</strong></p><pre><em>import </em>&#39;dart:io&#39;;<br><br><br><br><em>import </em>&#39;package:bloc/bloc.dart&#39;;<br><br><em>import </em>&#39;package:equatable/equatable.dart&#39;;<br><br><em>import </em>&#39;package:instagram_clone_app/features/domain/entities/user/user_entity.dart&#39;;<br><br><em>import </em>&#39;package:instagram_clone_app/features/domain/usecases/firebase_usecases/user/sign_in_user_usecase.dart&#39;;<br><br><em>import </em>&#39;package:instagram_clone_app/features/domain/usecases/firebase_usecases/user/sign_up_user_usecase.dart&#39;;<br><br><em>part </em>&#39;credential_state.dart&#39;;<br><br><em>class </em>CredentialCubit <em>extends </em>Cubit&lt;CredentialState&gt; {<br><br>  <em>final </em>SignInUserUseCase signInUserUseCase;<br>  <em>final </em>SignUpUseCase signUpUseCase;<br>  CredentialCubit({<em>required this</em>.signInUserUseCase, <em>required this</em>.signUpUseCase}) : <em>super</em>(CredentialInitial());<br><br>  Future&lt;<em>void</em>&gt; signInUser({<em>required </em>String email, <em>required </em>String password}) <em>async </em>{<br>    emit(CredentialLoading());<br><br>    <em>try </em>{<br>      <em>await </em>signInUserUseCase.call(UserEntity(email: email, password: password));<br>      emit(CredentialSuccess());<br>    } <em>on </em>SocketException <em>catch</em>(_) {<br>      emit(CredentialFailure());<br>    } <em>catch </em>(_) {<br>      emit(CredentialFailure());<br>    }<br>  }<br><br>  Future&lt;<em>void</em>&gt; signUpUser({<em>required </em>UserEntity user}) <em>async </em>{<br><br>    emit(CredentialLoading());<br>    <em>try </em>{<br>      <em>await </em>signInUserUseCase.call(user);<br>      emit(CredentialSuccess());<br>    } <em>on </em>SocketException <em>catch</em>(_) {<br>      emit(CredentialFailure());<br>    } <em>catch </em>(_) {<br>      emit(CredentialFailure());<br>    }<br>  }<br>}</pre><p><strong>User Cubit:</strong></p><p><strong>user_state.dart</strong></p><pre><em>part of </em>&#39;user_cubit.dart&#39;;<br><br><br><br><em>abstract class </em>UserState <em>extends </em>Equatable {<br>  <em>const </em>UserState();<br>}<br><br><em>class </em>UserInitial <em>extends </em>UserState {<br>  @override<br>  List&lt;Object&gt; <em>get </em>props =&gt; [];<br><br>}<br><br><em>class </em>UserLoading <em>extends </em>UserState {<br>  @override<br>  List&lt;Object&gt; <em>get </em>props =&gt; [];<br><br>}<br><br><em>class </em>UserLoaded <em>extends </em>UserState {<br>  <em>final </em>List&lt;UserEntity&gt; users;<br>  UserLoaded({<em>required this</em>.users});<br>  @override<br>  List&lt;Object&gt; <em>get </em>props =&gt; [users];<br><br>}<br><br><em>class </em>UserFailure <em>extends </em>UserState {<br>  @override<br>  List&lt;Object&gt; <em>get </em>props =&gt; [];<br>}</pre><p><strong>user_cubit.dart</strong></p><pre><em>import </em>&#39;dart:io&#39;;<br><br><br><br><em>import </em>&#39;package:bloc/bloc.dart&#39;;<br><br><em>import </em>&#39;package:equatable/equatable.dart&#39;;<br><br><em>import </em>&#39;package:instagram_clone_app/features/domain/entities/user/user_entity.dart&#39;;<br><br><em>import </em>&#39;package:instagram_clone_app/features/domain/usecases/firebase_usecases/user/get_users_usecase.dart&#39;;<br><br><em>import </em>&#39;package:instagram_clone_app/features/domain/usecases/firebase_usecases/user/update_user_usecase.dart&#39;;<br>x<br><em>part </em>&#39;user_state.dart&#39;;<br><br><em>class </em>UserCubit <em>extends </em>Cubit&lt;UserState&gt; {<br>  <em>final </em>UpdateUserUseCase updateUserUseCase;<br>  <em>final </em>GetUsersUseCase getUsersUseCase;<br>  UserCubit({<em>required this</em>.updateUserUseCase, <em>required this</em>.getUsersUseCase}) : <em>super</em>(UserInitial());<br><br><br><br>  Future&lt;<em>void</em>&gt; getUsers({<em>required </em>UserEntity user}) <em>async </em>{<br><br>    emit(UserLoading());<br>    <em>try </em>{<br>      <em>final </em>streamResponse = getUsersUseCase.call(user);<br>      streamResponse.listen((users) {<br>        emit(UserLoaded(users: users));<br>      });<br>    } <em>on </em>SocketException <em>catch</em>(_) {<br>      emit(UserFailure());<br>    } <em>catch </em>(_) {<br>      emit(UserFailure());<br>    }<br>  }<br><br><br><br>  Future&lt;<em>void</em>&gt; updateUser({<em>required </em>UserEntity user}) <em>async </em>{<br><br>    <em>try </em>{<br>      <em>await </em>updateUserUseCase.call(user);<br>    } <em>on </em>SocketException <em>catch</em>(_) {<br>      emit(UserFailure());<br>    } <em>catch </em>(_) {<br>      emit(UserFailure());<br>    }<br>  }<br>}</pre><p><strong>Conclusion:</strong></p><p>We’ve successfully created Cubits for our User and in the next article we will explore dependency injection and also will call these methods. In order to not miss next video be sure to subscribe to the channel and hit the bell icon to make sure you get notified whenever the next video is uploaded.</p><p>Website: <a href="https://www.etechviral.com/">https://www.etechviral.com</a></p><p>YouTube: <a href="https://www.youtube.com/channel/UCO6gMNHYhRqyzbskNh4gG_A">https://www.youtube.com/channel/UCO6gMNHYhRqyzbskNh4gG_A</a></p><p>eTechViral Instagram: <a href="https://www.instagram.com/etechviral/">https://www.instagram.com/etechviral/</a></p><p>Have any Questions? Find me on:</p><p>GitHub: <a href="https://github.com/AdnanKhan45">https://github.com/AdnanKhan45</a></p><p>LinkedIn: <a href="https://www.linkedin.com/in/adnan-khan-23bb8821b/">https://www.linkedin.com/in/adnan-khan-23bb8821b/</a></p><p>Instagram: <a href="https://www.instagram.com/dev.adnankhan">https://www.instagram.com/dev.adnankhan</a></p><p>Twitter: <a href="https://twitter.com/Adnan54M">https://twitter.com/Adnan54M</a></p><p>Facebook: <a href="https://web.facebook.com/profile.php?id=100011793480431">https://web.facebook.com/profile.php?id=100011793480431</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a38a0543cde9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>