<?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 Suraj Kulkarni on Medium]]></title>
        <description><![CDATA[Stories by Suraj Kulkarni on Medium]]></description>
        <link>https://medium.com/@thekoolsk?source=rss-99142d57c98d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*_Yt8Sp0ew0AMQVbr.jpg</url>
            <title>Stories by Suraj Kulkarni on Medium</title>
            <link>https://medium.com/@thekoolsk?source=rss-99142d57c98d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 14:58:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thekoolsk/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[Fastest way to open flutter modules from native using pre-warmed FlutterEngine]]></title>
            <link>https://thekoolsk.medium.com/fastest-way-to-open-flutter-modules-from-native-using-pre-warmed-flutterengine-115a24e4139f?source=rss-99142d57c98d------2</link>
            <guid isPermaLink="false">https://medium.com/p/115a24e4139f</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Suraj Kulkarni]]></dc:creator>
            <pubDate>Sun, 09 Apr 2023 16:30:36 GMT</pubDate>
            <atom:updated>2023-04-09T16:30:36.888Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S3RmaX0fefOcSNBi_KwMFA.jpeg" /></figure><p>This article is all about integrating flutter module in an existing android app. Whenever you decide to migrate your app to flutter it has to be done in baby steps. We all know flutter module can easily co-exist with native but, the first and foremost question you will face from product team is — “<em>Will user face any difference when flutter screen is opened from native?</em>”. The answer to this question is not straightforward, it complete depends upon how you start the flutter engine before rendering the first flutter screen.</p><p>So here we save two options to initialise flutter engine</p><ol><li>Initialise the flutter engine at the app start.</li><li>Initialise the flutter engine at later point when user tiggers the flutter module.</li></ol><p>Both of them has pros and cons — If you initialise the flutter engine at the app start then it adds additional memory overhead on app start plus latency. If you initialise the flutter engine at later point when user tiggers then the first time screen loading time increases as framework has to initialise the engine first then need to render the flutter screen. To know more about exact latency delays visit <a href="https://docs.flutter.dev/development/add-to-app/performance">ref</a>.</p><p>To initialise the flutter engine in a way that avoids adding latency and memory overhead at app startup, and prevents users from facing screen rendering delays when triggering the flutter module for the first time, you need to find the sweet spot between these two options.</p><p>At this point we have understood that we need to prewarm the flutter engine before we render the flutter screen so let us explore the steps performed by flutter framework when engine is initialised -</p><ol><li>Finding the Flutter resources</li><li>Loading the Flutter library</li><li>Starting the Dart VM</li><li>Creating and running a Dart Isolate</li></ol><p>The most important step here for us is last point, it means when flutter engine creates and runs “Dart Isolate”, (closest ally of thread for Java devs) the function main() is executed. Inside which we have written code for our root widget. Subsequently which means the whole flutter widget tree is initialised at this stage and everything is ready except the screen rendering part. This might create a problem when you need few params to initialise the flutter screen and you don’t have those params when you initialised the flutter engine. To put it in simple words suppose you decided to initialise flutter engine on app startup(ideally you should not) and you need profile ID to call profile API on flutter side but on app start up you do not have profile ID now you are stuck in this scenario.</p><p>To tackle such scenarios you need to initialise flutter engine with a placeholder screen which will not have any widget inside it. Just an empty screen. Later when you have profile ID with you and you are about to visit profile screen you can send a message over platform channel which will have route name for navigation and profile ID as a param. This will prepare the flutter screen for rendering just before user visits it.</p><p>Additional benefits of following this approach is even if you have multiple modules which are being opened from different locations in your native app. You become independent of initial screen and every time you open a module it will have its own route and parameters required for it which will be passed only while routing to that particular module. By doing so you are loose coupling components. Enough of talk let me show you some code.</p><p>Flutter Engine handler singleton class of Native (Android) side :</p><pre><br><br>import android.content.Context<br>import io.flutter.embedding.engine.FlutterEngine<br>import io.flutter.embedding.engine.FlutterEngineCache<br>import io.flutter.embedding.engine.dart.DartExecutor<br>import io.flutter.plugin.common.MethodChannel<br><br>object FlutterEngineHandler {<br>    private const val engineId = &quot;FlutterEngine&quot;<br>    private const val nativeToFlutterChannel = &quot;nativeToFlutterChannel&quot;<br>    private lateinit var flutterEngine: FlutterEngine<br>    private lateinit var methodChannel : MethodChannel<br><br>    fun initFlutterEngine(context: Context) {<br>        flutterEngine = FlutterEngine(context)<br>        flutterEngine.navigationChannel.setInitialRoute(&quot;/&quot;)<br>        flutterEngine.dartExecutor.executeDartEntrypoint(DartExecutor.DartEntrypoint.createDefault())<br>        FlutterEngineCache<br>            .getInstance()<br>            .put(engineId, flutterEngine)<br>        methodChannel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger,nativeToFlutterChannel)<br>    }<br><br>    fun getEngine(): FlutterEngine {<br>        if (this::flutterEngine.isInitialized) {<br>            return flutterEngine<br>        } else {<br>            throw UninitializedPropertyAccessException(&quot;Flutter engine not initialised call initFlutterEngine() first&quot;)<br>        }<br>    }<br><br>    fun setStartRoute(route : String){<br>        if (this::flutterEngine.isInitialized) {<br>            methodChannel.invokeMethod(&quot;setInitialRoute&quot;,route)<br>        } else {<br>            throw UninitializedPropertyAccessException(&quot;Flutter engine not initialised call initFlutterEngine() first&quot;)<br>        }<br>    }<br>}</pre><p>In Your application class on Android side :</p><pre>class MyApplication : Application() {<br>    lateinit var flutterEngine : FlutterEngine<br><br>    override fun onCreate() {<br>        super.onCreate()<br>        FlutterEngineHandler.initFlutterEngine(this)<br>    }<br>}</pre><p>In Activity/Fragment from where you want to launch flutter module :</p><pre> binding.btFlutter1.setOnClickListener {<br>            FlutterEngineHandler.setStartRoute(&quot;/module1&quot;)<br>            val intent = Intent(this, MainFlutterActivity::class.java)<br>            startActivity(intent)<br>        }<br><br>        binding.btFlutter2.setOnClickListener {<br>            FlutterEngineHandler.setStartRoute(&quot;/module2&quot;)<br>            val intent = Intent(this, MainFlutterActivity::class.java)<br>            startActivity(intent)<br>        }</pre><p>And your hosting activity for flutter code will be something like this :</p><pre><br><br>import android.content.Context<br>import android.content.ContextWrapper<br>import android.content.Intent<br>import android.content.IntentFilter<br>import android.os.BatteryManager<br>import android.os.Build<br>import android.os.Bundle<br>import android.os.PersistableBundle<br>import android.util.Log<br>import androidx.annotation.NonNull<br>import io.flutter.embedding.android.FlutterActivity<br>import io.flutter.embedding.engine.FlutterEngine<br>import io.flutter.plugin.common.MethodChannel<br>import io.flutter.view.FlutterView.FirstFrameListener<br>import io.flutter.embedding.android.FlutterView as flutterView<br><br>class MainFlutterActivity : FlutterActivity(), FirstFrameListener {<br>    private val CHANNEL = &quot;samples.flutter.dev/battery&quot;<br><br>    override fun provideFlutterEngine(context: Context): FlutterEngine =<br>        FlutterEngineHandler.getEngine()<br><br>    override fun onFirstFrame() {<br><br>    }<br>}</pre><p>Coming to Flutter side your main root widget :</p><pre>void main() {<br>  WidgetsFlutterBinding.ensureInitialized();<br>  runApp(const MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br><br>  // This widget is the root of your application.<br>  @override<br>  Widget build(BuildContext context) {<br>    var router = MyRouter();<br>    FlutterMethodChannel.instance.configureChannel();<br>    return MaterialApp.router(<br>      title: &#39;Flutter Demo&#39;,<br>      theme: ThemeData(<br>        primarySwatch: Colors.blue,<br>      ),<br>      routerConfig: router.router,<br>    );<br>  }<br>}</pre><p>Your router class :</p><pre>class MyRouter {<br>  static final MyRouter _singleton = MyRouter._internal();<br>  GoRouter? router;<br><br>  factory MyRouter() {<br>    return _singleton;<br>  }<br><br>  MyRouter._internal() {<br>    router = GoRouter(routes: _getAllRoutes());<br>  }<br><br>  List&lt;RouteBase&gt; _getAllRoutes() {<br>    var routes = [<br>      GoRoute(path: &quot;/placeholder&quot;, builder: (context, state) =&gt; const InitialScreen()),<br>      GoRoute(<br>          path: &quot;/module1&quot;,<br>          builder: (context, state) =&gt; const Module1Home(title: &quot;Module 1&quot;)),<br>      GoRoute(path: &quot;/module2&quot;, builder: (context, state) =&gt;  const MyHomePage(title: &quot;Module 2&quot;,)),<br>      GoRoute(<br>          path: &quot;/module1Screen1&quot;,<br>          builder: (context, state) =&gt; const Screen2()),<br>    ];<br>    return routes;<br>  }<br>}</pre><p>Platform channels on flutter side to accept the commands from native side :</p><pre>class FlutterMethodChannel {<br>  static const _channelName =<br>      &#39;nativeToFlutterChannel&#39;; // this channel name needs to match the one in Native method channel<br>  late MethodChannel _methodChannel;<br>  // late BuildContext context;<br>  static final FlutterMethodChannel instance = FlutterMethodChannel._init();<br><br>  FlutterMethodChannel._init();<br><br>  void configureChannel() {<br>    // this.context = context;<br>    _methodChannel = const MethodChannel(_channelName);<br>    _methodChannel.setMethodCallHandler(_methodHandler);<br>  }<br><br>  Future&lt;void&gt; _methodHandler(MethodCall call) async {<br>    var router = MyRouter();<br>    BuildContext? context = router.router?.routerDelegate.navigatorKey.currentContext;<br>    switch (call.method) {<br>      case &quot;setInitialRoute&quot;:<br>        print(&quot;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; data ${call.method} ${call.arguments} ${context}&quot;);<br>        try {<br>          if(context != null) {<br>            GoRouter.of(context)<br>                .pushReplacement(call.arguments);<br>          }<br>        }catch(exception){<br>          print(&quot;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; exception $exception&quot;);<br>        }<br>        break;<br>      default:<br>        print(&#39;no method handler for method ${call.method}&#39;);<br>    }<br>  }<br>}</pre><p>And that’s all you need to do. This will make your flutter app modularise and from native side you just need to call independent modules with their routes and params. This will also answer our initial question “<em>Will user face any difference when flutter screen is opened from native?</em>”. User will not face any issue provided this condition is satisfied — <strong><em>Flutter engine is prewarmed before launching the screen.</em></strong></p><p>If you wanna learn more about android and flutter follow me on <a href="http://www.linkedin.com/in/thekoolsk">linkedIn</a>, <a href="https://twitter.com/thekoolsk">twitter</a>. 🌟👨🏻‍💻🙏🏻</p><p>Please don’t forget to hit clap button👏🏻 if this article added some value in your code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=115a24e4139f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android-Better alternative for EventBus and local broadcast receivers using Flow]]></title>
            <link>https://thekoolsk.medium.com/android-better-alternative-for-eventbus-and-local-broadcast-receivers-using-flow-c0d0ae3e8344?source=rss-99142d57c98d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0d0ae3e8344</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-beginners]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Suraj Kulkarni]]></dc:creator>
            <pubDate>Sun, 12 Mar 2023 13:58:06 GMT</pubDate>
            <atom:updated>2023-03-12T13:58:06.046Z</atom:updated>
            <content:encoded><![CDATA[<p>The original idea for this pattern came from <a href="https://medium.com/@mohitrajput987/event-bus-pattern-in-android-using-kotlin-flows-1fe0c6ca08c8">this</a> blog. Many thanks to <a href="https://medium.com/u/49a9fa9ed7ce">Mohit Rajput</a> for this pattern. My article will be an enhanced version of this pattern. I will be using Kotlin reflections and a custom annotation to automatically subscribe to bus. So here we go.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P4oQ9uSDNR3hGEXXZ4rP6Q.jpeg" /></figure><p><strong>Step 1 : </strong>Add dependency of Kotlin refection -</p><pre>implementation &quot;org.jetbrains.kotlin:kotlin-reflect:1.6.21&quot;</pre><p><strong>Step 2 : </strong>Core Eventbus class -</p><pre>import kotlinx.coroutines.GlobalScope.coroutineContext<br>import kotlinx.coroutines.ensureActive<br>import kotlinx.coroutines.flow.MutableSharedFlow<br>import kotlinx.coroutines.flow.asSharedFlow<br>import kotlinx.coroutines.flow.collectLatest<br>import kotlinx.coroutines.flow.filterIsInstance<br><br><br>object KotlinBus {<br>    private val _events = MutableSharedFlow&lt;Any&gt;()<br>    val events = _events.asSharedFlow()<br><br>    suspend fun publish(event: Any) {<br>        _events.emit(event)<br>    }<br><br>    suspend inline fun &lt;reified T&gt; subscribe(crossinline onEvent: (T) -&gt; Unit) {<br>        events.filterIsInstance&lt;T&gt;()<br>            .collectLatest { event -&gt;<br>                coroutineContext.ensureActive()<br>                onEvent(event)<br>            }<br>    }<br>}</pre><p><strong>Step 3 : </strong>Custom annotation to recognise the subscribe function automatically -</p><pre>@Retention(AnnotationRetention.RUNTIME)<br>@Target(AnnotationTarget.FUNCTION)<br>annotation class Listen</pre><p><strong>Step 4 : </strong>BaseFragment/BaseActivity -</p><p>You need use your BaseFragment and BaseActivity class to write one time code for automatic subscription.</p><pre>open class BaseFragment : Fragment(){<br><br> override fun onViewCreated(view: View, savedInstanceState: Bundle?) {<br>        super.onViewCreated(view, savedInstanceState)<br>        subscribeToKotlinBus()<br>    }<br><br>  private fun subscribeToKotlinBus() {<br>        for (declaredMethod in javaClass.declaredMethods) {<br>            if (declaredMethod.isAnnotationPresent(Listen::class.java)) {<br>                try {<br>                    declaredMethod.invoke(this)<br>                } catch (e: IllegalAccessException) {<br>                    Utils.logException(e)<br>                } catch (e: InvocationTargetException) {<br>                    Utils.logException(e)<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>In <em>subscribeToKotlinBus() </em>function we first of all found all the methods from the child class, then we identified those method who have <em>Listen </em>annotation to them. After that we just invoked those functions using Kotlin refection. Thus we automatically subscribed to the events which are expected to be received by this class.</p><p><strong>Step 5 : </strong>Receive event<strong> </strong>usage -</p><pre>class MyFragment : BaseFragment(){<br>  @Listen<br>  fun onEventTriggered(){<br>      lifecycleScope.launch {<br>          viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.CREATED){<br>              KotlinBus.subscribe&lt;String&gt; {<br>                  Log.i(&quot;Received&quot;,it.toString())<br>              }<br>          }<br>      }<br>  }<br>}</pre><p><strong>Step 6: </strong>Publish event<strong> </strong>usage -</p><pre>class AnyRandomClass {<br>  suspend fun triggerEvent(){<br>    KotlinBus.publish(&quot;Test data to publish&quot;)<br>  }<br>}</pre><p>If you follow above approach there is no need to manually call <em>onEventTriggered() </em>function in <em>onViewCreated() </em>for<em> </em>subscription. Just annotate with @Listen and start listening to events.</p><p>If you wanna learn more about android and flutter follow me on <a href="http://www.linkedin.com/in/thekoolsk">linkedIn</a>, <a href="https://twitter.com/thekoolsk">twitter</a>. 🌟👨🏻‍💻🙏🏻</p><p>Please don’t forget to hit clap button👏🏻 if this article added some value in your code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0d0ae3e8344" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cleanest way to manage runtime permissions in android.]]></title>
            <link>https://thekoolsk.medium.com/cleanest-way-to-manage-runtime-permissions-in-android-45225f46419b?source=rss-99142d57c98d------2</link>
            <guid isPermaLink="false">https://medium.com/p/45225f46419b</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[permission]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Suraj Kulkarni]]></dc:creator>
            <pubDate>Fri, 10 Mar 2023 00:32:04 GMT</pubDate>
            <atom:updated>2024-05-23T17:42:03.647Z</atom:updated>
            <content:encoded><![CDATA[<p>Runtime permissions are one of the most common and at the same time most challenging topic in android. In this article I am gonna solve this puzzle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZtVBaGkeqzTTz3uvMo8Tyg.jpeg" /></figure><p>An ideal permission manager should be able to perform following tasks in a clean way.</p><ol><li>It should request appropriate permissions as per android API levels.</li><li>It should handle multiple and single permission requests.</li><li>Permission Manager should be a centralised wrapper class.</li><li>It should support request from both activity and fragment.</li><li>It should check if permission(s) are already granted before requesting.</li><li>In case of multiple permissions requests it should provide summarised as well as detailed status of the individual permission.</li><li>Permission Manager should handle show rationale and permanently denied cases internally.</li><li>Should work with both Java and Kotlin.</li></ol><p>To achieve all above mentioned points we need to have 3 different classes :</p><ol><li>Permissions</li><li>PermissionManager</li><li>PermissionPreferences</li></ol><p>Let’s understand responsibility of each of them one by one.</p><p><strong>Permissions</strong></p><p>This class is responsible for 2 things bundle multiple permissions in single object and provide appropriate permissions as per android API levels.</p><pre>import android.Manifest.permission.*<br><br><br>sealed class Permissions(vararg val permissions: String) {<br>    // Individual permissions<br>    object Camera : Permissions(CAMERA)<br>    // Bundled permissions<br>    object ImagePick : Permissions(*getImagePickPermissions())<br>    object ImgVidCamPerm : Permissions(*getImgVidCamPermission())<br>    object ImgVidPerm : Permissions(*getImgVidPermission())<br>    object AudioPickPerm : Permissions(*getAudioPermission())<br>    // Grouped permissions<br>    object Location : Permissions(ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION)<br><br>    companion object {<br>        private fun getImagePickPermissions(): Array&lt;String&gt; {<br>            return if (PermissionManager.sdkEqOrAbove33()) {<br>                arrayOf(READ_MEDIA_IMAGES)<br>            } else if (PermissionManager.sdkEqOrAbove29()) {<br>                arrayOf(READ_EXTERNAL_STORAGE)<br>            } else {<br>                arrayOf(<br>                    READ_EXTERNAL_STORAGE,<br>                    WRITE_EXTERNAL_STORAGE<br>                )<br>            }<br>        }<br>        private fun getImgVidCamPermission(): Array&lt;String&gt; {<br>            return if (PermissionManager.sdkEqOrAbove33()) {<br>                arrayOf(READ_MEDIA_IMAGES, READ_MEDIA_VIDEO, CAMERA)<br>            } else if (PermissionManager.sdkEqOrAbove29()) {<br>                arrayOf(READ_EXTERNAL_STORAGE, CAMERA)<br>            } else {<br>                arrayOf(<br>                    READ_EXTERNAL_STORAGE,<br>                    WRITE_EXTERNAL_STORAGE,<br>                    CAMERA<br>                )<br>            }<br>        }<br>         private fun getAudioPermission(): Array&lt;String&gt; {<br>            return if (PermissionManager.sdkEqOrAbove33()) {<br>                arrayOf(READ_MEDIA_AUDIO)<br>            } else if (PermissionManager.sdkEqOrAbove29()) {<br>                arrayOf(READ_EXTERNAL_STORAGE)<br>            } else {<br>                arrayOf(<br>                    READ_EXTERNAL_STORAGE,<br>                    WRITE_EXTERNAL_STORAGE<br>                )<br>            }<br>        }<br>      private fun getImgVidPermission(): Array&lt;String&gt; {<br>            return if (PermissionManager.sdkEqOrAbove33()) {<br>                arrayOf(READ_MEDIA_IMAGES, READ_MEDIA_VIDEO)<br>            } else if (PermissionManager.sdkEqOrAbove29()) {<br>                arrayOf(READ_EXTERNAL_STORAGE)<br>            } else {<br>                arrayOf(<br>                    READ_EXTERNAL_STORAGE,<br>                    WRITE_EXTERNAL_STORAGE<br>                )<br>            }<br>        }<br>    }<br>}</pre><p>You can add as many permissions as you want here. This achieves point number 1and 2 of our ideal permission manager.</p><p><strong>PermissionManager</strong></p><pre>import android.Manifest<br>import android.annotation.SuppressLint<br>import android.app.AlertDialog<br>import android.content.Context<br>import android.content.ContextWrapper<br>import android.content.Intent<br>import android.content.pm.PackageManager<br>import android.net.Uri<br>import android.os.Build<br>import android.provider.Settings<br>import androidx.activity.result.ActivityResultLauncher<br>import androidx.activity.result.contract.ActivityResultContracts.RequestMultiplePermissions<br>import androidx.annotation.ChecksSdkIntAtLeast<br>import androidx.appcompat.app.AppCompatActivity<br>import androidx.core.content.ContextCompat<br>import androidx.fragment.app.Fragment<br>import androidx.lifecycle.DefaultLifecycleObserver<br>import androidx.lifecycle.LifecycleOwner<br>import java.lang.ref.WeakReference<br><br>class PermissionManager private constructor(private val lifecycleOwner : WeakReference&lt;LifecycleOwner&gt;) : DefaultLifecycleObserver{<br><br>    private val requiredPermissions = mutableListOf&lt;Permissions&gt;()<br>    private var rationaleDescription: String? = null<br>    private var rationaleTitle: String? = null<br>    private var permanentlyDeniedDescription: String? = null<br>    private var callback: (Boolean) -&gt; Unit = {}<br>    private var intent : Intent? = null<br>    private var detailedCallback: (Map&lt;String, Boolean&gt;) -&gt; Unit = {}<br>    private val deniedList = arrayListOf&lt;String&gt;()<br>    private lateinit var permissionCheck : ActivityResultLauncher&lt;Array&lt;String&gt;&gt;<br>    private var activity : AppCompatActivity? = null<br><br>    init {<br>        lifecycleOwner.get()?.lifecycle?.addObserver(this)<br>    }<br>    override fun onCreate(owner: LifecycleOwner) {<br>        permissionCheck = if (owner is AppCompatActivity) {<br>            owner.registerForActivityResult(RequestMultiplePermissions()) { grantResults -&gt;<br>                    sendResultAndCleanUp(grantResults)<br>                }<br>        } else {<br>            (owner as Fragment).registerForActivityResult(RequestMultiplePermissions()) { grantResults -&gt;<br>                sendResultAndCleanUp(grantResults)<br>            }<br>        }<br>        activity = if(lifecycleOwner.get() is Fragment) (lifecycleOwner.get() as? Fragment)?.context?.scanForActivity() else lifecycleOwner.get() as? AppCompatActivity<br>        super.onCreate(owner)<br>    }<br><br>    companion object {<br>        fun from(lifecycleOwner: LifecycleOwner) = PermissionManager(WeakReference(lifecycleOwner))<br><br>        @ChecksSdkIntAtLeast(api = Build.VERSION_CODES.TIRAMISU)<br>        fun sdkEqOrAbove33() = Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.TIRAMISU<br><br>        @ChecksSdkIntAtLeast(api = Build.VERSION_CODES.Q)<br>        fun sdkEqOrAbove29() = Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.Q<br><br>        @ChecksSdkIntAtLeast(api = Build.VERSION_CODES.R)<br>        fun sdkEqOrAbove30() = Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.R<br><br>        @ChecksSdkIntAtLeast(api = Build.VERSION_CODES.S)<br>        fun sdkEqOrAbove31() = Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.S<br><br>        @ChecksSdkIntAtLeast(api = Build.VERSION_CODES.P)<br>        fun sdkEqOrAbove28() = Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.P<br><br>        @SuppressLint(&quot;ObsoleteSdkInt&quot;)<br>        @ChecksSdkIntAtLeast(api = Build.VERSION_CODES.M)<br>        fun sdkEqOrAbove23() = Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.M<br>    }<br><br>    fun rationale(description: String, title : String = activity?.getString(R.string.permission_title) ?: &quot;&quot;): PermissionManager {<br>        rationaleDescription = description<br>        rationaleTitle = title<br>        return this<br>    }<br><br>    fun request(vararg permission: Permissions): PermissionManager {<br>        requiredPermissions.addAll(permission)<br>        return this<br>    }<br><br>    fun permissionPermanentlyDeniedIntent(intent: Intent): PermissionManager {<br>        this.intent = intent<br>        return this<br>    }<br><br>    fun permissionPermanentlyDeniedContent(description : String = &quot;&quot;): PermissionManager {<br>        this.permanentlyDeniedDescription = description.ifEmpty { activity?.getString(R.string.permission_description) }<br>        return this<br>    }<br><br>    fun checkAndRequestPermission(callback: (Boolean) -&gt; Unit) {<br>        this.callback = callback<br>        handlePermissionRequest()<br>    }<br><br>    fun checkAndRequestDetailedPermission(callback: (Map&lt;String, Boolean&gt;) -&gt; Unit) {<br>        this.detailedCallback = callback<br>        handlePermissionRequest()<br>    }<br><br>    private fun handlePermissionRequest() {<br>        // 1 TRUE -&gt; When user has denied the permission at-least once -&gt; rationale alert-dialog show<br>        // 2 FALSE -&gt; i. User has never requested the permission -&gt; Show permission pop-up<br>        //            ii. User has denied the permission permanently -&gt; Settings<br>        activity?.let { activity -&gt;<br>                if (areAllPermissionsGranted(activity)) {<br>                    sendPositiveResult()<br>                } else if (shouldShowPermissionRationale(activity)) {<br>                    getPermissionList().forEach {<br>                        PermissionsPreferences.updatePermissionStatus(it, true)<br>                    }<br>                    val requiresRationaleList = getPermissionList().map { Pair(it,requiresRationale(activity,it)) }<br>                    displayRationale(activity, getCommaSeparatedFormattedString(requiresRationaleList.filter {it.second}.map {it.first}))<br>                } else {<br>                    if (getPermissionList().any{!PermissionsPreferences.getPermissionStatus(it) }) {<br>                        requestPermissions()<br>                    } else {<br>                        displayPermanentlyDenied(activity,getCommaSeparatedFormattedString(<br>                            getPermissionList().filter {isPermanentlyDenied(activity,it)}))<br>                        cleanUp()<br>                    }<br>                }<br>        }<br>    }<br><br>    private fun displayRationale(activity: AppCompatActivity, permission: String?) {<br>        AlertDialog.Builder(activity)<br>            .setTitle(rationaleTitle ?: activity.getString(R.string.permission_title))<br>            .setMessage(rationaleDescription ?: activity.getString(R.string.permission_description, permission ?: &quot;&quot;))<br>            .setCancelable(true)<br>            .setNegativeButton(activity.getString(R.string.no_thanks)){dialog,_ -&gt;<br>                dialog.dismiss()<br>                cleanUp() }<br>            .setPositiveButton(activity.getString(R.string.button_ok)){ _, _ -&gt; requestPermissions()}<br>            .show()<br>    }<br><br>    private fun displayPermanentlyDenied(activity: AppCompatActivity, permission: String?) {<br>        AlertDialog.Builder(activity)<br>            .setTitle(activity.getString(R.string.permission_title))<br>            .setMessage(permanentlyDeniedDescription ?: activity.getString(R.string.permission_description_permanently, permission ?: &quot;&quot;))<br>            .setCancelable(true)<br>            .setNegativeButton(activity.getString(R.string.no_thanks)){dialog,_-&gt;<br>                dialog.dismiss()<br>                cleanUp()}<br>            .setPositiveButton(activity.getString(R.string.go_to_settings)) { _, _ -&gt;<br>                val finalIntent = if(intent != null) {<br>                    intent<br>                }else{<br>                    val intent2 = Intent(<br>                        Settings.ACTION_APPLICATION_DETAILS_SETTINGS,<br>                        Uri.parse(&quot;package:&quot; + activity.packageName)<br>                    )<br>                    intent2.addCategory(Intent.CATEGORY_DEFAULT)<br>                    intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)<br>                    intent2<br>                }<br>                activity.startActivity(finalIntent)<br>            }.show()<br>    }<br><br>    private fun sendPositiveResult() {<br>        sendResultAndCleanUp(getPermissionList().associateWith { true })<br>    }<br><br>    private fun sendResultAndCleanUp(grantResults: Map&lt;String, Boolean&gt;) {<br>        if(deniedList.isNotEmpty()){<br>            activity?.let { displayPermanentlyDenied(it, getCommaSeparatedFormattedString(deniedList)) }<br>        }else{<br>            callback(grantResults.all { it.value })<br>            detailedCallback(grantResults)<br>        }<br>        cleanUp()<br>    }<br><br>    private fun cleanUp() {<br>        requiredPermissions.clear()<br>        rationaleDescription = null<br>        permanentlyDeniedDescription = null<br>        deniedList.clear()<br>        callback = {}<br>        detailedCallback = {}<br>    }<br>// 4 -&gt; 2 NEW 2 Permanently denied<br>    private fun requestPermissions() {<br>        val list = getPermissionList()<br>        val deniedList = list.filter {isPermanentlyDenied(activity,it)}<br>        this.deniedList.addAll(deniedList)<br>        val finalList = list.subtract(deniedList.toSet())<br>        permissionCheck.launch(finalList.toTypedArray())<br>    }<br><br>    private fun areAllPermissionsGranted(activity: AppCompatActivity) =<br>        requiredPermissions.all { it.isGranted(activity) }<br><br>    private fun shouldShowPermissionRationale(activity: AppCompatActivity) =<br>        requiredPermissions.any { it.requiresRationale(activity) }<br><br>    private fun getPermissionList() =<br>        requiredPermissions.flatMap { it.permissions.toList() }.toTypedArray()<br><br>    private fun Permissions.isGranted(activity: AppCompatActivity) =<br>        permissions.all { hasPermission(activity, it) }<br><br>    private fun Permissions.requiresRationale(activity: AppCompatActivity): Boolean {<br>     return   permissions.any { activity.shouldShowRequestPermissionRationale(it) }<br>    }<br><br>    private fun requiresRationale(activity: AppCompatActivity?, permission: String) =<br>        activity?.shouldShowRequestPermissionRationale(permission) ?: false<br>    private fun isPermanentlyDenied(activity: AppCompatActivity?, permission: String) =<br>        !requiresRationale(activity,permission) &amp;&amp; PermissionsPreferences.getPermissionStatus(permission)<br>    private fun hasPermission(activity: AppCompatActivity, permission: String) =<br>        ContextCompat.checkSelfPermission(<br>            activity,<br>            permission<br>        ) == PackageManager.PERMISSION_GRANTED<br><br>    private fun getCommaSeparatedFormattedString(permissions : List&lt;String&gt;) : String?{<br>        val newList = mapPermissionsToStrings(permissions)<br>        val list = newList.toMutableList()<br>        return if(list.size == 1){<br>            list.first()<br>        }else {<br>            list.removeLast()<br>            val string = list.joinToString(&quot;, &quot;)<br>            string + &quot; and &quot; + newList.last()<br>        }<br>    }<br><br>    private fun mapPermissionsToStrings(list: List&lt;String&gt;) : List&lt;String?&gt;{<br>        return list.map {<br>            when(it){<br>                Manifest.permission.POST_NOTIFICATIONS -&gt; activity?.getString(R.string.post_notifications)<br>                Manifest.permission.WAKE_LOCK -&gt; activity?.getString(R.string.wake_lock)<br>                Manifest.permission.INTERNET -&gt; activity?.getString(R.string.internet)<br>                Manifest.permission.ACCESS_NETWORK_STATE -&gt; activity?.getString(R.string.access_network_state)<br>                Manifest.permission.READ_CALENDAR -&gt; activity?.getString(R.string.read_calendar)<br>                Manifest.permission.WRITE_CALENDAR -&gt; activity?.getString(R.string.write_calendar)<br>                Manifest.permission.READ_EXTERNAL_STORAGE -&gt; activity?.getString(R.string.read_external_storage)<br>                Manifest.permission.READ_MEDIA_IMAGES -&gt; activity?.getString(R.string.read_media_images)<br>                Manifest.permission.READ_MEDIA_VIDEO -&gt; activity?.getString(R.string.read_media_video)<br>                Manifest.permission.READ_MEDIA_AUDIO -&gt; activity?.getString(R.string.read_media_audio)<br>                Manifest.permission.SCHEDULE_EXACT_ALARM -&gt; activity?.getString(R.string.schedule_exact_alarm)<br>                Manifest.permission.WRITE_EXTERNAL_STORAGE -&gt; activity?.getString(R.string.write_external_storage)<br>                Manifest.permission.CAMERA -&gt; activity?.getString(R.string.camera)<br>                Manifest.permission.READ_PHONE_STATE -&gt; activity?.getString(R.string.read_phone_state)<br>                Manifest.permission.READ_PHONE_NUMBERS -&gt; activity?.getString(R.string.read_phone_numbers)<br>                Manifest.permission.GET_ACCOUNTS -&gt; activity?.getString(R.string.get_accounts)<br>                Manifest.permission.FOREGROUND_SERVICE -&gt; activity?.getString(R.string.foreground_service)<br>                Manifest.permission.ACCESS_FINE_LOCATION -&gt; activity?.getString(R.string.access_fine_location)<br>                Manifest.permission.RECEIVE_BOOT_COMPLETED -&gt; activity?.getString(R.string.receive_boot_completed)<br>                Manifest.permission.READ_CONTACTS -&gt; activity?.getString(R.string.read_contacts)<br>                Manifest.permission.RECORD_AUDIO -&gt; activity?.getString(R.string.record_audio)<br>                Manifest.permission.ACCESS_WIFI_STATE -&gt; activity?.getString(R.string.access_wifi_state)<br>                Manifest.permission.MODIFY_AUDIO_SETTINGS -&gt; activity?.getString(R.string.modify_audio_settings)<br>                Manifest.permission.BLUETOOTH -&gt; activity?.getString(R.string.bluetooth)<br>                Manifest.permission.BLUETOOTH_CONNECT -&gt; activity?.getString(R.string.bluetooth_connect)<br>                Manifest.permission.ACTIVITY_RECOGNITION -&gt; activity?.getString(R.string.activity_recognition)<br>                Manifest.permission.USE_FULL_SCREEN_INTENT -&gt; activity?.getString(R.string.use_full_screen_intent)<br>                Manifest.permission.VIBRATE -&gt; activity?.getString(R.string.vibrate)<br>                else -&gt; &quot;Other&quot;<br>            }<br>        }<br>    }<br>}<br><br>fun Context.scanForActivity(): AppCompatActivity? {<br>    return when (this) {<br>        is AppCompatActivity -&gt; this<br>        is ContextWrapper -&gt; baseContext.scanForActivity()<br>        else -&gt; {<br>            null<br>        }<br>    }<br>}</pre><p>Let’s look how to use this class and then I will explain it’s features</p><pre>private val permissionManager = PermissionManager.from(this)<br><br>  private fun checkPermissionsAndAccessFeature() {<br>        val intentWhenDeniedPermanently = Intent()<br>        permissionManager<br>            .request(Permissions.ImgVidCamPerm)<br>            .rationale(description = &quot;Please approve permission to access this feature&quot;, title =&quot;Permission required&quot;)<br>            .permissionPermanentlyDeniedIntent(intentWhenDeniedPermanently)<br>            .permissionPermanentlyDeniedContent(description= &quot;To access this feature we need permission please provide access to app from app settings&quot;)<br>            .checkAndRequestPermission {<br>                if(it) openNewImagePicker()<br>                else<br>                    Utils.showToast(mContext,ResourceHelper.getString(R.string.need_this_permission_msg))<br>            }<br>    }<br><br> private fun checkDetailedPermissionsAndAccessFeature() {<br>        val intentWhenDeniedPermanently = Intent()<br>        permissionManager<br>            .request(Permissions.ImgVidCamPerm)<br>            .rationale(description = &quot;Please approve permission to access this feature&quot;, title =&quot;Permission required&quot;)<br>            .permissionPermanentlyDeniedIntent(intentWhenDeniedPermanently)<br>            .permissionPermanentlyDeniedContent(description= &quot;To access this feature we need permission please provide access to app from app settings&quot;)<br>            .checkAndRequestDetailedPermission {<br>                <br>            }<br>    }</pre><ol><li><em>request(mandatory) </em>method will take necessary object of Permissions class.</li><li><em>rationale(optional) </em>method will take description and title of the alert dialog which will be shown when user denies the permission at-least once.</li><li><em>permissionPermanentlyDeniedIntent(optional) </em>method will take an intent which will be used to redirect the user to appropriate permission screen if user has denied the permission permanently.</li><li><em>permissionPermanentlyDeniedContent(optional) </em>method will take description of alert dialog which will be shown to user when user has denied the permission permanently but still trying to access the feature.</li><li><em>checkAndRequestDetailedPermission(mandatory) </em>is a callback which will initiate the flow of checking permission and it will provide the result in the form of Map&lt;String,Boolean&gt; where key will be name of permission value will be status of grant result.</li><li><em>checkAndRequestPermission(mandatory) </em>is a callback which will initiate the flow of checking permission and it will return true if all the requested permissions are granted.</li></ol><p><strong>PermissionPreferences</strong></p><pre>import android.content.Context<br>import android.content.SharedPreferences<br>import androidx.security.crypto.EncryptedSharedPreferences<br>import androidx.security.crypto.MasterKeys<br>import java.io.File<br>import java.io.IOException<br>import java.security.GeneralSecurityException<br><br>object PermissionsPreferences {<br>    private var sharedPreferences: SharedPreferences? = null<br>    private const val PREF_NAME = &quot;permissions_pref&quot;<br><br>    fun initPermissionSharedPreferences(context: Context) {<br>        sharedPreferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)<br>    }<br><br>    fun updatePermissionStatus(key: String, value: Boolean) {<br>        val editor = sharedPreferences?.edit()<br>        editor?.putBoolean(key, value)<br>        editor?.apply()<br>    }<br><br>    fun getPermissionStatus(key: String): Boolean {<br>        return sharedPreferences?.getBoolean(key, false) ?: false<br>    }<br>}</pre><p>This is simple SharedPreferences wrapper class to handle permanently denied case. To know more about permanently denied scenario and runtime permission refer to this <a href="https://medium.com/android-kotlin/handle-android-permissions-easily-even-user-denied-it-permanently-73c55f804da1">blog</a>.</p><p><a href="https://github.com/the-kool-sk/android_permission_manager">Github</a></p><p>If you wanna learn more about android and flutter follow me on <a href="http://www.linkedin.com/in/thekoolsk">linkedIn</a>, <a href="https://twitter.com/thekoolsk">twitter</a>. 🌟👨🏻‍💻🙏🏻</p><p>Please don’t forget to hit clap button👏🏻 if this article added some value in your code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45225f46419b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter- Managing Payment Gateways Like A Pro!]]></title>
            <link>https://thekoolsk.medium.com/flutter-managing-payment-gateways-like-a-pro-b50f2a41a7fd?source=rss-99142d57c98d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b50f2a41a7fd</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter-widget]]></category>
            <dc:creator><![CDATA[Suraj Kulkarni]]></dc:creator>
            <pubDate>Sat, 30 Apr 2022 14:19:48 GMT</pubDate>
            <atom:updated>2022-04-30T14:19:48.824Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl0MYDoN32puQXNmx2%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fl0MYDoN32puQXNmx2%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Fl0MYDoN32puQXNmx2%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="245" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f787d21db7b59203d5d15b7792e62c2/href">https://medium.com/media/6f787d21db7b59203d5d15b7792e62c2/href</a></iframe><p>Payment gateways are most important part of any business app, and you cannot mess with it. I am gonna tell you how you can manage payment gateways at one single place, so that you can easily add or remove payment gateways as per your business requirement. Without wasting much time let’s get started.</p><p>Typical payment flow is something like this :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c3YmgZlVDz0UdIh2qg32ow.png" /><figcaption>Typical Payment Flow</figcaption></figure><blockquote>Steps :</blockquote><ol><li>Writing Data classes.</li><li>Writing Payment Gateway Contract (Interface).</li><li>Implementation of Interface.</li></ol><blockquote>Writing Data Classes</blockquote><p>Our system will contain three data classes</p><ol><li>PaymentEntity</li></ol><pre><em>class </em>PaymentEntity <em>extends </em>BaseDataModel {<br>  <em>final </em>PAYMENTGATEWAY _paymentGateWay;<br>  <em>final </em>String _amount;<br>  <em>final </em>String _currency;<br>  <em>final </em>String _customInfo;<br><br>  PaymentEntity(<em>this</em>._paymentGateWay, <em>this</em>._amount, <em>this</em>._currency, <em>this</em>._customInfo);<br><br>  @override<br>  List&lt;Object?&gt; <em>get </em>props =&gt; [_paymentGateWay, _amount, _currency, _customInfo];<br><br>  PAYMENTGATEWAY <em>get </em>paymentGateWay =&gt; _paymentGateWay;<br><br>  @override<br>  Map&lt;String, Object?&gt; toJson() {<br>    HashMap&lt;String, String&gt; map = HashMap();<br>    map[ParameterKeys.<em>PAYMENT_GATEWAY</em>] = Utils.<em>getCharPaymentGatewayFromEnum</em>(_paymentGateWay);<br>    map[ParameterKeys.<em>AMOUNT</em>] = _amount;<br>    map[ParameterKeys.<em>CURRENCY</em>] = _currency;<br>    <em>return </em>map;<br>  }<br><br>  <em>static </em>PaymentEntity <em>fromJson</em>(Map map) {<br>    <em>return </em>PaymentEntity(<br>      Utils.<em>getEnumPaymentGatewayFromChar</em>(map[ParameterKeys.<em>PAYMENT_GATEWAY</em>]),<br>      map[ParameterKeys.<em>AMOUNT</em>].toString(),<br>      map[ParameterKeys.<em>CURRENCY</em>],<br>      map[ParameterKeys.<em>CUSTOM_INFO</em>],<br>    );<br>  }<br><br>  String <em>get </em>amount =&gt; _amount;<br><br>  String <em>get </em>currency =&gt; _currency;<br><br>  String <em>get </em>customInfo =&gt; _customInfo;<br>}</pre><p>2. PaymentStatusEntity</p><pre><em>class </em>PaymentStatusEntity <em>implements </em>BaseModel {<br>  <em>final </em>bool _isPaymentSuccess;<br><br>  bool <em>get </em>isPaymentSuccess =&gt; _isPaymentSuccess;<br><br>  PaymentStatusEntity(<em>this</em>._isPaymentSuccess);<br><br>  @override<br>  List&lt;Object?&gt; <em>get </em>props =&gt; [_isPaymentSuccess];<br><br>  @override<br>  bool <em>get </em>stringify =&gt; <em>true</em>;<br><br>  @override<br>  Map&lt;String, Object?&gt; toJson() {<br>    <em>throw </em>UnimplementedError();<br>  }<br>}</pre><p>3. GatewaySpecificEntity :</p><pre><em>class </em>RazorpayEntity <em>extends </em>PaymentEntity {<br>  <em>static final </em>Environment <em>_currentEnvironment </em>= AppInfo.<em>getEnvironment</em>(AppInfo.<em>shared</em>.appMode);<br>  <em>final </em>String _razorPayKey = <em>_currentEnvironment</em>.razorPayKey();<br>  <em>final </em>String _amount;<br>  <em>final </em>String _currency;<br>  <em>final </em>String _merchantName = StringResources.<em>appName</em>.tr;<br>  <em>final </em>String _description;<br>  <em>final </em>String _logoLink = Constants.<em>placeHolderImage</em>;<br>  <em>final </em>String _orderId;<br>  <em>final </em>String _userName;<br>  <em>final </em>String _contactNumber;<br>  <em>final </em>String _customInfo;<br><br>  RazorpayEntity(<em>this</em>._amount, <em>this</em>._currency, <em>this</em>._description, <em>this</em>._orderId, <em>this</em>._userName, <em>this</em>._contactNumber, <em>this</em>._customInfo);<br><br>  @override<br>  List&lt;Object?&gt; <em>get </em>props =&gt; [_razorPayKey, _amount, _currency, _merchantName, _description, _logoLink, _orderId, _userName, _contactNumber, _customInfo];<br><br>  @override<br>  Map&lt;String, Object?&gt; toJson() {<br>    HashMap&lt;String, Object&gt; map = HashMap();<br>    HashMap&lt;String, Object&gt; prefillMap = HashMap();<br>    prefillMap[ParameterKeys.<em>NAME</em>] = _userName;<br>    prefillMap[ParameterKeys.<em>CONTACT</em>] = _contactNumber;<br>    prefillMap[ParameterKeys.<em>EMAIL</em>] = &#39;support@yourdomain.com&#39;;<br>    map[ParameterKeys.<em>KEY</em>] = _razorPayKey;<br>    map[ParameterKeys.<em>AMOUNT</em>] = Utils.<em>getAmountFromString</em>(_amount);<br>    map[ParameterKeys.<em>CURRENCY</em>] = _currency;<br>    map[ParameterKeys.<em>NAME</em>] = _merchantName;<br>    map[ParameterKeys.<em>ORDER_ID</em>] = _orderId;<br>    map[ParameterKeys.<em>DESCRIPTION</em>] = _description;<br>    map[ParameterKeys.<em>IMAGE</em>] = _logoLink;<br>    map[ParameterKeys.<em>PREFILL</em>] = prefillMap;<br>    map[ParameterKeys.<em>NOTES</em>] = {&#39;CustomInfo&#39;: _customInfo};<br>    <em>return </em>map;<br>  }<br>}</pre><p>Enums :</p><pre><em>enum </em>PAYMENTGATEWAY { RAZORPAY, PAYU, CASHFREE, NA }</pre><pre><em>enum </em>PAYMENT_STATES { INITIATED, FAILED, SUCCESS }</pre><blockquote>Writing Payment Gateway Contract (Interface).</blockquote><pre><em>abstract class </em>PaymentGatewayManager {<br>  Future&lt;PaymentStatusEntity&gt; razorpayCheckout(String orderId, PaymentEntity entity);</pre><pre>  Future&lt;PaymentStatusEntity&gt; payUCheckout(String orderId, PaymentEntity entity);</pre><pre>Future&lt;PaymentStatusEntity&gt; cashFreeCheckout(String orderId, PaymentEntity entity);</pre><pre>}</pre><blockquote>Implementation of Interface.</blockquote><p>Here the code gets little tricky. Most of the payment gateways does not provide method returning <em>Future </em>instead they ask you to give them a callback method which they calls when the SDK finishes the payment processing. So what are the implications of this, as we don’t have a <em>Future </em>returning function we cannot <em>await</em> but entire flow is build over Streams and Futures so how do you fix this problem? How do you <em>await </em>till the sdk finishes it’s payment processing. Carefully look at below code :</p><pre><em>class </em>PaymentGatewayManagerImpl <em>implements </em>PaymentGatewayManager {<br>  Razorpay razorpay;<br><br>  PaymentGatewayManagerImpl(<em>this</em>.razorpay);<br><br>  @override<br>  Future&lt;PaymentStatusEntity&gt; razorpayCheckout(String orderId, PaymentEntity endpoint) <em>async </em>{<br>    int status = 0;<br>    Future&lt;PAYMENT_STATES&gt; runDelay() <em>async </em>{<br>      <em>await </em>Future.delayed(Duration(seconds: 1));<br>      <em>if </em>(status == 0) {<br>        <em>return </em>runDelay();<br>      } <em>else </em>{<br>        <em>if </em>(status == 1) {<br>          <em>return </em>PAYMENT_STATES.SUCCESS;<br>        } <em>else </em>{<br>          <em>return </em>PAYMENT_STATES.FAILED;<br>        }<br>      }<br>    }<br><br>    dismissCallback() {<br>      status = 2;<br>      Utils.<em>showShorterToast</em>(&quot;Cancelled by user&quot;);<br>    }<br><br>    PaymentEntity paymentEntity = PaymentEntity.<em>fromJson</em>(endpoint.params);<br>    <em>var </em>value = <em>await </em>Utils.<em>getUser</em>();<br>    <em>var </em>options = RazorpayEntity(<br>      paymentEntity.amount,<br>      paymentEntity.currency,<br>      &quot;&quot;,<br>      orderId,<br>      value.name ?? StringResources.<em>appName</em>.tr,<br>      value.mobileNumber ?? &quot;&quot;,<br>      paymentEntity.customInfo,<br>    );<br>    options.toJson()[ParameterKeys.<em>MODAL</em>] =<br>        &quot;{${ParameterKeys.<em>HANDLEBACK</em>} : ${<em>false</em>}, ${ParameterKeys.<em>CONFIRM_CLOSE</em>} : ${<em>true</em>}, ${ParameterKeys.<em>CONFIRM_CLOSE</em>} :&quot;<br>        &quot; ${<em>true</em>} ${ParameterKeys.<em>ONDISMISS</em>} : $dismissCallback()&quot;;</pre><pre>razorpay.open(options.toJson());<br>    razorpay.on(Razorpay.<em>EVENT_PAYMENT_SUCCESS</em>, (PaymentSuccessResponse response) {<br>      status = 1;<br>    });<br>    razorpay.on(Razorpay.<em>EVENT_PAYMENT_ERROR</em>, (PaymentFailureResponse response) {<br>      status = 2;<br>    });<br>    <em>var </em>result = <em>await </em>runDelay();<br>    <em>if </em>(result == PAYMENT_STATES.SUCCESS) {<br>      <em>return </em>PaymentStatusEntity(isPaymentSuccess: <em>true</em>);<br>    } <em>else </em>{<br>      <em>return </em>PaymentStatusEntity(isPaymentSuccess: <em>false</em>);<br>    }<br>  }<br>}</pre><p>So trick is simple I wrote a recursive <em>async</em> runDelay() inside which I checked if the status of the payment using a variable. If it has changed then just stop calling runDelay() and return the response, if not the keep calling it after every second. 😃. After completion of this runDelay() function return the result. 🤑💻💰</p><p>If you wanna learn more about flutter follow me on <a href="http://www.linkedin.com/in/thekoolsk">linkedIn</a>, <a href="https://twitter.com/thekoolsk">twitter</a>. 🌟👨🏻‍💻🙏🏻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b50f2a41a7fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to write null safe code with Kotlin? — Part 2]]></title>
            <link>https://thekoolsk.medium.com/how-to-write-null-safe-code-with-kotlin-part-2-d8924ef592f5?source=rss-99142d57c98d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8924ef592f5</guid>
            <category><![CDATA[kotlin-native]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-beginners]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <dc:creator><![CDATA[Suraj Kulkarni]]></dc:creator>
            <pubDate>Sat, 23 Apr 2022 09:26:18 GMT</pubDate>
            <atom:updated>2022-04-23T09:28:56.291Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to write null safe code with Kotlin? — Part 2</h3><p>In the <a href="https://thekoolsk.medium.com/how-to-write-null-safe-code-with-kotlin-30f917773116">part 1</a> of this article we have seen how Kotlin empower us with it’s null safe syntax. And yet I challenge you, you will face NPE if you don’t use that power wisely. So today let’s discuss some pragmatic ways to avoid NPE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*3E-f11LOg9ZAn7_oBpZSxw.jpeg" /></figure><p>Let’s first talk about what are the sources of NPE, from my personal experience following are the places where NPE occur :</p><ol><li><em>Null</em> value in data classes.</li><li><em>Null</em> value being passed as param to function.</li><li>Global variables being declared as <em>Null</em>.</li></ol><p>Let’s study them one by one.</p><blockquote><em>Null</em> value in data classes.</blockquote><p>Data classes are the containers which have the data from data source. If data inside these containers itself is null you are bound to have NPE. Here data source could be local data source or from and API response. Look at the below JSONs :</p><ol><li>Expected JSON :</li></ol><pre>{<br>  &quot;name&quot;: &quot;Absolute Fitness&quot;,<br>  &quot;membersCount&quot;: 200,<br>  &quot;fees&quot;: 100.5,<br>  &quot;address&quot;: {<br>    &quot;shopNumber&quot;: 101,<br>    &quot;laneName&quot;: &quot;Katraj&quot;,<br>    &quot;district&quot;: &quot;Pune&quot;,<br>    &quot;state&quot;: &quot;MH&quot;,<br>    &quot;pinCode&quot;: 411028<br>  }<br>}</pre><p>2. JSON with <em>null</em> values :</p><pre>{<br>  &quot;name&quot;: null,<br>  &quot;membersCount&quot;: 200,<br>  &quot;fees&quot;: 100.5,<br>  &quot;address&quot;: {<br>    &quot;shopNumber&quot;: 101,<br>    &quot;laneName&quot;: null,<br>    &quot;district&quot;: &quot;Pune&quot;,<br>    &quot;state&quot;: &quot;MH&quot;,<br>    &quot;pinCode&quot;: 411028<br>  }<br>}</pre><p>3. JSON with missing keys :</p><pre>{<br>  &quot;membersCount&quot;: 200,<br>  &quot;fees&quot;: 100.5,<br>  &quot;address&quot;: {<br>    &quot;laneName&quot;: &quot;Katraj&quot;,<br>    &quot;district&quot;: &quot;Pune&quot;,<br>    &quot;state&quot;: &quot;MH&quot;,<br>    &quot;pinCode&quot;: 411028<br>  }<br>}</pre><p>There are two scenarios in this case if you are starting new project the it’s easy for you simply use <a href="https://github.com/square/moshi">MOSHI</a> library which supports default values in Kotlin data classes. Whenever you write a data class make your fields non-nullable and provide a default value to the fields, if any value is coming null from data source the default value will be picked up by moshi while parsing. Same applies if any key is missing in JSON. For example write your data class as below :</p><pre><em>data class </em>GymModel(<br>    <em>val </em>name: String = &quot;default&quot;,<br>    <em>val </em>membersCount: Int = 0,<br>    <em>val </em>fees: Double = 0.0,<br>    <em>val </em>address: Address = Address(shopNumber = 101, laneName = &quot;default&quot;, district = &quot;default&quot;, state = &quot;default&quot;, pinCode = 411011)<br>)<br><br><em>data class </em>Address(<br>    <em>val </em>shopNumber: Int = 0,<br>    <em>val </em>laneName: String = &quot;default&quot;,<br>    <em>val </em>district: String = &quot;default&quot;,<br>    <em>val </em>state: String = &quot;default&quot;,<br>    <em>val </em>pinCode: Long = 0,<br>)</pre><p>Real challenge comes when you are using legacy library GSON with Kotlin. GSON does not respect non-nullable fields and default values of Kotlin data class and you end up writing nullable code without your knowledge, IDE will not throw error, code will get compiled successfully and you will see NPE when only when it will go to production. But wait I have solution for that, you need to make some changes in your data classes so as to solve this problem and here is the magical data class :</p><pre><em>data class </em>GymModel(<br>    @SerializedName(&quot;name&quot;) <em>private val </em>_name: String?,<br>    @SerializedName(&quot;membersCount&quot;) <em>private val </em>_memberCount: Int?,<br>    @SerializedName(&quot;fees&quot;) <em>private val </em>_fees: Double?,<br>    @SerializedName(&quot;address&quot;) <em>private val </em>_address: Address?<br>) {<br>    <em>val </em>name<br>        <em>get</em>() = _name ?: &quot;default&quot;<br>    <em>val </em>membersCount<br>        <em>get</em>() = _memberCount ?: 0<br>    <em>val </em>fees<br>        <em>get</em>() = _fees ?: 0<br>    <em>val </em>address<br>        <em>get</em>() = _address ?: Address(<br>            _shopNumber = 0, _laneName = &quot;default&quot;, _district = &quot;default&quot;, _state = &quot;default&quot;, _pinCode = 0<br>        )<br>}<br><br><em>data class </em>Address(<br>    @SerializedName(&quot;shopNumber&quot;) <em>private val </em>_shopNumber: Int?,<br>    @SerializedName(&quot;laneName&quot;) <em>private val </em>_laneName: String?,<br>    @SerializedName(&quot;district&quot;) <em>private val </em>_district: String?,<br>    @SerializedName(&quot;state&quot;) <em>private val </em>_state: String?,<br>    @SerializedName(&quot;pinCode&quot;) <em>private val </em>_pinCode: Long?,<br>) {<br>    <em>val </em>laneName<br>        <em>get</em>() = _laneName ?: &quot;default&quot;<br>    <em>val </em>shopNumber<br>        <em>get</em>() = _shopNumber ?: 0<br>    <em>val </em>district<br>        <em>get</em>() = _district ?: &quot;default&quot;<br>    <em>val </em>state<br>        <em>get</em>() = _state ?: &quot;default&quot;<br>    <em>val </em>pinCode<br>        <em>get</em>() = _pinCode ?: 0<br>}</pre><p>Here, we are allowing GSON to store null values in the properties while parsing, but we have made constructor properties private hence we cannot access those null values to get them we need to go through the custom get() which uses elvis operator and provide us default value instead of null value.</p><blockquote><em>Null</em> value being passed as param to function.</blockquote><p>So if you try to pass null value to a non-null parm in runtime you gonna hit this exception :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NCnmorTneI7rPNWHZ5cRRQ.png" /></figure><p>To avoid this you need to always make sure you are passing non-null value as a param or you need to make param nullable in later case you have a change of getting NPE. If the param passed is nullable param always use one of the methods described in <a href="https://thekoolsk.medium.com/how-to-write-null-safe-code-with-kotlin-30f917773116">part 1</a> of this article before using that param.</p><blockquote>Global variables being declared as <em>Null</em>.</blockquote><p>I have seen it is a general practice to declare nullable variable globally, later initialise it in some function and use it somewhere else. I would recommend avoid using global variables where you can pass them inside param of the function this will further keep you away from NPE. Some times you class is dependent on another class to perform its duties in that case prefer using dependency injection you will never get NPE. In Android sometimes you see context getting <em>null </em>to avoid that make sure you always have null check before using the context this is mandatory one to avoid NPE from a <em>null</em> context. I personally do not prefer <em>lateinit </em>keyword because defined it will save you from NPE but if you try to use it before initialising it you have a bigger change of getting into this exception :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IcRMAPOOubtEOE2UzyEPvg.png" /></figure><p>Hence instead of making it <em>lateinit </em>I declare it as nullable it helps me getting compile time error if I have used it anywhere without null check. I hope this will help you to avoid NPE.</p><p>If you feel this article has contributed to improve your knowledge regarding NPE please consider hitting 👏🏻 button. Stay safe avoid NPE.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8924ef592f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to write null safe code with Kotlin?]]></title>
            <link>https://thekoolsk.medium.com/how-to-write-null-safe-code-with-kotlin-30f917773116?source=rss-99142d57c98d------2</link>
            <guid isPermaLink="false">https://medium.com/p/30f917773116</guid>
            <category><![CDATA[kotlindev]]></category>
            <category><![CDATA[kotlin-native]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-beginners]]></category>
            <dc:creator><![CDATA[Suraj Kulkarni]]></dc:creator>
            <pubDate>Mon, 18 Apr 2022 17:01:39 GMT</pubDate>
            <atom:updated>2022-04-18T17:06:10.446Z</atom:updated>
            <content:encoded><![CDATA[<p>There are many articles which explains about null safety in Kotlin, but I gonna tell you how to write null safe code and where to use which kind of null safety. Without wasting much time let’s get started.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*7bsUf5Sai-IjN7N_du8saA.jpeg" /></figure><p>NullPointerException(NPE) can be nightmare for a developer, Kotlin provides four in-build mechanisms which can help to avoid this exception.</p><ol><li>Safe call operator ?.</li><li><em>let</em> keyword</li><li>elvis operator ?:</li><li><em>lateinit</em> keyword</li></ol><p>Look at below code snippet :</p><p>Let’s see one by one how Kotlin saves us from NPE :</p><blockquote><strong><em>Safe call operator :</em></strong></blockquote><pre>1. var nullObject:String? = null</pre><pre>2. print(nullObject.length)// throws NPE.</pre><p>If any object is defined to carry <em>null,</em> means we explicitly tells Kotlin compiler that this variable is going to carry null value at some point of time in future the compiler simply will not allow us to call any method on that object. It will throw below compile time error :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dBtwGpUMv4iuLufz-tjTLg.png" /></figure><p>you can get around this by calling <strong><em>“?.” </em></strong>on the object like this :</p><pre>print(nullObject?.length)</pre><p>What this means, it means if the nullObject contains the <em>null </em>value then length function will never get called and code beyond that won’t be executed.</p><p>You might be thinking then what will be output of above code in that case. I want you to check that out by yourself here at <a href="https://pl.kotl.in/yViDuBQQf">kotlinplayground</a>.</p><blockquote><strong><em>let</em> keyword</strong></blockquote><pre>var nullObject:String? = null<br>nullObject?.let{<br> print(it.length)// throws NPE.<br>}</pre><p>let simply a lambda function, so here you can say this is an enhanced way of using safe call operator. OK! I will explain here what happens if nullObject value is <em>null</em> then the lambda won’t get executed at all and obviously the code written inside lambda will never be executed hence it becomes null safe. In that case there is no output of above code snippet. Check that <a href="https://pl.kotl.in/sRYyxNrIY">here</a>.</p><blockquote><strong>elvis operator ?:</strong></blockquote><pre>var nullObject:String? = null<br>print(nullObject?.length ?: &quot;value of nullObject is null&quot;)</pre><p>Here also you need to use safe call operator but the difference is if the value of nullObject is <em>null </em>then code after the elvis(?:) operator is executed it like writing null check :</p><pre>if(nullObject != null){ <br>  print(nullObject?.length) <br>}else{ <br>  print(&quot;value of nullObject is null&quot;) <br>}</pre><blockquote><strong><em>lateinit</em> keyword</strong></blockquote><pre>lateinit var nullObject:String<br>nullObject = &quot;Suraj&quot;<br>print(nullObject.length)</pre><p>Here you explicitly tells Kotlin compiler that right now I don’t know what is the value of nullObject variable but before I use it I will make sure two things:</p><ol><li>I will initialise the variable before I use it.</li><li>The value which I am going to save in this variable will be non-null.</li></ol><p>If you break the first commitment you will get :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A331uivdF76frQJ-jtLvzQ.png" /></figure><p>If you break the second commitment you will get :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2tYqVylFtnvRWL3g2VgfOQ.png" /></figure><p>So you will not get NPE but you will get these exceptions if betray to the Kotlin compiler 😜.</p><p>The most worst way to get around with null pointer compile time error is to use assertion operator(!!) in Kotlin. This is like telling Kotlin compiler I know this variable can be null, I know if it is null you are going to throw NPE and still I will go for it. :</p><pre>var nullObject:String? = null<br>print(nullObject!!.length)// throws NPE.</pre><p>Second part of this article is coming soon! where I will explain where to use which kind of null safety and why. Stay tuned. Stay Safe from NPE use safe operator 👊.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30f917773116" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Best Way Of Writing Network Layer.]]></title>
            <link>https://thekoolsk.medium.com/flutter-best-way-of-writing-network-layer-5fccca5371f4?source=rss-99142d57c98d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fccca5371f4</guid>
            <category><![CDATA[flutter-widget]]></category>
            <category><![CDATA[flutter-ui]]></category>
            <category><![CDATA[flutter-web]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Suraj Kulkarni]]></dc:creator>
            <pubDate>Sun, 10 Apr 2022 06:14:57 GMT</pubDate>
            <atom:updated>2022-04-10T06:14:57.657Z</atom:updated>
            <content:encoded><![CDATA[<p>Almost all the apps in the market are network dependent, network calls have become an integral part of the app development. There are many things which needs to be taken care while making an API call. It’s like a complex machine when all things come together it works fluidly. Today we gonna check how we can write the whole Network layer of a flutter app like a Pro!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ppeTAEOvDLqLYyWvrE7pkA.png" /></figure><blockquote><strong>What you will learn:</strong></blockquote><p>We will write complete network layer using <a href="https://pub.dev/packages/dio">Dio </a>package. This will include:</p><ol><li>Centralised Request/Response logging.</li><li>Request/Response interceptors.</li><li>Environment specific base URL’s.</li><li>Centralised auth management.</li><li>Centralised error handling.</li><li>Error message control from backend.</li></ol><p>We will have a bottom top approach meaning starting from model and going all the way upto API call via Dio. We will achieve this step by step :</p><ol><li>Step 1 writing data model.</li><li>Step 2 writing base endpoint class.</li><li>Step 3 writing api service.</li><li>Step 4 joining all pieces via writing network manager.</li></ol><blockquote><strong>Step 1 :</strong></blockquote><p>To write an appropriate data model we need to have a standard format of response for API success and error from our backend. For this article I am considering following response structure you may change this structure as per your need and make changes accordingly in your network layer.</p><p>For Success Response:</p><pre>{<br>  &quot;meta_data&quot;: {<br>    &quot;show_to_user&quot;: true,<br>    &quot;message&quot;: &quot;I want to get displayed&quot;,<br>    &quot;display_type_code&quot;: 2<br>  },<br>  &quot;data&quot;: {<br>    &quot;info&quot;: [],<br>    &quot;model&quot;: {},<br>    &quot;key&quot;: &quot;value&quot;<br>  }<br>}</pre><p>For Failure Response :</p><pre>{<br>  &quot;meta_data&quot;: {<br>    &quot;show_to_user&quot;: true,<br>    &quot;message&quot;: &quot;Data not found&quot;,<br>    &quot;display_type_code&quot;: 2<br>  },<br>  &quot;data&quot;: {<br>    &quot;error&quot;: {<br>      &quot;error_code&quot;: 204,<br>      &quot;error_message&quot;: &quot;Requetsed data is not found on server.&quot;<br>    }<br>  }<br>}</pre><p>First Let’s write base model, all our models have to extend this base model:</p><pre><em>abstract class </em>BaseDataModel&lt;T&gt; {<br>  ErrorModel? errorModel;<br><br>  T fromJson(Map&lt;String, <em>dynamic</em>&gt; json);<br>}</pre><p>This will ensure that all our models will have fromJson() method and error model is available.</p><p>BaseErrorModel should look something like this :</p><pre><em>class </em>ErrorModel <em>extends </em>BaseDataModel {<br>  String errorMessage;<br>  int errorCode;<br><br>  ErrorModel({<em>this</em>.errorMessage = &quot;something went wrong&quot;, <em>this</em>.errorCode = 404});<br><br>  @override<br>  fromJson(Map&lt;String, <em>dynamic</em>&gt; json) {<br>    <em>return </em>ErrorModel(<br>      errorCode: json[&quot;error_code&quot;],<br>      errorMessage: json[&quot;error_message&quot;],<br>    );<br>  }<br>}</pre><blockquote><strong>Step 2:</strong></blockquote><p>Our BaseEndpoint will look something like this, all our endpoints have to extend this endpoint class :</p><pre><em>import </em>&#39;dart:io&#39;;<br><em>import </em>&#39;base_env.dart&#39;;<br><br><em>abstract class </em>BaseEndpoint {<br>  BaseEndpoint(<em>this</em>.endpoint, {<em>this</em>.params = <em>const </em>{}});<br><br>  <em>final </em>String endpoint;<br>  <em>final </em>Map&lt;String, <em>dynamic</em>&gt; params;<br><br>  Future&lt;Map&lt;String, String&gt;&gt; <em>get </em>headers <em>async </em>{<br>    <em>var </em>accessToken = &quot;\$2b\$10\$zN92ZQrV9.NNb9UQw9Q6fOUA80gV5/EmcrQIqEuYtc2uXcstMy..u&quot;;<br>    <em>//Add other common headers param which you want to send to all APIs. Like device ID, app version, package name etc.<br><br>    return </em>{<br>      <em>if </em>(accessToken != <em>null</em>) &quot;secret-key&quot;: accessToken,<br>      &quot;timezone&quot;: DateTime.now().timeZoneOffset.toString().split(&#39;.&#39;).first,<br>      &quot;device-type&quot;: Platform.<em>isAndroid </em>? &quot;android&quot; : &quot;iOS&quot;,<br>      &quot;Content-Type&quot;: &quot;application/json&quot;,<br>      &quot;timestamp&quot;: DateTime.now().millisecondsSinceEpoch.toString()<br>    };<br>  }<br><br>  <em>void </em>addParams(Map&lt;String, <em>dynamic</em>&gt; params) {<br>    <em>this</em>.params.addAll(params);<br>  }<br><br>  String buildPathWith(BaseEnvironment env) {<br>    <em>return </em>env.baseURL() + &#39;/&#39; + endpoint;<br>  }<br>}</pre><p>This will ensure that we send mandatory header params to each and every API. Here I have hard-coded API token but you should always pull that from local storage.</p><p>Feature Endpoint class will look something like this :</p><pre><em>import </em>&#39;package:network_layer_pro/base/base_endpoint.dart&#39;;<br><em>import </em>&#39;package:network_layer_pro/base/endpoints.dart&#39;;<br><br><em>class </em>FeatureEndpoint <em>extends </em>BaseEndpoint {<br>  <em>final </em>Map&lt;String, <em>dynamic</em>&gt; param;<br><br>  FeatureEndpoint(<em>this</em>.param) : <em>super</em>(Endpoints.<em>feature</em>, params: param);<br>}</pre><blockquote><strong>Step 3:</strong></blockquote><p>Let’s write API contract :</p><pre><em>import </em>&#39;base_response.dart&#39;;<br><br><em>abstract class </em>BaseAPIService {<br>  Future&lt;BaseResponse&gt; get(String url, Map&lt;String, String&gt; headers, Map&lt;String, <em>dynamic</em>&gt; params);<br><br>  Future&lt;BaseResponse&gt; post(String url, Map&lt;String, String&gt; headers, Map&lt;String, <em>dynamic</em>&gt; params);<br><br>  Future&lt;BaseResponse&gt; put(String url, Map&lt;String, String&gt; headers, Map&lt;String, <em>dynamic</em>&gt; params);<br><br>  Future&lt;BaseResponse&gt; delete(String url, Map&lt;String, String&gt; headers, Map&lt;String, <em>dynamic</em>&gt; params);<br>}</pre><p>It’s implementation :</p><pre><em>import </em>&#39;dart:convert&#39;;<br><em>import </em>&#39;dart:core&#39;;<br><em>import </em>&#39;dart:io&#39;;<br><br><em>import </em>&#39;package:dio/dio.dart&#39;;<br><em>import </em>&#39;package:network_layer_pro/base/base_api_service.dart&#39;;<br><br><em>import </em>&#39;base_log.dart&#39;;<br><em>import </em>&#39;base_response.dart&#39;;<br><br><em>enum </em>REQUEST_METHOD { POST, GET, DELETE, PUT }<br><br><em>class </em>DioAPIService <em>extends </em>BaseAPIService {<br>  <em>late </em>Dio _dio;<br><br>  DioAPIService() {<br>    <em>var </em>options = BaseOptions(<br>      connectTimeout: 5000,<br>      receiveTimeout: 3000,<br>      sendTimeout: 1000,<br>    );<br>    _dio = Dio(options);<br>    _dio.interceptors.add(InterceptorsWrapper(onRequest: (options, handler) <em>async </em>{<br>      logRequest(options.path, options.headers, options.method == &quot;GET&quot; ? options.queryParameters : options.data, options.method);<br>      handler.next(options);<br>    }, onResponse: (_, handler) <em>async </em>{<br>      logResponse(_);<br>      handler.next(_);<br>    }, onError: (_, handler) <em>async </em>{<br>      handler.next(_);<br>    }));<br>  }<br><br>  @override<br>  Future&lt;BaseResponse&gt; delete(String url, Map&lt;String, String&gt; headers, Map&lt;String, <em>dynamic</em>&gt; params) <em>async </em>{<br>    <em>var </em>response = <em>await </em>_dio<br>        .delete(url, queryParameters: params, options: Options(headers: headers, validateStatus: (status) =&gt; isValidResponse(status)))<br>        .onError((error, stackTrace) <em>async </em>{<br>      <em>await </em>logOnFirebase(error ?? &quot;&quot;, stackTrace);<br>      <em>return </em>Response(<br>        requestOptions: RequestOptions(path: &#39;&#39;),<br>        data: getErrorResponse(),<br>        statusCode: HttpStatus.<em>requestTimeout</em>,<br>        statusMessage: &quot;Timeout&quot;,<br>      );<br>    });<br>    <em>return </em>convertResponse(response);<br>  }<br><br>  @override<br>  Future&lt;BaseResponse&gt; get(String url, Map&lt;String, String&gt; headers, Map&lt;String, <em>dynamic</em>&gt; params) <em>async </em>{<br>    <em>var </em>response = <em>await </em>_dio<br>        .get(url, queryParameters: params, options: Options(headers: headers, validateStatus: (status) =&gt; isValidResponse(status)))<br>        .onError((error, stackTrace) <em>async </em>{<br>      <em>await </em>logOnFirebase(error ?? &quot;&quot;, stackTrace);<br>      <em>return </em>Response(<br>        requestOptions: RequestOptions(path: &#39;&#39;),<br>        data: getErrorResponse(),<br>        statusCode: HttpStatus.<em>requestTimeout</em>,<br>        statusMessage: &quot;Timeout&quot;,<br>      );<br>    });<br>    <em>return </em>convertResponse(response);<br>  }<br><br>  @override<br>  Future&lt;BaseResponse&gt; post(String url, Map&lt;String, String&gt; headers, Map&lt;String, <em>dynamic</em>&gt; params) <em>async </em>{<br>    <em>var </em>response = <em>await </em>_dio<br>        .post(url, data: params, options: Options(headers: headers, validateStatus: (status) =&gt; isValidResponse(status)))<br>        .onError((error, stackTrace) <em>async </em>{<br>      <em>await </em>logOnFirebase(error ?? &quot;&quot;, stackTrace);<br>      <em>return </em>Response(<br>        requestOptions: RequestOptions(path: &#39;&#39;),<br>        data: getErrorResponse(),<br>        statusCode: HttpStatus.<em>requestTimeout</em>,<br>        statusMessage: &quot;Timeout&quot;,<br>      );<br>    });<br>    <em>return </em>convertResponse(response);<br>  }<br><br>  @override<br>  Future&lt;BaseResponse&gt; put(String url, Map&lt;String, String&gt; headers, Map&lt;String, <em>dynamic</em>&gt; params) <em>async </em>{<br>    <em>var </em>response = <em>await </em>_dio<br>        .put(url, data: params, options: Options(headers: headers, validateStatus: (status) =&gt; isValidResponse(status)))<br>        .onError((error, stackTrace) <em>async </em>{<br>      <em>await </em>logOnFirebase(error ?? &quot;&quot;, stackTrace);<br>      <em>return </em>Response(<br>        requestOptions: RequestOptions(path: &#39;&#39;),<br>        data: getErrorResponse(),<br>        statusCode: HttpStatus.<em>requestTimeout</em>,<br>        statusMessage: &quot;Timeout&quot;,<br>      );<br>    });<br>    <em>return </em>convertResponse(response);<br>  }<br><br>  bool isValidResponse(int? status) =&gt; status! &lt; 500 &amp;&amp; status &gt;= 1;<br><br>  BaseResponse convertResponse(Response response) {<br>    <em>switch </em>(response.statusCode) {<br>      <em>case </em>401:<br>        <em>return </em>BaseResponse(response.data[&quot;data&quot;], parseMetaData(response.data[&quot;meta_data&quot;]), response.statusCode);<br>      <em>case </em>408:<br>        <em>return </em>BaseResponse(response.data[&quot;data&quot;], parseMetaData(response.data[&quot;meta_data&quot;]), response.statusCode);<br>      <em>case </em>200:<br>        <em>return </em>BaseResponse(response.data[&quot;data&quot;], parseMetaData(response.data[&quot;meta_data&quot;]), response.statusCode);<br>      <em>case </em>403:<br>        <em>return </em>BaseResponse(response.data[&quot;data&quot;], parseMetaData(response.data[&quot;meta_data&quot;]), response.statusCode);<br>      <em>default</em>:<br>        <em>//TODO: add other clauses here as per your requirement.<br>        return </em>BaseResponse(response.data[&quot;data&quot;], parseMetaData(response.data[&quot;meta_data&quot;]), response.statusCode);<br>    }<br>  }<br><br>  <em>void </em>logRequest(String url, Map&lt;String, <em>dynamic</em>&gt; headers, Map&lt;String, <em>dynamic</em>&gt; params, String method) {<br>    fLog(&quot;NETWORK_CALL : RequestUrl &quot; + url);<br>    fLog(&quot;NETWORK_CALL : RequestMethod &quot; + method);<br>    fLog(&quot;NETWORK_CALL : RequestHeader &quot; + headers.toString());<br>    fLog(&quot;NETWORK_CALL : RequestParams &quot; + json.encode(params));<br>  }<br><br>  <em>void </em>logFormRequest(String url, Map&lt;String, String&gt; headers, FormData params, String method) {<br>    fLog(&quot;NETWORK_CALL : RequestUrl &quot; + url);<br>    fLog(&quot;NETWORK_CALL : RequestMethod &quot; + method);<br>    fLog(&quot;NETWORK_CALL : RequestHeader &quot; + headers.toString());<br>    fLog(&quot;NETWORK_CALL : RequestParams &quot; + params.toString());<br>  }<br><br>  <em>void </em>logResponse(Response response) {<br>    fLog(&quot;NETWORK_CALL : StatusCode &quot; + response.statusCode.toString());<br>    fLog(&quot;NETWORK_CALL : StatusMessage &quot; + response.statusMessage.toString());<br>    fLog(&quot;NETWORK_CALL : ResponseHeader &quot; + response.headers.map.toString());<br>    fLog(&quot;NETWORK_CALL : Data &quot; + json.encode(response.data));<br>  }<br><br>  MetaData parseMetaData(Map&lt;String, <em>dynamic</em>&gt; metaData) {<br>    <em>return </em>MetaData(<br>      metaData[&quot;show_to_user&quot;],<br>      metaData[&quot;message&quot;],<br>      metaData[&quot;display_type_code&quot;],<br>    );<br>  }<br><br>  Future&lt;<em>void</em>&gt; logOnFirebase(Object error, StackTrace trace) <em>async </em>{<br>    <em>try </em>{<br>      logFirebaseError(error, trace, module: &quot;network&quot;);<br>    } <em>catch </em>(e) {<br>      logFirebaseError(error, trace, module: &quot;networkCatch&quot;);<br>    }<br>  }<br><br>  Map getErrorResponse() {<br>    <em>return </em>{<br>      &quot;data&quot;: {<br>        &quot;error&quot;: {<br>          &quot;error_code&quot;: 504,<br>          &quot;error_message&quot;: &quot;Something went wrong&quot;,<br>        }<br>      },<br>      &quot;meta_data&quot;: {<br>        &quot;show_to_user&quot;: <em>true</em>,<br>        &quot;message&quot;: &quot;Something went wrong&quot;,<br>        &quot;display_type_code&quot;: 1,<br>      }<br>    };<br>  }<br>}</pre><blockquote><strong>Step 4:</strong></blockquote><p>Finally our Network manager :</p><pre><em>import </em>&#39;package:network_layer_pro/base/base_api_service.dart&#39;;<br><em>import </em>&#39;package:network_layer_pro/base/base_endpoint.dart&#39;;<br><em>import </em>&#39;package:network_layer_pro/base/base_exception.dart&#39;;<br><em>import </em>&#39;access_token_Model.dart&#39;;<br><em>import </em>&#39;base_env.dart&#39;;<br><em>import </em>&#39;base_log.dart&#39;;<br><em>import </em>&#39;base_model.dart&#39;;<br><em>import </em>&#39;base_response.dart&#39;;<br><em>import </em>&#39;dio_api_service.dart&#39;;<br><em>import </em>&#39;new_access_token.dart&#39;;<br><br><em>class </em>NetworkManager {<br>  bool _isFreshAccessTokenRequested = <em>false</em>;<br><br>  <em>//This should be dynamic, but this not in scope of this article we will see this in some other article<br>  static final </em>BaseEnvironment <em>_currentEnvironment </em>= BaseEnvironment();<br><br>  <em>final </em>BaseAPIService _apiService;<br><br>  NetworkManager(<em>this</em>._apiService);<br><br>  BaseEnvironment <em>get </em>currentEnvironment =&gt; <em>_currentEnvironment</em>;<br><br>  Future&lt;R&gt; get&lt;R, T <em>extends </em>BaseDataModel&gt;(BaseEndpoint endpoint, T parseModel) <em>async </em>{<br>    <em>var </em>response = <em>await </em>_apiService.get(endpoint.buildPathWith(<em>_currentEnvironment</em>), <em>await </em>endpoint.headers, endpoint.params);<br>    <em>return </em>_parseResponse&lt;R, T&gt;(response, endpoint, parseModel, REQUEST_METHOD.GET);<br>  }<br><br>  Future&lt;R&gt; post&lt;R, T <em>extends </em>BaseDataModel&gt;(BaseEndpoint endpoint, T parseModel) <em>async </em>{<br>    <em>var </em>response = <em>await </em>_apiService.post(endpoint.buildPathWith(<em>_currentEnvironment</em>), <em>await </em>endpoint.headers, endpoint.params);<br>    <em>return </em>_parseResponse&lt;R, T&gt;(response, endpoint, parseModel, REQUEST_METHOD.POST);<br>  }<br><br>  Future&lt;R&gt; put&lt;R, T <em>extends </em>BaseDataModel&gt;(BaseEndpoint endpoint, T parseModel) <em>async </em>{<br>    <em>var </em>response = <em>await </em>_apiService.put(endpoint.buildPathWith(<em>_currentEnvironment</em>), <em>await </em>endpoint.headers, endpoint.params);<br>    <em>return </em>_parseResponse&lt;R, T&gt;(response, endpoint, parseModel, REQUEST_METHOD.POST);<br>  }<br><br>  Future&lt;R&gt; delete&lt;R, T <em>extends </em>BaseDataModel&gt;(BaseEndpoint endpoint, T parseModel) <em>async </em>{<br>    <em>var </em>response = <em>await </em>_apiService.delete(endpoint.buildPathWith(<em>_currentEnvironment</em>), <em>await </em>endpoint.headers, endpoint.params);<br>    <em>return </em>_parseResponse&lt;R, T&gt;(response, endpoint, parseModel, REQUEST_METHOD.DELETE);<br>  }<br><br>  Future&lt;R&gt; _parseResponse&lt;R, T <em>extends </em>BaseDataModel&gt;(BaseResponse response, BaseEndpoint endpoint, T parseModel, REQUEST_METHOD method) <em>async </em>{<br>    <em>//TODO:Dismiss your loader here like this:<br>    //await EasyLoading.dismiss();<br>    </em>_handleDisplayToUser(response.metaData);<br>    <em>if </em>(response.httpStatusCode! &gt;= 1 &amp;&amp; response.httpStatusCode! &lt;= 300) {<br>      <em>return </em>_parseModel&lt;R, T&gt;(response.data, parseModel);<br>    } <em>else if </em>(response.httpStatusCode! == 401) {<br>      <em>if </em>(!_isFreshAccessTokenRequested) {<br>        <em>return </em>handleUnAuthResponse(response, endpoint, method, parseModel);<br>      } <em>else </em>{<br>        fLog(&#39;Unauthorised access both tokens are expired logging out user.&#39;);<br>        logoutUser();<br>        <em>throw </em>UserUnAuthException(&quot;Unauthorised Access&quot;);<br>      }<br>    } <em>else if </em>(response.httpStatusCode! == 403) {<br>      fLog(&#39;User Logged into another device&#39;);<br>      logoutUser();<br>      <em>throw </em>UserUnAuthException(&quot;Unauthorised Access&quot;);<br>    } <em>else </em>{<br>      <em>throw </em>ServerException(&quot;Something terribly went wrong&quot;);<br>    }<br>  }<br><br>  Future&lt;R&gt; _parseModel&lt;R, T <em>extends </em>BaseDataModel&gt;(<em>dynamic </em>responseBody, T model) <em>async </em>{<br>    <em>if </em>(responseBody <em>is </em>List) {<br>      <em>return </em>responseBody.map((data) =&gt; model.fromJson(data)).cast&lt;T&gt;().toList() <em>as </em>R;<br>    } <em>else </em>{<br>      <em>return </em>model.fromJson(responseBody[&#39;data&#39;][&#39;result&#39;]) <em>as </em>R;<br>    }<br>  }<br><br>  Future&lt;R&gt; handleUnAuthResponse&lt;R, T <em>extends </em>BaseDataModel&gt;(<br>      BaseResponse response, BaseEndpoint endpoint, REQUEST_METHOD method, T parseModel) <em>async </em>{<br>    _isFreshAccessTokenRequested = <em>true</em>;<br>    String? newAccessToken = <em>await </em>requestFreshAccessToken();<br>    <em>return </em>handleNewAccessTokenResponse(newAccessToken, endpoint, method, parseModel);<br>  }<br><br>  Future&lt;String&gt; requestFreshAccessToken() <em>async </em>{<br>    <em>//TODO: Pull Refresh toke from local storage<br>    var </em>refresh = {&quot;refresh&quot;: &quot;&quot;};<br>    <em>var </em>getNewAccessTokenEndPoint = GetNewAccessTokenEndPoint(refresh);<br>    <em>try </em>{<br>      <em>//TODO : Request new token something like this :<br>      return await </em>post(getNewAccessTokenEndPoint, AccessTokenModel());<br>    } <em>on </em>Exception <em>catch </em>(exception) {<br>      fLog(exception.toString());<br>      logoutUser();<br>      <em>throw </em>UserUnAuthException(&quot;Unauthorised Access&quot;);<br>    }<br>  }<br><br>  Future&lt;R&gt; handleNewAccessTokenResponse&lt;R, T <em>extends </em>BaseDataModel&gt;(<br>      String? response, BaseEndpoint endpoint, REQUEST_METHOD method, T parseModel) <em>async </em>{<br>    <em>try </em>{<br>      <em>if </em>(response != <em>null</em>) {<br>        <em>return </em>saveAndSendPreviousRequest(endpoint, method, parseModel, response);<br>      } <em>else </em>{<br>        <em>return </em>logoutUser();<br>      }<br>    } <em>on </em>Exception <em>catch </em>(e) {<br>      fLog(e.toString());<br>      <em>throw </em>UserUnAuthException(&quot;Unauthorised Access&quot;);<br>    }<br>  }<br><br>  Future&lt;R&gt; saveAndSendPreviousRequest&lt;R, T <em>extends </em>BaseDataModel&gt;(<br>      BaseEndpoint endpoint, REQUEST_METHOD method, T parseModel, String response) <em>async </em>{<br>    <em>//TODO: Save new access token to local storage here.<br>    </em>_isFreshAccessTokenRequested = <em>false</em>;<br>    <em>switch </em>(method) {<br>      <em>case </em>REQUEST_METHOD.POST:<br>        <em>return await </em>post(endpoint, parseModel);<br>      <em>case </em>REQUEST_METHOD.GET:<br>        <em>return await </em>get(endpoint, parseModel);<br>      <em>case </em>REQUEST_METHOD.DELETE:<br>        <em>return await </em>delete(endpoint, parseModel);<br>      <em>case </em>REQUEST_METHOD.PUT:<br>        <em>return await </em>put(endpoint, parseModel);<br>    }<br>  }<br><br>  Future&lt;R&gt; logoutUser&lt;R <em>extends </em>BaseDataModel&gt;() {<br>    fLog(&#39;Unauthorised request logging out user&#39;);<br>    <em>//TODO: Perform logout activities.<br>    throw </em>UserUnAuthException(&quot;Unauthorised Access&quot;);<br>  }<br><br>  <em>void </em>_handleDisplayToUser(MetaData metaData) {<br>    <em>if </em>(metaData.showToUser) {<br>      <em>switch </em>(metaData.displayMethod) {<br>        <em>case </em>1:<br>          {<br>            <em>//TODO:Show toast message<br>            break</em>;<br>          }<br>        <em>case </em>2:<br>          {<br>            <em>//TODO:Show dialog box<br>            break</em>;<br>          }<br>        <em>case </em>3:<br>          {<br>            <em>//TODO:Show snackbar<br>            break</em>;<br>          }<br>        <em>default</em>:<br>          {<br>            <em>//TODO:Show toast<br>            break</em>;<br>          }<br>      }<br>    }<br>  }<br>}</pre><p>Here you can see we have control from our backend by which means the message should be displayed to the user. We have handled UnAuth scenario only in once class. Complete code can be found on <a href="https://github.com/the-kool-sk/FlutterNetworkLayer">github</a>.</p><p>Any queries, questions comment below, I will be happy to answer them.</p><p>This may not be the perfect solution for your use-case but this should work for most of the problems out there.</p><p>Relax you are a Pro now! If you gain some knowledge from this article give me start 🌟🌟🌟 on <a href="https://github.com/the-kool-sk/FlutterNetworkLayer"><strong>gihub</strong></a> follow me on <a href="https://twitter.com/thekoolsk"><strong>Twitter</strong></a> to get more such updates.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FS6TEoUBJuGfQCoGl8l%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FS6TEoUBJuGfQCoGl8l%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FS6TEoUBJuGfQCoGl8l%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/2caead87986464bbff21e5cdf6ef3213/href">https://medium.com/media/2caead87986464bbff21e5cdf6ef3213/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fccca5371f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to prevent multiple clicks in flutter?]]></title>
            <link>https://thekoolsk.medium.com/how-to-prevent-multiple-clicks-in-flutter-fbc71a562b2c?source=rss-99142d57c98d------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbc71a562b2c</guid>
            <category><![CDATA[issues]]></category>
            <category><![CDATA[flutter-widget]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter-ui]]></category>
            <dc:creator><![CDATA[Suraj Kulkarni]]></dc:creator>
            <pubDate>Fri, 01 Apr 2022 18:33:02 GMT</pubDate>
            <atom:updated>2022-04-02T10:32:42.062Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>Problem</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/169/1*I-uy5O-IGyRF9tAoKzbGHw.gif" /></figure><p>Let’s discuss the problem first, whenever you use “onPressed” of a MaterialButton or “onTap” of a GestureDetector you might have faced this. Upon clicking on a clickable widget the callback gets called two times just because user has mistakenly clicked it two times. And the result is you ended up calling your function two times. Things get worse when you send a network call on click on one such widget, that call gets triggered multiple times and you messed up with the whole system. Another example of such a problem is navigation, upon clicking on a widget you expect to navigate to some particular page but because of this multiple click issue you end up showing that page two times. When user comes back from the page he sees the same page again which completely destroys the user experience. Here is one such example :</p><blockquote><strong>Solution</strong></blockquote><p>So I am gonna provide two solutions one is generic where you write a wrapper for all your clickable widgets and another one where you implemet it by your own.</p><p>#1</p><pre><em>import </em>&#39;dart:async&#39;;<br><br><em>import </em>&#39;package:flutter/material.dart&#39;;<br><br><em>typedef </em>VoidCallback = <em>void </em>Function();<br><br><em>class </em>SingleTapDetector <em>extends </em>StatelessWidget {<br>  <em>final </em>Widget child;<br><br>  SingleTapDetector({<br>    Key? key,<br>    <em>required this</em>.child,<br>    <em>required this</em>.onButtonPressed,<br>    <em>this</em>.interval = 1000,<br>  }) : <em>super</em>(key: key);<br>  int interval;<br>  <em>final </em>VoidCallback onButtonPressed;<br>  <em>var </em>isClicked = <em>false</em>;<br>  <em>late </em>Timer _timer;<br><br>  _startTimer() {<br>    _timer = Timer(Duration(milliseconds: interval), () =&gt; isClicked = <em>false</em>);<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    <em>return </em>GestureDetector(<br>      onTap: () {<br>        <em>if </em>(isClicked == <em>false</em>) {<br>          _startTimer();<br>          onButtonPressed();<br>          isClicked = <em>true</em>;<br>        }<br>      },<br>      child: child,<br>    );<br>  }<br>}</pre><p>You can use this wrapper it takes in two mandatory parameters and one optional parameter. “onButtonPressed” this is same as your “onTap” and “onPressed”, “interval” this is the time for which you want to disable the button after first click. After this time interval the button will again start accepting clicks.</p><p>#2</p><p>Second solution is just your own implementation of above wrapper. First declare two variables</p><pre><em>var </em>isClicked = <em>false</em>;<br><em>late </em>Timer _timer;</pre><p>Then add below code snippet in your on tap</p><pre><em>if </em>(isClicked == <em>false</em>) {<br>    _startTimer();<br>    isClicked = <em>true</em>;<br>    // Your other code which you want to execute on click. <br>}</pre><p>Finally write timer</p><pre>_startTimer() {<br>    _timer = Timer(Duration(milliseconds: 1000), () =&gt; isClicked = <em>false</em>);</pre><pre>//After this particular time the value of flag will toggle.</pre><p><a href="https://github.com/the-kool-sk/flutter_prevent_multiple_clicks/blob/main/single_tap_detector.dart">Github link</a></p><p>Then sit back and enjoy your coffee. Thank me later!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FxThtakPUrqAuOeqVZ6%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FxThtakPUrqAuOeqVZ6%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FxThtakPUrqAuOeqVZ6%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="580" frameborder="0" scrolling="no"><a href="https://medium.com/media/f80ceff3546fd31cadaf20783d64484c/href">https://medium.com/media/f80ceff3546fd31cadaf20783d64484c/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbc71a562b2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Secured shared preferences]]></title>
            <link>https://thekoolsk.medium.com/flutter-secured-shared-preferences-feb0e30272bf?source=rss-99142d57c98d------2</link>
            <guid isPermaLink="false">https://medium.com/p/feb0e30272bf</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[encryption]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[storage]]></category>
            <dc:creator><![CDATA[Suraj Kulkarni]]></dc:creator>
            <pubDate>Wed, 30 Mar 2022 02:07:43 GMT</pubDate>
            <atom:updated>2022-04-01T16:27:00.564Z</atom:updated>
            <content:encoded><![CDATA[<h3>Flutter Secure shared preferences</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*5KJ5hWWLIQXRwKYbJRIGwQ.jpeg" /></figure><p>If you are concern about your users data security on flutter this is for you. If you are someone like me who is stuck while finding a solution to securely save key-value pairs in local mobile storage this is for you. <strong>secure_shared_preferences </strong>can be a saviour for you. Let me introduce you to this amazing package available on pub.dev.</p><p>There are packages available on flutter which can encrypt data and there are packages which can save your data to local storage, hmm… but there is non if you want to do both and if there is one then its very difficult to use and not optimised. Let us see some of them :</p><p>shared_preferences : No encryption</p><p>encrypted_shared_preferences : Only string data type is supported, not encrypting keys and not so secure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*JG7AFKS_NF6Sa9GQFNreWg.gif" /></figure><p><strong>secure_shared_preferences </strong>uses master key to encrypt your data and generates 2 keys from the master key one for key encryption and one for value encryption. It saves master key to super secure place in users device. Keystore in android and Keychain in iOS. Internally package uses AES-CBC 128 encryption to encrypt keys and values.</p><blockquote>Features :</blockquote><ul><li>You have an option to by-pass encryption just by passing a bool.</li><li>Supports String, int, bool, double, map and List&lt;String&gt;.</li><li>Uses advance AES-CBC-128 algorithm for encryption.</li><li>Encrypts both key and value.</li><li>Integration unit tests available <a href="https://github.com/the-kool-sk/secure_shared_preferences/blob/master/example/integration_test/app_test.dart">here</a></li></ul><blockquote>How do I use it :</blockquote><pre><strong>To Save data :</strong></pre><pre>var pref = await SecureSharedPref.getInstance();<br>    await pref.putString(&quot;StringEncrypted&quot;, &quot;This is my first string test&quot;,isEncrypted: true);<br>    await pref.putInt(&quot;key&quot;, 100, isEncrypted: true);<br>    await pref.putMap(&quot;mapKey&quot;, {&quot;Hello&quot;:true}, isEncrypted: true);<br>    await pref.putDouble(&quot;doubleKey&quot;, 20.32, isEncrypted: true);<br>    await pref.putBool(&quot;boolKey&quot;, true,isEncrypted:  true);<br>    await pref.putStringList(&quot;listKey&quot;, [&quot;S&quot;,&quot;K&quot;], isEncrypted: true);</pre><pre><br><strong>To Fetch data :</strong></pre><pre>var pref = await SecureSharedPref.getInstance();<br>    await pref.getString(&quot;StringEncrypted&quot;, isEncrypted: true);<br>    await pref.getInt(&quot;key&quot;, isEncrypted: true);<br>    await pref.getMap(&quot;mapKey&quot;, isEncrypted: true);<br>    await pref.getDouble(&quot;doubleKey&quot;, isEncrypted: true);<br>    await pref.getBool(&quot;boolKey&quot;,isEncrypted: true);<br>    await pref.getStringList(&quot;listKey&quot;, isEncrypted: true);</pre><pre>The second parameter here is wheather you want encryption or not. I</pre><pre>You are done!</pre><blockquote>Encryption Flowchart :</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FChl1DjLpsHCuJG4_KPmqA.png" /></figure><p>Here are the links : <a href="https://pub.dev/packages/secure_shared_preferences">pub.dev</a>. <a href="https://github.com/the-kool-sk/secure_shared_preferences">github</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*ZLronSWbmj4IwGoWepecHQ.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=feb0e30272bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>