<?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 Nahit FIDANCI on Medium]]></title>
        <description><![CDATA[Stories by Nahit FIDANCI on Medium]]></description>
        <link>https://medium.com/@fnfidanci?source=rss-c17b8fc11bf6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*M_GsaN7WoIHYIV6pC01xag.jpeg</url>
            <title>Stories by Nahit FIDANCI on Medium</title>
            <link>https://medium.com/@fnfidanci?source=rss-c17b8fc11bf6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 01:56:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fnfidanci/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[How to Customize Notification Sounds on Android]]></title>
            <link>https://fnfidanci.medium.com/how-to-customize-notification-sounds-on-android-3f86df25f63a?source=rss-c17b8fc11bf6------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f86df25f63a</guid>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[notifications]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Nahit FIDANCI]]></dc:creator>
            <pubDate>Sun, 11 Aug 2024 21:41:54 GMT</pubDate>
            <atom:updated>2024-08-12T07:07:09.914Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oJo2TY86gYU8CmICou7clQ.png" /><figcaption>Custom Notification Sound on Flutter Android by <strong>Nahit Fidancı</strong></figcaption></figure><p>Hello everyone,</p><p>You might be familiar with handling notifications in Flutter using third-party plugins like flutter_local_notifications and awesome_notifications. However, there are times when you might prefer to manage notifications in a more traditional manner, such as with firebase_messaging.</p><p>On the iOS side, it’s not too complicated. You can simply import sound files (e.g., .wav, .aiff, .caf) into the root of your iOS folder. After that, you’ll need to add the sound name in your notification payload, but without the file extension. It would look something like this:</p><pre>{<br>  &quot;message&quot;: {<br>    &quot;token&quot;: &quot;your-registration-token&quot;,<br>    &quot;apns&quot;: {<br>      &quot;payload&quot;: {<br>        &quot;aps&quot;: {<br>          &quot;alert&quot;: {<br>            &quot;title&quot;: &quot;Notification Title&quot;,<br>            &quot;body&quot;: &quot;Notification Body&quot;<br>          },<br>          &quot;sound&quot;: &quot;your-custom-sound&quot; <br>        }<br>      }<br>    }<br>  }<br>}</pre><p>And with that, you’re all set for iOS. On the other hand, Android requires a few more steps — or at least, that’s been my experience. For some reason, the example payload below doesn’t seem to work as expected on Android.</p><pre>{<br>  &quot;message&quot;: {<br>    &quot;token&quot;: &quot;your-registration-token&quot;,<br>    &quot;android&quot;: {<br>      &quot;notification&quot;: {<br>        &quot;title&quot;: &quot;Notification Title&quot;,<br>        &quot;body&quot;: &quot;Notification Body&quot;,<br>        &quot;sound&quot;: &quot;your-custom-sound&quot; <br>      }<br>    }<br>  }<br>}</pre><p>Android doesn’t always play your custom notification sound, even if you follow the same steps that work on iOS.</p><h3>Manual set-up</h3><p>Usually, iOS is the problematic sibling among mobile platforms, but this time, Android decided to steal the show. We can’t play custom sounds because, guess what? We don’t have a custom notification channel. Voilà!</p><p>By default, there’s only the default notification channel, and your payload doesn’t specify which channel to use for notifications. So, the question arises: How do we create these elusive notification channels?</p><p>Well, here’s the kicker — Firebase Messaging plugin doesn’t support creating channels. At least, I couldn’t find any magical button for it. So, yes, you’ll have to get your hands dirty and dive into native Android code. It’s unavoidable.</p><p>First things first, we need a sound file, say, in WAV format. You’ll need to place it in the source directory. Assuming you’re not setting custom sounds for different flavors, go ahead and drop your sound files under android &gt; app &gt; src &gt; main &gt; res &gt; raw. And if you don’t see a raw directory, create one.</p><p>We’ll also need a few things:</p><ul><li><strong>channel_id</strong>: This is your notification channel, and it should be unique because it’ll be used in the notification payload.</li><li><strong>title</strong>: This will be visible in the notification settings of your phone.</li><li><strong>description</strong>: This is basically the same as the title.</li></ul><p>Let’s keep these values under resources. To do that, navigate to android &gt; app &gt; src &gt; main &gt; res &gt; values. If there’s no values folder, you’ll need to create one. Then, create a strings.xml file, and add your string resources like this:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;resources&gt;<br>    &lt;string name=&quot;message_channel_name&quot;&gt;Message Channel&lt;/string&gt;<br>    &lt;string name=&quot;message_channel_description&quot;&gt;This is used to receive chat message notifications&lt;/string&gt;<br>    &lt;string name=&quot;message_channel_id&quot;&gt;message_channel&lt;/string&gt;<br>&lt;/resources&gt;</pre><p>We’ll use the name attributes to access these strings later.</p><p>Now, it’s time to bring everything together. Head over to android &gt; app &gt; src &gt; main &gt; kotlin &gt; path/to/package &gt; MainActivity.kt and add the following code:</p><pre>package com.nahitfidanci.notification_example<br><br>import android.app.NotificationChannel<br>import android.app.NotificationManager<br>import android.media.AudioAttributes<br>import android.net.Uri<br>import android.os.Build<br>import android.os.Bundle<br>import io.flutter.embedding.android.FlutterActivity<br><br>class MainActivity : FlutterActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br><br>        initChatChannel()<br>    }<br><br>    private fun initChatChannel() {<br>        if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.O) {<br>            val channelId = getString(R.string.message_channel_id)<br>            val name = getString(R.string.message_channel_name)<br>            val descriptionText = getString(R.string.message_channel_description)<br>            val importance = NotificationManager.IMPORTANCE_DEFAULT<br>            val mChannel = NotificationChannel(channelId, name, importance)<br>            mChannel.description = descriptionText<br>            <br>            val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager<br>            notificationManager.createNotificationChannel(mChannel)<br>        }<br>    }<br><br>}</pre><p>So, we access our channel information via R.string. If you open the Android project in Android Studio, Intellisense should suggest the available string resources. If it doesn’t, no worries—just use the exact names you defined in the strings.xml file. The getString function helps us convert these resources to actual strings.</p><p>Now, we’ve created our notification channel. And here’s the kicker: after you send your notifications with the unique channel_id you’ve set here, you might still hear the default sound. How cool is that!</p><p>At this point, I assume you’re a bit confused. Trust me, I was too. It turns out that we need to set the sound during the channel creation process. Now, you might be asking:</p><blockquote>“Nahit, if we’re sending the sound name through the payload, why on earth do we need to set the sound here as well?”</blockquote><p>Well, my friend, I asked myself the exact same question and couldn’t find a satisfying answer. If you know what I’m missing, please leave a comment and fill us in!</p><p>Let’s make a small addition to the previous code.</p><pre>package com.nahitfidanci.notification_example<br><br>import android.app.NotificationChannel<br>import android.app.NotificationManager<br>import android.media.AudioAttributes<br>import android.net.Uri<br>import android.os.Build<br>import android.os.Bundle<br>import io.flutter.embedding.android.FlutterActivity<br><br>class MainActivity : FlutterActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br><br>        initChatChannel()<br>    }<br><br>    private fun initChatChannel() {<br>        if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.O) {<br>            val channelId = getString(R.string.message_channel_id)<br>            val name = getString(R.string.message_channel_name)<br>            val descriptionText = getString(R.string.message_channel_description)<br>            val importance = NotificationManager.IMPORTANCE_DEFAULT<br>            val mChannel = NotificationChannel(channelId, name, importance)<br>            mChannel.description = descriptionText<br>            // Set the custom sound URI<br>            val soundName = &quot;raw/message_tone&quot;<br>            val soundUri =<br>                Uri.parse(&quot;android.resource://${context.packageName}/&quot; + soundName)<br><br>            val audioAttributes = AudioAttributes.Builder()<br>                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)<br>                .setUsage(AudioAttributes.USAGE_NOTIFICATION)<br>                .build()<br><br>            mChannel.setSound(soundUri, audioAttributes)<br>            val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager<br>            notificationManager.createNotificationChannel(mChannel)<br>        }<br>    }<br><br>}</pre><p>We should be able to access the raw sound file similarly to how we retrieve string resources, but for some reason, I couldn’t get it to work. This is a workaround — I manually build the path myself. If you encounter a similar issue, you can create the sound path just as I did.</p><p>Once you’ve set up your notification channel, if you send a notification with the corresponding channel_id, you’ll hear the custom sound.</p><h3>Important Note</h3><p>Once you set a notification channel, you cannot change its settings. This includes the title, description, channel_id, and, of course, the sound. If a channel is created without a custom sound, you won’t be able to add one later. The only way for the user to see these changes is to permanently delete your app and reinstall it. Keep this in mind.</p><h3>Conclusion</h3><p>And there you have it — Android’s quirky notification channels in all their glory. Who knew setting a custom sound could turn into such a saga?</p><p>But hey, you’ve got this now. If this guide saved you some headaches (or at least gave you a chuckle), go ahead and hit that clap button. You’ve earned it!</p><p>Thank you for reading.</p><p><a href="https://www.nahitfidanci.com/">Website</a></p><p><a href="https://www.youtube.com/@nahitfidanci">Youtube</a></p><p><a href="https://github.com/dokumanx">Github</a></p><p><a href="https://www.linkedin.com/in/nahit-fidanci/">LinkedIn</a></p><p><a href="https://twitter.com/FerdaNahit">Twitter</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f86df25f63a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Right Way To Use Riverpod in Flutter]]></title>
            <link>https://fnfidanci.medium.com/the-right-way-to-use-riverpod-in-flutter-77869f9b741c?source=rss-c17b8fc11bf6------2</link>
            <guid isPermaLink="false">https://medium.com/p/77869f9b741c</guid>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[riverpod]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-bloc-pattern]]></category>
            <dc:creator><![CDATA[Nahit FIDANCI]]></dc:creator>
            <pubDate>Fri, 15 Mar 2024 13:41:12 GMT</pubDate>
            <atom:updated>2024-03-21T08:52:15.051Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M3gwBlV6G32IfUkpx8FpEQ.png" /></figure><p>Hi folks. Today, we will talk about how to use Riverpod in the right way. I have seen so many implementations and they seem to struggle to achieve a result that can be done in a much better and easy way. I will show you how I use Riverpod and I hope it will help you to see it from a different perspective.</p><p>I will not teach you the basics. You can learn it from the official <a href="https://riverpod.dev/">docs</a>. I will only show you how to better use the same instruments.</p><h3>Using Riverpod as a Presenter</h3><p>Sometimes you don&#39;t want to return a widget when a state changes. Sometimes, Riverpod plays just a presenter role. You don&#39;t need to draw a user info card. Or, you don’t need to keep an empty string as a state just to use Riverpod to access your login network call. No worries, you will understand what I mean.</p><p>Imagine that you have a login screen and you need an authentication flow. Your first choice is to use Riverpod. Yey! But you don’t know what to put as an initial state. You only need to be sure that you are authorized so you can navigate to the home screen. Then, what the hell in the world Riverpod’s state will do anything? You might put a dummy UserModel and then replace it with the real one when you are authorized. Doing so, you might navigate to the home screen too.</p><p>It might sound right but there are two mistakes here.</p><ul><li>You use Riverpod just to access your network layer. Which can be done by directly using them in UI(it is not the right way either).</li><li>You navigate inside Riverpod (with a global navigator key for example).</li></ul><p>Then, what can be done?</p><ul><li>Create an enum to keep track of the current state of authentication.</li><li>Listen to the state changes on the UI side and navigate if it is a success.</li></ul><p>Let’s take a look at the below example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b790ed004bdb8b8277af541fb84cc55/href">https://medium.com/media/8b790ed004bdb8b8277af541fb84cc55/href</a></iframe><p>You see? I let Riverpod do its job. I don’t rely on Riverpod to do the navigation. I only need to listen to the success state. It can be emitted by Riverpod, Bloc, or any other state management tool.</p><h3>Do you feel like you pass too much data across your app?</h3><p>Who doesn’t do that, does it? Well, It’s kind of a point why we use a state management tool. We don’t want to pass the state/data by hand. But even with Riverpod, you might do that. I will show you the wrong and right ways and explain why they are wrong or right.</p><h4>Wrong way</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6d20b1f488d50b83bedbf2e4f03f7fd/href">https://medium.com/media/a6d20b1f488d50b83bedbf2e4f03f7fd/href</a></iframe><p>I need to pass the current value ProductFilter every time I need to use GetProductsProvider. And if I am on the products page and change the filter, I need to call getProducts with the filter parameter. You can use another method to manually trigger the update. You might not show immediate effects on filter changes and let user decides when it will be applied. That’s alright. But, you still do not need to pass the filter value every time. When you feel that you are doing this. You need to rely on another provider to access ProductFilter .</p><h4>Right way</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8d4e126c3e0860200deeb282950bed1/href">https://medium.com/media/c8d4e126c3e0860200deeb282950bed1/href</a></iframe><p>You see? I don’t manually pass anything. getProductsProvider will fetch the product when the filter is changed. I know, in this version I cannot control when it should be fetched. Well, simply, I can do this though.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86d245abb8926895a492b4f4284f141f/href">https://medium.com/media/86d245abb8926895a492b4f4284f141f/href</a></iframe><p>I read the filter and fetch the product. Any state changes in ProductFilterProvider will not have any effects on GetProductsProvider . If I want to fetch, I just invalidate GetProductsProvider and it will run the build again.</p><p>Do you see? I don&#39;t try to make things harder. This is much easier than passing the data all the way. But if you don’t have such recurring cases, you can use parameters. Getting product details by product ID for example. Like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b0da08269b343d41173a05646a3311b/href">https://medium.com/media/5b0da08269b343d41173a05646a3311b/href</a></iframe><h3>Conclusion</h3><p>Thank you for reading so far. I hope that I helped you to see things from a different perspective today.</p><p>Don’t forget to follow me, give claps, and share the article if you find it helpful.</p><p>Thank you for reading.</p><p><a href="https://www.nahitfidanci.com/">Website</a></p><p><a href="https://www.youtube.com/@nahitfidanci">Youtube</a></p><p><a href="https://github.com/dokumanx">Github</a></p><p><a href="https://www.linkedin.com/in/nahit-fidanci/">LinkedIn</a></p><p><a href="https://twitter.com/FerdaNahit">Twitter</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77869f9b741c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use Injectable package in Dart?]]></title>
            <link>https://fnfidanci.medium.com/how-to-use-injectable-package-in-dart-adbb63a9044c?source=rss-c17b8fc11bf6------2</link>
            <guid isPermaLink="false">https://medium.com/p/adbb63a9044c</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Nahit FIDANCI]]></dc:creator>
            <pubDate>Tue, 09 Jan 2024 19:44:01 GMT</pubDate>
            <atom:updated>2024-01-09T19:44:01.668Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to inject dependencies?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AsQ4c_TTAstwwo827AM47w.png" /><figcaption>Inject dependencies with injectable package</figcaption></figure><p>Hello folks!</p><p>It’s been a while since my last <a href="https://fnfidanci.medium.com/how-to-secure-api-keys-in-flutter-41cfb31ae52a">article</a>. I got quite a reaction from you. You like that it is to the point. So, here is another.</p><h3>What is dependency injection?</h3><p>Let’s imagine that you want to make a smoothie. You need a blender and ingredients. What ingredients you choose affects the results but the process stays the same. So, ingredients can be changed. If you didn’t change them, you would have to drink the same smoothie forever.</p><p>Consider ingredients as dependencies. You want to change(inject) them freely. This is where the dependency injection term comes in. You say that I need ingredient type X. You will accept the type and use it as usual.</p><p>Let’s see a short example programmatically.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9eba1d2df399e4985ba21f9d0dc2b94/href">https://medium.com/media/e9eba1d2df399e4985ba21f9d0dc2b94/href</a></iframe><p>NotificationRepository is our contract(ingredient type). Each concrete class implements sendNotification method as they please. UserService doesn’t care which concrete class it gets. It only needs to have a NotificationRepository. Just like a blender. So, I can give/inject any concrete class that implements NotificationRepository . This is known as Dependency Injection .</p><h3>Why Injectable package?</h3><p>It is a wrapper around get_it service locator. Therefore, we also need to add get_it to pubspec.yaml. Injectable gives us an easy way to define dependencies. There are a bunch of terminological terms in Injectable but I only mention some of them. For more on that, you can check out the official <a href="https://pub.dev/packages/injectable">doc</a>.</p><p>Injectable is easier to use and manage. Thanks to injectable_generator you don’t manually give dependencies. It generates a file with all your dependencies set as you wish. Including asynchronous dependencies. You can even create disposal methods for your dependencies in case they are no longer in use.</p><p>You can also use 3rd party dependencies as part of your dependency tree. More on that later.</p><h3>Let’s get started</h3><p>Add these dependencies</p><pre>dependencies: <br> # add injectable to your dependencies <br> injectable: <br> # add get_it <br> get_it: <br> <br>dev_dependencies: <br> # add the generator to your dev_dependencies <br> injectable_generator: <br> # add build runner if not already added <br> build_runner:</pre><p>After that, you need a configuration file as a starting point.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fcb5610fe9b6fa6d9bb6fc4d2a2d556/href">https://medium.com/media/2fcb5610fe9b6fa6d9bb6fc4d2a2d556/href</a></iframe><p>The last import is the combination of your file name and .config.dart suffix.</p><p>You can also set environments like prod, dev, test, or custom. Imagine you have a backend with different environments. Each has its baseUrl. You can even create absract BaseUrl and implement it depending on the environment. See below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a366a821b76d076de79531108b150db4/href">https://medium.com/media/a366a821b76d076de79531108b150db4/href</a></iframe><p>Look how easy it is! You can use your current flavor as an environment. So, each time you switch environments, everything will work as it should without changing a single line of code.</p><p>Do you need a development environment? Done. Production? Done. In the blink of an eye.</p><h4>@Singleton and @LazySingleton</h4><p>Annotating a class Singleton makes it unique. So, every time you call the class you will get the same class. LazySingleton is similar but only instantiates the class when it is called.</p><h4>@Injectable</h4><p>It only marks the class as a dependency so injectable_generator access it. It is a factory. Everytime you call it, you will get a new instance of it.</p><h3>Again, why did we use injectable package?</h3><ul><li>You don’t need to write boilerplate code by yourself. Annotations are quite helpful.</li><li>It supports different environments.</li><li>It finds and injects proper dependencies by itself. No need getIt&lt;T&gt;() hell.</li></ul><h3>Conclusion</h3><p>Thank you for reading so far. Next, we will jump into more complex usage of injectable. Until that be well.</p><p>Don’t forget to follow me, give claps, and share the article if you find it helpful.</p><p>Thank you for reading.</p><p><a href="https://www.nahitfidanci.com/">Website</a></p><p><a href="https://www.youtube.com/@nahitfidanci">Youtube</a></p><p><a href="https://github.com/dokumanx">Github</a></p><p><a href="https://www.linkedin.com/in/nahit-fidanci/">LinkedIn</a></p><p><a href="https://twitter.com/FerdaNahit">Twitter</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adbb63a9044c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Become a Senior Developer?]]></title>
            <link>https://fnfidanci.medium.com/how-to-become-a-senior-developer-0bb7860549f3?source=rss-c17b8fc11bf6------2</link>
            <guid isPermaLink="false">https://medium.com/p/0bb7860549f3</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[seniors]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[careers]]></category>
            <dc:creator><![CDATA[Nahit FIDANCI]]></dc:creator>
            <pubDate>Sat, 25 Nov 2023 21:33:33 GMT</pubDate>
            <atom:updated>2023-11-25T21:39:27.659Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>One day in the morning, you will feel the sun shining brighter than before. The air will be warmer, and you will find yourself rising from your cozy bed, floating ever so slightly. At that moment, there will be no doubt that you have become a senior developer.</blockquote><p>Sounds crazy, doesn’t it? Well, this is mostly how you become a senior nowadays. Everyone gives themselves titles that they want. No authority, no certificate, no adequate experience to demonstrate proficiency. To be more specific, let me give you examples from my field.</p><p>There are a bunch of Flutter developers out there who claim they are senior developers with only 1 year of experience. I might accept it if they were previously an Android/iOS developer for 4–5 years and then switched to Flutter. Why? Because fundamentals don’t change. If you develop native apps, you are most likely to learn Flutter faster than newbies. Because you know fundamentals. You know ADLC, networking, architectural patterns, navigations, testing, animations (idea, adequate math, structure), etc. It doesn’t matter which language/framework you use if you have prior mobile development experience. Especially native development. You touch the core functionalities of the phone. You write platform-specific code which is much more efficient. And it’s much harder than Flutter/Dart. Dart is a declarative language (continuously gaining more functional programming magic), and Flutter has a similar structure to SwiftUI and Compose. Even a junior developer can quickly adapt to Flutter and develop basic apps.</p><p>It’s like speaking English and deciding to learn Spanish, which is easier to learn because you are familiar. The same thing goes with app development. That’s why I can accept prior native developers as senior Flutter developers with little experience. They don’t learn how to speak from scratch. They learn how to speak in Flutter.</p><p>But when someone who knows only Flutter claims themselves a senior with one year of experience and publishes a dummy to-do app with shoddy theming, I am going crazy. It’s not something you can claim. And it’s not something a startup can give to you just because you somehow manage the whole app without any architecture with spaghetti code.</p><p>There should be authority to give these titles. If there is, please let me know. And others who you think they need.</p><p>So, what is it all about being a senior, staff, manager, etc.? Is it necessary? Couldn’t you introduce yourself to others if you are not at a level that is found respectful? Well, there are most likely two reasons why you might want to have a title.</p><blockquote><strong>1- More money</strong></blockquote><blockquote><strong>2- More authority</strong></blockquote><p>That’s it. Other than that, if you are good at coding or managing people, good for you. There is no other benefit of having a title.</p><p>If your goal is one of these above or just being good at what you are doing, then I have some pieces of advice for you.</p><blockquote>Copy your senior co-workers.</blockquote><p>I mean real seniors. Copy their style of writing. Copy their habits. Copy how they structure the code. And be as lazy as possible like them. Because lazy developers don’t like to repeat themselves. And they don’t like to dig into code to change a small part of it. They even created architectural patterns for that reason. Once they go back to the forgotten part of the project, they want to do what needs to be done as quickly and easily as possible. Copy them to be a senior.</p><blockquote>Learn from your mistakes.</blockquote><p>There is no way to learn something in the blink of an eye. There will be ups and downs. Your work might not be perfect at once. But you will learn why you need to do it as your senior does. Once you do these, well, who knows, maybe you can find yourself floating on your bed.</p><h3>Conclusion</h3><p>If you enjoyed the reading, I would appreciate your applause. And you might want to share it with others to help me grow.</p><p>Thanks for reading.</p><p><a href="https://www.nahitfidanci.com/">Website</a></p><p><a href="https://www.youtube.com/@nahitfidanci">Youtube</a></p><p><a href="https://github.com/dokumanx">Github</a></p><p><a href="https://www.linkedin.com/in/nahit-fidanci/">LinkedIn</a></p><p><a href="https://twitter.com/FerdaNahit">Twitter</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0bb7860549f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crafting High-Quality Flutter Apps: A Journey into Clean Architecture]]></title>
            <link>https://fnfidanci.medium.com/crafting-high-quality-flutter-apps-a-journey-into-clean-architecture-455986e10127?source=rss-c17b8fc11bf6------2</link>
            <guid isPermaLink="false">https://medium.com/p/455986e10127</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[bloc]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <dc:creator><![CDATA[Nahit FIDANCI]]></dc:creator>
            <pubDate>Wed, 08 Nov 2023 23:40:34 GMT</pubDate>
            <atom:updated>2023-11-10T18:55:57.439Z</atom:updated>
            <content:encoded><![CDATA[<h3>Crafting High-Quality Flutter Apps: A Journey into Clean Architecture — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*4gNMvn3t3rtez-7V.jpeg" /></figure><p>Hey there, folks!</p><p>Ever had that feeling of drowning when your project just keeps growing? Like, you don’t even know where to look to find that specific part of your project to fetch some boring stuff from an API? Or maybe you just forget it even exists?</p><p>I feel your pain, and guess what? I’ve got the perfect remedy to make it… umm… less painful.</p><h3>Exaggerated term: Clean Architecture</h3><p>No doubt, organizing your projects is a great help. However, it doesn’t come with a magic wand to make everything perfect forever.</p><blockquote>It’s not something set in stone that cannot be bent, or altered. It can be even ignored in some parts. It’s neither a rule nor a must.</blockquote><p>I totally get where you’re coming from. I wanna make sure you understand this too. Clean architecture, MVVM, MVC, or anything else out there, they’re nothing more than organizers. It’s like when you prefer folding your laundry, so when you come back to use them next time, they’re all neatly organized and ready to go.</p><p>I know… You want me to show you how. Let’s keep it brief and take some action.</p><p>I believe most of you heard about Uncle Bob and his famous diagram.</p><figure><img alt="Clean Architecture by Robert C. Martin (Uncle Bob)" src="https://cdn-images-1.medium.com/max/772/0*uT4bONAWj644_gb-.jpg" /><figcaption>Clean Architecture by Robert C. Martin (Uncle Bob)</figcaption></figure><p>There is a bunch of stuff going here and you don’t need to use every piece of layer here but you need to understand why they are stated. I will explain them both in general and in a Flutter way. Some of them are mutual like <strong>Entities</strong> and <strong>Usecases</strong>. But I will give solid examples for Controller and UI.</p><h3>General explanation</h3><p><strong>Entities: </strong>Pure objects/models (whatever you call them) between Usecases and Repositories. You don’t see Repositories here but I will show and explain them later on. Entities are pure because they don’t include any ORM. It is the job of <a href="https://www.baeldung.com/java-dto-pattern">DTOs</a> (Data Transfer Objects).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wpZSUq6i0Ijqb-tD0DerYg.png" /></figure><p>Above, UserDTO is the first place to obtain raw data from APIs. It converts JSON, XML, or any other existing format into UserDTO, which is then mapped to <strong>User</strong> and <strong>Role</strong> Entities using a mapper. It’s worth noting that User has an additional parameter, password whereas Role does not require it. The mapper handles the differentiation between the two.</p><p><strong>Usecases: </strong>Easy way to reach an API. It includes repositories (local/remote). You most likely use dependency injection (<a href="https://en.wikipedia.org/wiki/Dependency_injection">DI</a>) if you decide to go in a clean way. So, this is the very first place where you inject your dependencies (repositories, other use cases, etc.). This layer is highly testable because it is isolated from any other layer. It doesn’t depend on higher-level layers. You can replicate(mock) its dependencies (lower or same layers — Repositories, other use cases). Therefore, it is highly testable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d44244928e9f33ee93154f94e8826370/href">https://medium.com/media/d44244928e9f33ee93154f94e8826370/href</a></iframe><p><strong>GetMusicUsecase</strong> depends on <strong>MusicRepository</strong>. I can give it anything that implements MusicRepository’s blueprint. Therefore, it can be easily mocked when it is tested.</p><p><strong>Interface Adapters: </strong>This is a bridge between your business logic (use cases) and UI (Mobile, Web, Desktop). Well, you might know about <a href="https://bit.ly/3X10ExM">Bloc</a>, Riverpod, or other state management solutions. They are the <strong>Presenters. </strong>They help you to keep the UI (Presentation) layer clean. By clean, I mean no business logic. AnimationController, ScrollController, ValueNotifier, and other UI-related logic are not counted. UI needs them to spin the wheels. So, don’t try to handle them in your Presenters. You can use <a href="https://pub.dev/packages/flutter_hooks">Hooks</a> though.</p><p>What about Controllers? Well, they are the first access points to the use cases. If you have an architecture that clean, you can call this Controller is an <strong><em>SDK</em></strong>. This is where you set all your environment, more particularly, which base url you want to use. You can toggle things here such as enabling logging. You got it.</p><p><strong>Presentation: </strong>This is where you use all your business logic with fancy designs, animations, and transitions. Of course, the help of your <strong>InterfaceAdapters</strong>. There could be numerous examples of doing so. Nonetheless, it is all the same. You ask for something from Presenters and it returns it from business logic. You surround your widget with BlocBuilder and wait for it to return your <em>music collection</em> from the backend. Maybe, you don’t have an internet connection and it’s alright. You don’t care about it. Because it is not UI’s responsibility to think of that. You handled it in your business logic. It returns you from the cache if there is no connection. And it updates once you reconnect. It updates the cache too.</p><p>I know you need to see how. Let’s check out this simple example below.</p><blockquote>I will use some notations from <a href="https://pub.dev/packages/injectable">injectable</a> package for DI. Don’t worry, I plan to write an article about how to use it too. And you might see some functional programming magic which is alright. I will have another article for it to dive into details. But I will still explain here.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7111d9b81aa29a897cb1cca59cf39d37/href">https://medium.com/media/7111d9b81aa29a897cb1cca59cf39d37/href</a></iframe><p>First, it checks the network connection. If it is connected, it ensures that there is cached data and that it is not expired (we don’t want to use data that’s 100 years old — in reality, it will most likely be a minute or so). It returns the cached data while mapping it to the <strong><em>entity</em></strong>.</p><p>If the cached data doesn’t exist or is expired, we use the remote repository to fetch the data. Afterwards, we cache it. And so on. Any error at this point is considered a <strong>ServerFailure</strong>.</p><p>If there is no network connection, it only attempts to return the cache. If it fails to do so, it is considered a <strong>CacheFailure</strong>.</p><h3>Do we really need this mess?</h3><p>Well, it will be a classic answer, but “it depends.”</p><p>Are you building an enterprise app? Do you have any coworkers? Does your app need to be tested? Are you planning to create a different app with the same business logic (SDK)? Is your app potentially scalable? Do you have enough time? Did your boss tell you that you need to do this by Monday? If the answer is yes to any of these questions, then yes, you need it.</p><p>Are you having fun with small projects? Don’t have much time? Not ready to explore the dark side just yet? Are you a junior developer? In that case, no, this might be overkill for you. However, it doesn’t mean that you can write <a href="https://en.wikipedia.org/wiki/Spaghetti_code">spaghetti code</a>. And it doesn’t mean that juniors should avoid using this architecture. But it cannot be denied that it can feel overwhelming for someone who has just started. You need to take it one step at a time, like taking baby steps.</p><h3>Conclusion</h3><p>In the next part, I’ll show you a lighter version of this clean architecture. It’s still clean, but not as complicated. Sneak peek: you can toss out the use cases and forget about needing an SDK. I’ll also guide you on how to structure your folders properly.</p><p>Thanks for reading and spending your time here! If you found it helpful, please give me a <strong>follow</strong>, some <strong>claps</strong>, and <strong>share</strong> it around to keep me motivated to share more!</p><p>Cheers.</p><p><a href="https://www.nahitfidanci.com/">Website</a></p><p><a href="https://www.youtube.com/@nahitfidanci">Youtube</a></p><p><a href="https://github.com/dokumanx">Github</a></p><p><a href="https://www.linkedin.com/in/nahit-fidanci/">LinkedIn</a></p><p><a href="https://twitter.com/FerdaNahit">Twitter</a></p><h4>References</h4><p><a href="https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html">Clean Coder Blog</a></p><p><a href="https://www.baeldung.com/java-dto-pattern">https://www.baeldung.com/java-dto-pattern</a></p><p><a href="https://en.wikipedia.org/wiki/Dependency_injection">https://en.wikipedia.org/wiki/Dependency_injection</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=455986e10127" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to secure API keys in Flutter]]></title>
            <link>https://fnfidanci.medium.com/how-to-secure-api-keys-in-flutter-41cfb31ae52a?source=rss-c17b8fc11bf6------2</link>
            <guid isPermaLink="false">https://medium.com/p/41cfb31ae52a</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[keys]]></category>
            <dc:creator><![CDATA[Nahit FIDANCI]]></dc:creator>
            <pubDate>Wed, 01 Nov 2023 21:28:33 GMT</pubDate>
            <atom:updated>2023-11-02T06:32:02.061Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d_5dJ-5ZhYMnux8PVBJ-GQ.png" /><figcaption>Secure API key with envied</figcaption></figure><p>Hello everyone, it’s been a while since I wrote my last article. I felt like it ‘s time to write something new and useful. So, here we are. You can check out my previous articles below.</p><ul><li><a href="https://fnfidanci.medium.com/flutter-dart-bloc-pattern-with-freezed-part-1-83b9bc6f9333">[Flutter/Dart] Bloc Pattern with Freezed Part-1</a></li><li><a href="https://fnfidanci.medium.com/flutter-dart-bloc-pattern-with-freezed-part-2-testing-253e145a6ab1">[Flutter/Dart] Bloc Pattern with Freezed Part-2 Testing</a></li></ul><p>Some of you might not be aware of that but almost anything bundled in your app’s build can be demystified. It includes your commented test account credentials, funny todos, a grocery list that you committed by mistake, and your API keys. Yes, some of you still store groceries in your projects.</p><h4>What would be a better move?</h4><p>We can use .env files to store our secrets. And then we can access them easily. Check out <a href="https://pub.dev/packages/flutter_dotenv">flutter_dotenv</a> for more. This approach is better but it is much easier to demystify secrets. Why? Because we have to add .env files to pubspec.yaml as assets to access them in dart files. Why is it a bad thing? Because assets can be reached easily without any decryption or other fancy reverse-engineering magics.</p><p>You can simply use Android Studio’s APK analyzer to see each resource even if — obfuscate flag is used, assets can still be accessible easily. So, your secrets are not safe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*GFEiw_1GeuwWF5nloPSIKA.png" /><figcaption>Flutter Assets</figcaption></figure><h4>What would be a smarter move?</h4><p>Well, have you ever heard about environment variables? Yes, I am talking about them. You can pass critical information such as your anniversary through environment variables. Add — dart-define into your toolArgs of you launch.json file in VS Code. And then access them with String.fromEnvironment(&#39;NAME&#39;);</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7af9b55f865b06f094e7eb906485dbb9/href">https://medium.com/media/7af9b55f865b06f094e7eb906485dbb9/href</a></iframe><pre>print(const String.fromEnvironment(&#39;ANNIVERSARY&#39;));</pre><p>You can do the same in Android Studio too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*yCvPUq4OmZOCf9rem2Gzdw.png" /></figure><p>So, did we solve the problem? Not so fast. This is a good starting point and it will help you to secure your secrets. But it is not a best practice since you give everything through your run configurations. Of course, there are workarounds like passing all the data through a file with — dart-define-from-file . And you can add it .gitignore and you are good to go. But hear me out. There is a better way.</p><h3>Meet our rockstar: Envied</h3><p><a href="https://pub.dev/packages/envied">Envied</a> is the best option so far for <strong>ME</strong>.</p><h4>Why?</h4><p>It is safe because we don’t add .env files as assets. It is safe because it generates dart files which include your credentials in base64 format which makes it harder to decompile and find the secrets. Of course, you need to use obfuscate=true to enable obfuscation.</p><p>It is officially supported to use different flavors but I will show you how to do it in the right way.</p><p>Let’s create a blueprint for both flavors.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20ab7fe01df23fd94c3e92f504724a53/href">https://medium.com/media/20ab7fe01df23fd94c3e92f504724a53/href</a></iframe><p>Remembered String.fromEnvironment ? We give ENV key to define which flavor we want to use. And AppSecret will return that flavor’s secrets.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50013f1ab28d16b5974bac0539c6afac/href">https://medium.com/media/50013f1ab28d16b5974bac0539c6afac/href</a></iframe><p>Let’s see inside of ProductionSecret . First, we need to add part to generate secrets from the environment file. We need to use @Envied annotation with the path of the environment and obfuscate=true .</p><p>We implement AppSecret and AppEnvFields, therefore, we agree with what keys should be overriding and AppSecret has exact same secret. So, we can use them without breaking anything in different flavors.</p><p>Due to obfuscate=true each key should be final . And each should have @EnviedField with the secret’s key name in the environment file. Which is SECRET_KEY in our case.</p><p>Then we say _ProductionSecret.secretKey which will come from the generated file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/edf7ef92128927252e1cc06927ae44b6/href">https://medium.com/media/edf7ef92128927252e1cc06927ae44b6/href</a></iframe><p>Lastly, we need to run one of the below commands.</p><pre># dart<br>dart run build_runner build<br># flutter<br>flutter pub run build_runner build</pre><p>Do not forget to add .env, production_secret.dart and production_secret.g.dart into .gitignore . You don’t want to store these in your repository.</p><h3>How to use secrets in CI/CD flows?</h3><p>If you use a CI/CD tool such as Github Actions or CodeMagic, you need to store your keys in these platforms and dynamically generate envied files in the workflow. You can check out the below link to see how to do it in CodeMagic.</p><p><a href="https://docs.codemagic.io/yaml-basic-configuration/configuring-environment-variables/">Adding environment variables in codemagic.yaml</a></p><h3>Conclusion</h3><p>Well, that’s pretty much it. I hope you learned something useful today. Still, I do not recommend you to store the nuclear codes with envied just in case.</p><p>Don’t forget to follow me, give claps, and share the article if you found it helpful.</p><p>Thank you for reading.</p><p><a href="https://www.nahitfidanci.com/">Website</a></p><p><a href="https://www.youtube.com/@nahitfidanci">Youtube</a></p><p><a href="https://github.com/dokumanx">Github</a></p><p><a href="https://www.linkedin.com/in/nahit-fidanci/">LinkedIn</a></p><p><a href="https://twitter.com/FerdaNahit">Twitter</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41cfb31ae52a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Flutter/Dart] Bloc Pattern with Freezed Part-2 Testing]]></title>
            <link>https://fnfidanci.medium.com/flutter-dart-bloc-pattern-with-freezed-part-2-testing-253e145a6ab1?source=rss-c17b8fc11bf6------2</link>
            <guid isPermaLink="false">https://medium.com/p/253e145a6ab1</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[bloc]]></category>
            <category><![CDATA[mobile-development]]></category>
            <dc:creator><![CDATA[Nahit FIDANCI]]></dc:creator>
            <pubDate>Thu, 09 Feb 2023 00:38:34 GMT</pubDate>
            <atom:updated>2023-02-09T01:43:27.776Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Testin bloc with mockito" src="https://cdn-images-1.medium.com/max/1024/1*H4VM9CaYigR9FR2T9oDHag.jpeg" /><figcaption>Bloc Test with Mockito</figcaption></figure><p>Hello! I hope you’re doing well. Today, we will test our previously created MusicPlayerBloc to ensure it functions as intended.</p><p><a href="https://fnfidanci.medium.com/flutter-dart-bloc-pattern-with-freezed-part-1-83b9bc6f9333">[Flutter/Dart] Bloc Pattern with Freezed Part-1</a></p><p>Testing your code is always a good practice, as it allows you to write modular and functional code, and understand the logic better. As you develop the bloc, it’s essential to think about all the possible test cases. This will help you check that all cases still apply every time you make changes to the code. The purpose of writing tests is to automate the process and ensure that the functionality remains the same every time you add or change something in the code. By writing possible scenarios and use cases, you can be confident that the code is working as expected.</p><h3>Introduction</h3><p>There are several types of tests, including unit testing, widget testing, integration testing, golden testing, and user acceptance testing.</p><figure><img alt="Testing types in flutter apps" src="https://cdn-images-1.medium.com/max/800/1*IX50nFvws9G88Hdo4flRLA.png" /><figcaption>Types of Testing</figcaption></figure><p><strong>Unit tests </strong>help us verify the smallest pieces of code, known as units, such as a function for image-to-byte conversion, a network call, JSON parsing, or in our case, a bloc.</p><p><strong>Widget tests </strong>ensure that widgets in Flutter display the correct information. They often include the units tested in unit tests. For example, in a counter app, you can verify that after tapping the “increase” button, the widget displaying the current count will show the increased value. Or in a list of items displayed using a FutureBuilder, you can verify that the items are properly retrieved and displayed from a network call.</p><p><strong>Integration tests </strong>involve simulating user interactions and feature flow in the app to verify that all functionalities work together and display the correct information on the screen. For example, a login test can be an integration test where you programmatically input an email and password, and verify if the login is successful or not.</p><p>Unit, widget, and integration tests can be compared to atoms, molecules, and organisms. First, you have unit tests, then use the units to test widgets, and finally write integration tests to see everything in action.</p><figure><img alt="An illustration that show how tests combine together" src="https://cdn-images-1.medium.com/max/454/1*o-4oOUjbZrMdWEHPqcvZxQ.png" /><figcaption>Atoms-&gt;Molecules-&gt;Organisms</figcaption></figure><p><strong>Golden tests</strong> are a form of automated testing that compare the current state of screens with pre-approved images to verify that everything is functioning as expected with each change in the code. If the output differs from the golden image, the test will fail, and the developer will be notified of the difference.</p><p><strong>User acceptance</strong> <strong>testing</strong> involves real users testing the functionality and user experience. This test is crucial as it provides real-life feedback on how users will interact with the app. Even with multiple tests, it is impossible to simulate all real-life scenarios, so user acceptance testing is essential to ensure the app is functioning as expected.</p><p>A use case for user acceptance testing (UAT) could be testing the functionality and user experience of a new e-commerce platform. During UAT, a group of real end-users would be invited to navigate the platform, purchase items, and provide feedback on the overall experience. The goal of UAT is to identify any issues with the platform that real users may encounter, such as difficulty in navigating the site, issues with the checkout process, or problems with the mobile app. This feedback can then be used to make improvements to the platform before its official launch.</p><h3>Testing MusicPlayerBloc</h3><p>To ensure that our code functions as expected, we first create mocks of the TrackTime and PlaylistRepository functionalities. We use the <strong>mockito</strong> library to create these mocks and give them optional names using the <strong>as</strong> keyword. Then, we import the not-yet-generated file <strong>music_player_bloc_test.mocks.dart</strong>. Finally, we run the following command to generate the mocks.</p><pre>flutter pub run build_runner build --delete-conflicting-outputs</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a33c8b62fb6231288fc3fa2dc4ed0bc5/href">https://medium.com/media/a33c8b62fb6231288fc3fa2dc4ed0bc5/href</a></iframe><p>To set up the bloc, we use <strong>MockTrackTimer</strong> and <strong>MockPlaylistRepository</strong>. The mock repository allows us to simulate the behavior of different functions and return any desired output. In our scenario, we return the constant Playlist data <strong>blues90s</strong>. Additionally, we establish a base state for the bloc. This setup provides a controlled environment for testing the bloc’s behavior and ensuring that it functions as intended.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eea76339f329f9fcdb69d091cf4b473c/href">https://medium.com/media/eea76339f329f9fcdb69d091cf4b473c/href</a></iframe><p>Our first test will be about playing the first track. First, we give the bloc we’re working on by passing it to <strong>build</strong>. Then we set up the <strong>trackTimer</strong>. Regardless of the input <strong>trackDuration</strong>, <strong>passedTime()</strong> will always return 0 Duration. The act section will include events. We only added a play event. We can skip states. If there are many state changes after an event is dispatched, you might focus on the latest two by skipping others. By skipping one, we skip the initial status of the state. And after the event occurs, we expect the first loading status, then the playing status.</p><p>I’m not calling playing and loading states because they’re actually in the same state, but they’re different statuses.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5248acba860369dc9aaa8995478d97dc/href">https://medium.com/media/5248acba860369dc9aaa8995478d97dc/href</a></iframe><p>In this test, we set up the <strong>passedTime</strong> to return 0 Duration and seed a state. This is done because a starting point is needed to simulate a scenario. In this case, the starting point is the seed state with the current status as playing. By only updating the status, the current track being played is the first track of <strong>blues90</strong>. The next event is then dispatched, which simulates a network call. We also wait for 200ms. If the bloc is working properly, we should first see the loading status, followed by the next track’s index and the playing status.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/673a1faf0021783c36e206964982b25d/href">https://medium.com/media/673a1faf0021783c36e206964982b25d/href</a></iframe><p>In this test, we set the starting state of the bloc to playing and the <strong>currentTrackIndex</strong> as the last item of the track list. We then dispatch the <strong>next</strong> event. Since we are already on the last track, the event should stop at the last track and not move on to the next one. The bloc should correctly reflect this state change.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e45f7eadae9e6d686ccc5c2a3ac9cbd/href">https://medium.com/media/3e45f7eadae9e6d686ccc5c2a3ac9cbd/href</a></iframe><p>In this test scenario, we start with a playing status, with the current track being the 6th one and the current time being 10 seconds. Then, the <strong>previous</strong> event is dispatched, and we wait for 200ms. The expected outcome is that the next status should be loading along with the current time and current track index. After the loading, the bloc should start playing the previous track, which means the next status should be playing, but with the current track index being 4 and the current time being 0.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/917e819710827e2a0921e63e87d779cc/href">https://medium.com/media/917e819710827e2a0921e63e87d779cc/href</a></iframe><p>You can check out all tests below. The same logic applies to other tests.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e45622e3036161c8881c04221bc792c2/href">https://medium.com/media/e45622e3036161c8881c04221bc792c2/href</a></iframe><figure><img alt="Bloc test group results" src="https://cdn-images-1.medium.com/max/533/1*rKRp4XJxEwCdUTVjJ8Ne3w.png" /><figcaption>Test results</figcaption></figure><h3>Conclusion</h3><p>Thank you for reading up to this point. I hope you learned something new today. In part 3, we will finally create UI and integrate it with the bloc.</p><h3>Source code</h3><p><a href="https://github.com/dokumanx/music_player_bloc">GitHub - dokumanx/music_player_bloc</a></p><p>Don’t forget to give claps and share if you found the article helpful. You can also check out my website and follow me on my socials.</p><p><a href="https://www.nahitfidanci.com/">Website</a></p><p><a href="https://www.youtube.com/@nahitfidanci">Youtube</a></p><p><a href="https://github.com/dokumanx">Github</a></p><p><a href="https://www.linkedin.com/in/nahit-fidanci/">LinkedIn</a></p><p><a href="https://twitter.com/FerdaNahit">Twitter</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=253e145a6ab1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Flutter/Dart] Bloc Pattern with Freezed Part-1]]></title>
            <link>https://fnfidanci.medium.com/flutter-dart-bloc-pattern-with-freezed-part-1-83b9bc6f9333?source=rss-c17b8fc11bf6------2</link>
            <guid isPermaLink="false">https://medium.com/p/83b9bc6f9333</guid>
            <category><![CDATA[bloc]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[freezed]]></category>
            <category><![CDATA[mobile-development]]></category>
            <dc:creator><![CDATA[Nahit FIDANCI]]></dc:creator>
            <pubDate>Fri, 03 Feb 2023 14:01:06 GMT</pubDate>
            <atom:updated>2023-02-13T23:18:57.368Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Flutter Bloc and Freezed packages example for a music player app in Flutter" src="https://cdn-images-1.medium.com/max/1024/1*M5uGxwXObQxNje3JQvs0DQ.png" /><figcaption>Flutter Bloc and Freezed</figcaption></figure><p>Hello everyone, I hope you are doing well. It’s been a while since I wrote about <a href="https://bit.ly/social-connection-auth0-part1">authentication with Auth0 via social connections</a>, and I thought writing a new article would be refreshing. Today, I will demonstrate how to effectively use the Bloc pattern with the freezed package. I will aim to create a real-life scenario that incorporates all of the best practices that I have outlined. Let’s begin.</p><h3>What is Bloc Pattern?</h3><p>The Bloc pattern is a powerful tool for managing the business logic of your app in a clean and organized way. Separating the logic from the presentation allows for easier testing, maintenance, and scalability. The pattern utilizes unidirectional data flow, where events are sent to trigger business logic, and the resulting state is used to update the UI. The Bloc Pattern is often used in conjunction with the provider pattern in Flutter, it can help keep your codebase clean and easy to understand.</p><figure><img alt="Diagram shows 3 layers of a Flutter app using the Bloc pattern: UI dispatches events, Bloc requests data, and updates UI state." src="https://cdn-images-1.medium.com/max/776/0*ChnzWMsfLEnKD-cj" /><figcaption>Representation of flow of Bloc Pattern</figcaption></figure><h3>Why Bloc Pattern?</h3><p>It is one of the many state management solutions out there. It depends on your use case to go with the Bloc pattern. If your project is high scale and you need to keep things organized, you can give it a shot. But it would be overkill to handle simple state changes. Even if some of the community members think that it requires a lot of boilerplates, I still think that this is because of its nature. Everything is clear. You can track the flow easily. You can create custom events and states depending on your needs and update the UI as you like so. Of course, all these can be achieved with other solutions like Riverpod. You can create a StateNotifierProvider and it could do the same with help of some magic. Personally, I like Riverpod too. But this is a topic of another story. Anyway, I realized that even though I use Riverpod, I try to make things similar the way I do with the Bloc pattern. I really like the declarative way of managing the state. I like to dispatch a new event and leave the rest to the bloc. It works like a black box. I can debounce, filter events, and mutate states. I can control the way of failure through states. No surprises here.</p><h3>Let’s create an example</h3><p>Well, I will not create a to-do list, as it has been done many times before. Instead, I will create a music player controller using the Bloc pattern. Of course, it’s not our focus here to implement the actual music player feature, it will be a conceptual implementation to demonstrate the usage of the Bloc pattern. But I will simulate some basic features such as playing, pausing, and skipping songs back and forward.</p><p>Firstly, let’s include our necessary dependencies.</p><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>  flutter_bloc: ^8.1.1<br>  bloc_test: ^9.1.0 # To test bloc&#39;s funtionality<br>  freezed: ^2.3.2<br>  freezed_annotation: ^2.2.0<br>  # This is not required.<br>  # It is used to easily simulate track&#39;s current time.<br>  stop_watch_timer: ^2.0.0 <br>  mockito: ^5.3.2 # To mock our repository<br><br>dev_dependencies:<br>  flutter_test:<br>    sdk: flutter<br>  flutter_lints: ^2.0.1<br>  build_runner: ^2.3.3 # Generate files for mockito and freezed</pre><p>We will divide the example into 3 parts. The first part (this one) will be about creating the MusicPlayerBloc. In the second part, we will write tests to see whether the bloc works as expected. In the last part, we will create a UI and connect it with our bloc.</p><p>Let’s start with creating bloc states.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e7235146dc7dbab900527587a7210c1/href">https://medium.com/media/6e7235146dc7dbab900527587a7210c1/href</a></iframe><p>To maintain data integrity during state transitions, we introduced the <strong>PlayerStatus</strong> enum. The <strong>MusicPlayerState</strong> now encompasses all relevant information across states. When updating the state, we utilize <strong>copyWith()</strong> to only modify the status, thus preserving the existing data while updating the state.</p><p><strong>Initial</strong>: This will be the starting point and nothing more.</p><p><strong>Loading: </strong>This will be used prior to asynchronous events, even though we won’t have any actual events, we will still simulate them.</p><p><strong>Playing:</strong> This will be used when a track is being played.</p><p><strong>Paused:</strong> This will be used when a track is paused.</p><p><strong>Stopped: </strong>This will be used when the playlist reaches the end of the last track.</p><p><strong>Error:</strong> This will be utilized to display a snack bar or perform any other actions in the event of an error.</p><p>Thanks to the use of <strong>freezed</strong>, we don’t need to create an abstract class as a base state and derive each state from it. Instead, we create a named factory constructor with parameters if needed and <strong>freezed</strong> takes care of the rest. This is not the only feature offered by <strong>freezed</strong>; it defines immutable classes, handles equalities, pattern matching, <strong>copyWith</strong>, and more. You can check out its <a href="https://pub.dev/packages/freezed">official documentation</a> for further information.</p><p>Next, let’s create events.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c6068f54ac22a9471a32318d9abde64/href">https://medium.com/media/3c6068f54ac22a9471a32318d9abde64/href</a></iframe><p><strong>PlayMusicPlayer</strong>: This will start playing the track and emit the <strong>Playing</strong> state.</p><p><strong>PauseMusicPlayer</strong>: This will pause the track and emit the <strong>Paused</strong> state.</p><p><strong>ResumeMusicPlayer</strong>: This will resume the track and emit the <strong>Playing</strong> state.</p><p><strong>NextMusicPlayer</strong>: If there is a next track, it will play it and emit the <strong>Playing</strong> state. Otherwise, it will emit the <strong>Stopped</strong> state.</p><p><strong>PreviousMusicPlayer</strong>: If there is a previous track, it will play it and emit the <strong>Playing</strong> state. If not, it will play the first track and emit the <strong>Playing</strong> state.</p><p>So far, we have an understanding of the flow of the music player bloc. We have defined some events, and each event emits corresponding states based on the use case. Next, let’s see how we can integrate them into the bloc.</p><p>Before that, let me introduce you to our <strong>PlaylistRepository</strong>. To be honest, we don’t actually need it in this case as we have everything stored locally. However, I wanted to demonstrate how a repository should be used in such scenarios. Our repository in this case is a local one. I created an abstract class here to make it testable. This way, I can simply mock the abstract repository and use it as needed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bde40a775b41e016f5fed859059f4aca/href">https://medium.com/media/bde40a775b41e016f5fed859059f4aca/href</a></iframe><p>Let’s take a look at our models, <strong>Track</strong> and <strong>Playlist</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e4bf2bd65fe0dc0146675cb9fb0895f/href">https://medium.com/media/3e4bf2bd65fe0dc0146675cb9fb0895f/href</a></iframe><p>One more thing, we need to create a time tracker to monitor the progress of the song. As I mentioned earlier, I utilized an external package called the <strong>stop_watch_timer</strong> to make the task easier. Let’s examine it in detail.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af0ff1ba4d246a3c9f62734f6ceb5521/href">https://medium.com/media/af0ff1ba4d246a3c9f62734f6ceb5521/href</a></iframe><p>Up to this point, we’ve reviewed the flow of the music player bloc, combined events and states, and introduced the <strong>PlaylistRepository</strong> and <strong>Track/Playlist</strong> models. Additionally, we also introduced the time tracker using a stopwatch package. The package has various functions, including <strong>dispose(), </strong><strong>pause(), </strong><strong>resume(), </strong>and<strong> </strong><strong>stop()</strong>. The <strong>setTrackDuration()</strong> function sets a new preset time, and the <strong>passedTime()</strong> function calculates the passed time since the countdown started. The <strong>passedTimeStream()</strong> function does the same but returns a stream that only streams new, distinct seconds to prevent duplicated data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36efd8cb27e619fb8e6e6f85352ac545/href">https://medium.com/media/36efd8cb27e619fb8e6e6f85352ac545/href</a></iframe><p>It might look overwhelming all at once, but don’t worry, we will go over everything step by step. Thanks to the <strong>freezed</strong> package, we can handle event handlers more easily. You can see how it works on line 25.</p><blockquote>Remember, we update the state by changing the status and updating the related data if needed. If the data stays the same, the state can still be updated without touching the data, keeping it persistent unless we make changes on purpose.</blockquote><p>The <strong>_play()</strong> function takes an <strong>index</strong> parameter. In this function, we use the <strong>index</strong> to get the current track in the playlist. We then set the preset time to the track&#39;s duration and finally, emit the <strong>Playing</strong> state with the relevant data.</p><p>The <strong>_pause()</strong> function makes use of the <strong>currentTrackIndex</strong> getter (as seen on line 103) to obtain the current track. It pauses the timer and returns to the <strong>Paused</strong> state. We only carry the <strong>currentTrackIndex</strong> in the <strong>Playing</strong> and <strong>Paused</strong> states. This is because every time we emit the <strong>Playing</strong> or <strong>Paused</strong> states, we can be sure to get the proper index from the <strong>currentTrackIndex</strong> getter. If the state is <strong>Stopped</strong>, we get the last index of the playlist. If it&#39;s anything else, such as the initial state or an error, we get the default index of 0.</p><p><strong>_resume()</strong>: Resumes the timer and transitions the state back to <strong>Playing</strong>.</p><blockquote>Did you understand what’s going on here? We don’t have a state named <strong>Resumed</strong>. Instead, we transition back to the <strong>Playing</strong> state. This is because, logically, if we resume something that was previously paused, it will start playing again. Having redundant states would only make the logic more complex. It&#39;s important to prioritize clarity and simplicity.</blockquote><p><strong>_stop()</strong>: This is not an event actually. You thought that I missed adding this one to the <strong>MusicPlayerEvents</strong>, right? Well, not really. Because we will never use it explicitly outside of the bloc. So, having it as an event has no benefit other than using it in the <strong>NextMusicPlayer</strong> event.</p><p><strong>_next()</strong>: First, it makes sure that the playlist is not stopped. If it is, we cannot go further and simply ignore the event. Otherwise, it checks whether the track is the latest. If it is, it will execute <strong>_stop()</strong>. If it isn&#39;t, first we emit a <strong>Loading</strong> state, which can be used to show a loading indicator or anything else in the UI. After that, we simulate an asynchronous action to see the <strong>Loading</strong> state a bit more on the screen. Then, we add the play event. Yes, we can add new events inside of the bloc too.</p><blockquote>Why didn’t we directly call <strong>_play()</strong>? Well, we can. But it leads to losing some functionalities. Even if we didn&#39;t use it here, we can actually transform events through <strong>EventTransformer</strong>. I will not give details about it, but long story short, directly calling the <strong>_play()</strong> might cause losing desired behaviors of the event. The safe way to do this is always adding a new event. You can check out <a href="https://pub.dev/packages/bloc_concurrency"><strong>bloc_concurrency</strong></a> to learn more about <strong>EventTransformers</strong>.</blockquote><p><strong>_previous()</strong>: It has the similar functionality with <strong>_next()</strong> but in the opposite direction. And if we are at the first track, it will restart the track. Check out <strong>setTrackDuration()</strong>. It stops and starts the timer with the duration of the track. In our case, it will be the same track.</p><p>Alright, I think we learned how to create a bloc that best suits our use case. We should first decide on events and states, focusing on simplicity. We shouldn’t be overly generous in creating events and states; less is better. However, don’t force the logic too much just to reduce the number. Sometimes, it is what it is. Try to rely on abstraction as much as possible and avoid strict dependencies (<a href="https://en.wikipedia.org/wiki/Loose_coupling">Loose Coupling</a>). This is not exactly <a href="https://en.wikipedia.org/wiki/Dependency_injection">dependency injection</a>, but pay attention to how I get the <strong>TrackTimer</strong> and <strong>IPlaylistRepository</strong> outside of the bloc. This allows me to provide anything I want, including mocks, and keeps the bloc testable. Additionally, I relied on abstraction instead of a concrete implementation of <strong>IPlaylistRepository</strong>, providing me with the flexibility to use any implementer (<a href="https://en.wikipedia.org/wiki/Dependency_inversion_principle">Dependency Inversion</a>).</p><h3>Next</h3><p><a href="https://bit.ly/3xdrUOU">Testing Bloc with Mockito [Part 2]</a></p><h3>Conclusion</h3><p>Thank you for reading up to this point. I hope you learned something new today. In part 2, we will focus on testing the bloc.</p><h4>Source code</h4><p><a href="https://github.com/dokumanx/music_player_bloc">GitHub - dokumanx/music_player_bloc</a></p><p>Don’t forget to give claps and share if you found the article helpful. You can also check out my website and follow me on my socials.</p><p><a href="https://www.nahitfidanci.com/">Website</a></p><p><a href="https://www.youtube.com/@nahitfidanci">Youtube</a></p><p><a href="https://github.com/dokumanx">Github</a></p><p><a href="https://www.linkedin.com/in/nahit-fidanci/">LinkedIn</a></p><p><a href="https://twitter.com/FerdaNahit">Twitter</a></p><h4>References</h4><ul><li><a href="https://pub.dev/packages/freezed">freezed | Dart package</a></li><li><a href="https://pub.dev/packages/bloc_concurrency">bloc_concurrency | Dart package</a></li><li><a href="https://en.wikipedia.org/wiki/Loose_coupling">Loose coupling - Wikipedia</a></li><li><a href="https://en.wikipedia.org/wiki/Dependency_injection">Dependency injection - Wikipedia</a></li><li><a href="https://en.wikipedia.org/wiki/Dependency_inversion_principle">Dependency inversion principle - Wikipedia</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83b9bc6f9333" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrate Google and Apple sign-in to your Flutter app through Auth0 — Part-2]]></title>
            <link>https://fnfidanci.medium.com/integrate-google-and-apple-sign-in-to-your-flutter-app-through-auth0-part-2-2b5637084028?source=rss-c17b8fc11bf6------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b5637084028</guid>
            <category><![CDATA[auth0]]></category>
            <category><![CDATA[social-connection]]></category>
            <category><![CDATA[google-sign-in]]></category>
            <category><![CDATA[apple-sign-in]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Nahit FIDANCI]]></dc:creator>
            <pubDate>Wed, 11 Jan 2023 12:01:48 GMT</pubDate>
            <atom:updated>2023-01-11T13:58:50.007Z</atom:updated>
            <content:encoded><![CDATA[<h3>Integrate Google and Apple sign-in to your Flutter app through Auth0 — Part-2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UfH_gGmlvmuQ4-5a31_tfA.png" /></figure><p>It’s been a while since my <a href="https://bit.ly/3hREQGm">last article</a> on setting up social connections, and now I’m going to show you how to do it for production. As a reminder, we’ve been using Auth0development keys, but now it’s time to move on to the real deal. Let’s get started!</p><h3>Google set up</h3><p>First, let’s take a look at setting up Google. To do this, we’ll be following the official installation guide for <a href="https://marketplace.auth0.com/integrations/google-social-connection">Google/Gmail</a> connection.</p><p>To begin, go to the <a href="https://console.cloud.google.com/">Google Cloud Console</a> and create a new project. This is simple to do and can be done by following the instructions on the Google Developers website.</p><p><a href="https://developers.google.com/workspace/guides/create-project?hl=en">Create a Google Cloud project | Google Workspace | Google Developers</a></p><p>Once your project is created, it’s time to set up your <strong>OAuth consent screen</strong>. This screen is shown to users when they authenticate through Google sign-in.</p><p>To do this, choose <strong>External</strong> and hit the <strong>CREATE</strong> button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*iwjNDDSqnFemjy99fyUAkw.png" /></figure><p>Fill in the required fields, but make sure to add <strong>auth0.com</strong> as an authorized domain. If you’re planning to publish your app to production, you’ll also want to fill in the <strong>App Domain</strong> section. Be sure to add any domains you used in the <strong>App Domain</strong> section as <strong>Authorized Domains</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*N8juWI1s0b1zpuiotI9HHQ.png" /></figure><p>You can skip the <strong>Scopes, Test users, </strong>and<strong> Summary</strong> sections. After completing these steps, you’ll be taken to the dashboard where the status of the <strong>OAuth consent screen</strong> will be set to Testing. If you haven’t provided any optional information such as uploading a logo or requesting sensitive or restricted scopes, you can immediately publish it globally. However, before you do that, it&#39;s important to <a href="https://support.google.com/googleapi/answer/6158849">create credentials</a> that you can use with Auth0 later.</p><p>To create credentials, go to the Credentials section in the sidebar. Select <strong>Create Credentials</strong> and choose <strong>OAuth client ID</strong>. Choose <strong>Web application</strong> as the <strong>Application type</strong> and fill in the fields as prompted in the <a href="https://marketplace.auth0.com/integrations/google-social-connection">instruction</a>.</p><p>It should be in the below format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*F7uPqZGlrdFX9gaf-soSbQ.png" /></figure><p>For me, it will look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*XF5l45ErkLc8cgJiFbF2oA.png" /></figure><p>After hitting the <strong>CREATE</strong> button, you will be shown your <strong>Client ID</strong> and <strong>Client Secret</strong>. Be sure to store these credentials in a safe place, as you’ll need them later when configuring Auth0. You can also download the credentials as a JSON file for safekeeping.</p><blockquote>Before moving on, don’t forget to publish your OAuth consent screen. This will make it visible to users when they authenticate through Google sign-in.</blockquote><p>Let’s add them to auth0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*_XNLCmxzwvsr3QfTsoKFUw.png" /></figure><p>After you’ve saved the changes in Auth0 and added the Google credentials, any warning related to the google-oauth2 should be resolved. Now, you can proceed to configuring the Apple setup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/246/1*HvMQYZy8jzp0Ed36cwvEcA.png" /></figure><h3>Apple set up</h3><p>Apple’s side can be tricky, I’ll explain it best I can. Let’s follow <a href="https://marketplace.auth0.com/integrations/apple-social-connection">official instructions</a>.</p><h4><strong>1- Create App IDs identifier:</strong></h4><blockquote>If you already have an identifier, proceed to step 6:</blockquote><ol><li>Go to <a href="https://developer.apple.com/account/resources/authkeys/list"><strong><em>Certificates, Identifiers &amp; Profiles</em></strong></a></li><li>Choose <strong>Identifiers</strong> from the sidebar</li><li>Hit the blue icon to make a new one</li><li>Select <strong>App IDs</strong> and choose App</li><li>Add a Description and your app’s Bundle ID</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*BRInp4YlN4JM6Kw7JlSs3Q.png" /></figure><p>6. Scroll down and pick Sign In with Apple</p><p>7. Save and register</p><h4>2- Create Services IDs identifier:</h4><ol><li>Go back to identifiers</li><li>Click the blue button to create a new identifier</li><li>Choose <strong>Services IDs</strong></li><li>Give it a description and a unique identifier</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*huQqwcFOFa6hpu0RwH4FgQ.png" /></figure><p>5. Continue and register</p><h4>3- Configure Services IDs for Sign In with Apple:</h4><ol><li>Go back to your newly created <strong>Services ID </strong>and hit the <strong>Configure</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*RW-bH6jYNdA8sn_bPiNGbw.png" /></figure><p>2. Hit the blue button to add a domain and return URL</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*mUmftWGTKp9mSuocIboN1g.png" /></figure><p>3. Provide your Auth0 domain and return URL. They should be in this format:</p><pre>For domain: &lt;YOUR_AUTH0_DOMAIN&gt;<br>For redirect URL: https://&lt;YOUR_AUTH0_DOMAIN&gt;/login/callback</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*1VkOduRyAk5zMQrbB-AlNA.png" /></figure><p>4. Next, Continue, and Save.</p><h4>4- Create a Signing Key</h4><ol><li>Go back to the <a href="https://developer.apple.com/account/resources/authkeys/list"><strong><em>Certificates, Identifiers &amp; Profiles</em></strong></a><strong><em>.</em></strong></li><li>Choose <strong>Keys</strong> from the sidebar</li><li>Hit the blue button to make a new one</li><li>Name it</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4FxRslTg77tMYzODSkCX1A.png" /></figure><p>5. Select<strong> Sign in with Apple</strong>, configure it with your App ID</p><p>6. Save, register, and download the key.</p><h3>Auth0 Set up</h3><ol><li>Go to the apple social connection settings.</li><li>Use the identifier(<strong>Service ID) </strong>from step 2 for the Client ID (e.g. “<strong>com.nahitfidanci.auth0Apple</strong>”)</li><li>Use the key from step 4 for the Client Secret Signing Key (copy the entire contents, including the <strong>BEGIN/END PRIVATE KEY</strong> lines)</li></ol><p>Apple Team ID and Key ID come from Apple.</p><p>Documentation says:</p><ul><li><strong>Apple Team ID: </strong>Add your Apple Team ID. In the Apple Developer Console top right menu, navigate to View Membership &gt; Membership &gt; Team ID.</li><li><strong>Key ID: </strong>Paste the key ID of your Apple key. To find this, navigate to Certs, Identifiers, nad Profiles in the Apple Developer Console. Choose Keys and open your key.</li></ul><p>That’s it! You have successfully set up sign in with google and apple.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/1*ui7qnprbkKUxsQEU71pyFA.png" /></figure><h3>Conclusion</h3><p>In conclusion, this article has provided you a guide on how to set up Google and Apple Sign-In using Auth0.</p><p>Thank you for reading this article and I hope it has been helpful. If you have any further questions or issues, feel free to reach out. Have a great day!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b5637084028" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrate Google and Apple sign-in to your Flutter app through Auth0 — Part-1]]></title>
            <link>https://fnfidanci.medium.com/integrate-google-and-apple-sign-in-to-your-flutter-app-through-auth0-part-1-9bb1d26880cd?source=rss-c17b8fc11bf6------2</link>
            <guid isPermaLink="false">https://medium.com/p/9bb1d26880cd</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[auth0]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[sign-in-with-google]]></category>
            <category><![CDATA[sign-in-with-apple]]></category>
            <dc:creator><![CDATA[Nahit FIDANCI]]></dc:creator>
            <pubDate>Sat, 24 Dec 2022 00:47:02 GMT</pubDate>
            <atom:updated>2023-01-18T18:51:25.238Z</atom:updated>
            <content:encoded><![CDATA[<h3>Integrate Google and Apple sign-in to your Flutter app through Auth0 — Part-1</h3><h3>Introduction</h3><p>It’s been a long time since I wrote my last article. I feel like I need to do more. And I decided to contribute to the community more with in-depth tutorials and key points for developing better Flutter apps.</p><p>Today, I will show you how to integrate Google and Apple sign-in through Auth0. First, I will create a project on Auth0 and then integrate Google and Apple, respectively. After that, I will show you how to create a well-structured and maintainable authentication service.</p><p>Before we start, I will use Auth0 development keys to first demonstrate how to set up a working authentication service with social connections. In part 2, I will show you how to set up a production environment.</p><h3>Create a new tenant on Auth0</h3><p>After you log in, at the top right corner, create a new tenant.</p><p>It will navigate you to the below screen. Just give a name. You can leave the rest as is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*QzbaVWG9ZyKBXhvphr1Pqw.png" /></figure><p>After that, create a new application. Go to Applications and then Create Application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*GV3qeOX9WEucLgPQUWIdzw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N58EWkP9CjF66wIEgMoeog.png" /></figure><p>Give it a name and select Native.</p><p>The important part is social connections. In the Quick Start tab, you can find a default auth0 connection guide. You can either follow the setup from there or here.</p><p>Before continuing, let’s create a Flutter app. You can give any name you like. I will use the below command. The organization name is <strong>com.nahitfidanci</strong> and the app name is <strong>social_connections</strong>.<strong> </strong>This will be important when we set up allowed callback/logout URLs.</p><blockquote>flutter create --org com.nahitfidanci social_connections</blockquote><h3>Base configurations for Android and iOS</h3><p>First of all, we need to add allowed callback/logout URLs.</p><p>Android: SCHEME://nahit-fidanci.eu.auth0.com/android/YOUR_PACKAGE_NAME/callback</p><p>iOS: YOUR_BUNDLE_ID://nahit-fidanci.eu.auth0.com/ios/YOUR_BUNDLE_ID/callback</p><p>Above, are example callback URLs of mine without bundle id and package names. According to our setting above, my YOUR_BUNDLE_ID ‘<strong>com.nahitfidanci.socialConnections’</strong>and YOUR_PACKAGE_NAME will be ‘<strong>com.nahitfidanci.social_connections’. </strong>SCHEME can be ‘<strong>demo’ </strong>if you don’t have a custom scheme. Actually, I tried to use <strong>https</strong> but it redirects me to not found page. I searched on the internet and found other users have the same issue and they use <strong>demo</strong> instead. So, I will keep it as <strong>demo</strong> for now. If you find how <strong>https</strong> can be used, please do not hesitate to leave a comment.</p><p>After the modifications, they will look like these:</p><p>Android: <a href="https://nahit-fidanci.eu.auth0.com/android/com.nahitfidanci.social_connections">demo://nahit-fidanci.eu.auth0.com/android/com.nahitfidanci.social_connections</a>/callback</p><p>iOS: com.nahitfidanci.socialConnections://nahit-fidanci.eu.auth0.com/ios/com.nahitfidanci.socialConnections/callback</p><p>Let’s add them to <strong>Allowed Callback URLs</strong> and <strong>Allowed Logout URLs</strong> under the <strong>Application URIs </strong>section in our auth0 native app’s <strong>Settings</strong>. Don’t forget to separate links with comma (,).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*OKcpKF3zKf1LMeJgsw4Veg.png" /></figure><h4>Android</h4><p>First, let’s make it clean and create a string resource under :</p><blockquote>social_connections/android/app/src/main/res/values/strings.xml</blockquote><p>The domain should be your tenant domain. It is in the <strong>Settings</strong> of your auth0 native app, under the <strong>Basic Information</strong> sections as named <strong>Domain</strong>. For me, it will look like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2e234fb4e9cc99a62343670de0de847/href">https://medium.com/media/f2e234fb4e9cc99a62343670de0de847/href</a></iframe><p>After that, we can use them in app/build.gradle.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ecaffc2ebe4dc0696f6fc6d697f5320/href">https://medium.com/media/5ecaffc2ebe4dc0696f6fc6d697f5320/href</a></iframe><p>Don’t forget to assign new placeholders with <strong>+=. </strong>Otherwise, you will get an error. With this form, you add new placeholders onto existing ones.</p><h4>iOS</h4><p>Open the iOS project of your app. Under <strong>TARGETS</strong>, open <strong>Runner</strong> and then <strong>Info</strong>. At the bottom of the page, add a new URL Type. Identifier should be <strong>auth0</strong> and URL Schemes should be <strong>$(PRODUCT_BUNDLE_IDENTIFIER)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4vWTh0dj56xhpLo3m39JNg.png" /></figure><h3>Add Apple connection to the Auth0 project</h3><p>Google sign-in is the default connection. So, we only need to add Apple connection.</p><p>Under the <strong>Authentication</strong> dropdown, choose <strong>Social</strong> and then click <strong>Create Connection</strong> button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*qv3fy9stSpbPU2d2c0oH0w.png" /></figure><p>Choose <strong>Apple</strong> and then click <strong>Continue.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*QvqxCH59L8OfBnLMCf14ng.png" /></figure><p>You can leave <strong>ClientID</strong> and <strong>Client Secret Signing Key</strong> as is. In part 2, we will use actual keys. But you need to add your <strong>Apple Team ID</strong> and <strong>Key ID</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NGVAN08o1hCRhtRuOPF2NQ.png" /></figure><p>And then, hit the <strong>Create</strong> button. And you’re done.</p><h3>Create an authentication service in the Flutter app</h3><p>First of all, let’s add <a href="https://pub.dev/packages/auth0_flutter">auth0_flutter</a> SDK in pubspec.yaml. After that let’s create an authentication service.</p><p>The folder structure will look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*cf3pe0c9KmGQSpIFi55zyg.png" /></figure><p>Let’s create a base authentication service, abstract class. We need to configure Auth0 here. So, other child classes can access it from one place. We will have two basic methods <strong>signIn()</strong> and <strong>signOut()</strong>. For domain and client id, as usual, we will use tenant domain and client id.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/caf9111781b4e0a862eb24fa6079244a/href">https://medium.com/media/caf9111781b4e0a862eb24fa6079244a/href</a></iframe><p>We might authenticate users with credentials beside social connections. I will not implement auhentication with credentials but I will treat that we have. So, lets create divide authentication methods into two categories. One is <strong>AuthenticationWithCredentials</strong> and the other is <strong>AuthenticationWithSocialConnections</strong>. We extend AuthenticationService with these descendants because each can override <strong>signIn()</strong> and <strong>signOut()</strong> in their own ways. We actually give them freedom by abstraction. And thanks to generics we can return anything in <strong>signIn()</strong> method by specifying it in <strong>AuthenticationService&lt;T&gt;</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85926965e4f54a3b2f9e6bc26ccb639b/href">https://medium.com/media/85926965e4f54a3b2f9e6bc26ccb639b/href</a></iframe><p>Let’s understand the above class. We have a <strong>connection</strong> getter. And we use it in signIn() method. Why? Because if we don’t specify the connection, it will navigate us to the default social login page of auth0. If we use that page instead, it would be nonsense to have two different authentication buttons on our Flutter App. Since each will navigate us to the Auth0 page. See below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*ge5wsgt8wPUpZDKIYZ_03A.png" /></figure><p><strong>connection </strong>getter returns an enum. And we use a custom name called <strong>getName </strong>to use the proper connection name. For example, <strong>SocialConnection.google.getName</strong> returns <strong>google-auth2.</strong> We will override the getter later in terms of connection type.</p><p>We also need to specify the <strong>scheme</strong> as <strong>demo</strong>. To be clear, we didn’t create a new <strong>Auth0</strong> instance. We still use the one that we created in the parent class.</p><p><strong>signIn()</strong> and <strong>signOut()</strong> methods simply use <strong>Auth0</strong> methods<strong> login()</strong> and <strong>logout()</strong>, respectively.</p><blockquote>Top right corner of the above screenshot, there is a red warning icon. This is because, we still use auth0 development keys.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12f056cd1da848af5ee4b09ec3031162/href">https://medium.com/media/12f056cd1da848af5ee4b09ec3031162/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f7e5e66dbc95365a92f90a2ffbeb602/href">https://medium.com/media/3f7e5e66dbc95365a92f90a2ffbeb602/href</a></iframe><p>Without knowing the details of the implementation, we just gave the proper SocialConnection enum. Let’s use them.</p><h3>Create a simple UI to test the new authentication service</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9179d67af04b63cf8f39a717844b33ab/href">https://medium.com/media/9179d67af04b63cf8f39a717844b33ab/href</a></iframe><p>We use descendants of <strong>AuthenticationWithSocialConnections </strong>because each overrides the connection getter in the proper enum value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6094d0f58c9fa07dbf18b79abb962282/href">https://medium.com/media/6094d0f58c9fa07dbf18b79abb962282/href</a></iframe><p>We use <strong>AuthenticationWithSocialConnections</strong> to sign out. We didn’t use <strong>signOut()</strong> from any social connections since there is no specific case to sign out for any of the connections. If in the future, there will be an extra process that is different for each social connection, then we can override the <strong>signOut()</strong> method and use it.</p><p>And then we display basic user info in the ProfilePage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*tTwBCwwDNn2HUe90_NuK6Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*q_hmG_Rs3VBStCrmkOxTKw.png" /></figure><h3>Source Code</h3><p>You can clone the below repository and use your own domain and client id to try.</p><p><a href="https://github.com/dokumanx/social_connections.git">GitHub - dokumanx/social_connections</a></p><h3>Conclusion</h3><p>I hope that I can explain well how to set up auth0 and social connections and how to use them in a proper way. In part 2, I will show you how to set up social connections for production. And we will get rid of the red warning once and for all. Thank you for reading. Have a good one!</p><blockquote>Read on <a href="https://nahitfidanci.medium.com/integrate-google-and-apple-sign-in-to-your-flutter-app-through-auth0-part-2-2b5637084028">Integrate Google and Apple sign-in to your Flutter app through Auth0 — Part-2</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bb1d26880cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>