<?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 Muhammed Shabeer on Medium]]></title>
        <description><![CDATA[Stories by Muhammed Shabeer on Medium]]></description>
        <link>https://medium.com/@muhmmdshabeer?source=rss-dc9ac9b74141------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KSKK6nNY3VIUTQEY8slIXA.jpeg</url>
            <title>Stories by Muhammed Shabeer on Medium</title>
            <link>https://medium.com/@muhmmdshabeer?source=rss-dc9ac9b74141------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 04:07:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@muhmmdshabeer/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[Flutter Localization with ARB and Context Extensions]]></title>
            <link>https://medium.com/@muhmmdshabeer/stop-hardcoding-strings-in-flutter-build-a-production-localization-system-with-arb-and-context-04d238aab7f1?source=rss-dc9ac9b74141------2</link>
            <guid isPermaLink="false">https://medium.com/p/04d238aab7f1</guid>
            <dc:creator><![CDATA[Muhammed Shabeer]]></dc:creator>
            <pubDate>Wed, 17 Jun 2026 05:32:33 GMT</pubDate>
            <atom:updated>2026-06-17T05:34:37.667Z</atom:updated>
            <content:encoded><![CDATA[<p>A step-by-step Flutter localization setup using ARB files, generated strings, multi-language support, placeholders, plurals, and clean widget access.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*KPj5PGa2_LNU8WrHN3jSOA.gif" /></figure><p>Hardcoded strings are easy when an app is small.</p><pre>Text(&#39;Create account&#39;)<br>Text(&#39;Please enter a valid email address&#39;)<br>Text(&#39;No reports yet&#39;)</pre><p>But as soon as the app grows, hardcoded strings become technical debt.</p><p>You start seeing the same labels repeated across screens. Error messages are inconsistent. Designers update copy in one place but developers miss another place. Product wants Spanish, French, German, or Hindi support, and suddenly every widget has to be touched.</p><p>A production Flutter app should not treat UI text as random strings.</p><p>It should have a localization system.</p><h3>Why Localization Matters</h3><p>Localization is not only for apps that already support five languages.</p><p>Localization is about controlling product language from one place.</p><p>Even if your app is English-only today, UI text still appears in many places:</p><ul><li>buttons</li><li>form labels</li><li>validation messages</li><li>empty states</li><li>snack bars</li><li>dialogs</li><li>onboarding screens</li><li>paywalls</li><li>settings screens</li><li>error states</li></ul><p>If those strings are scattered across widgets, changing copy becomes slow and risky.</p><p>For example, imagine your app has this text in ten places:</p><pre>Text(&#39;Create account&#39;)</pre><p>Later the product team decides the wording should be:</p><pre>Text(&#39;Create your account&#39;)</pre><p>If the string is hardcoded, someone has to search the whole project, update every match, and hope they did not miss a dialog, test, empty state, or validation message.</p><p>If the string is centralized, the change happens once:</p><pre>&quot;createAccount&quot;: &quot;Create your account&quot;</pre><p>That is the real value.</p><h3>The Problem with Adding Static Text First</h3><p>A common mistake is saying:</p><pre>We do not need localization now.<br>Let us hardcode strings first.<br>We can localize later.</pre><p>This sounds practical, but it usually creates expensive cleanup later.</p><p>When localization is added late, you need to:</p><ul><li>find every user-facing string</li><li>decide whether each string should be translated</li><li>create keys for all of them</li><li>replace strings across many widgets</li><li>handle dynamic text that was manually concatenated</li><li>fix tests that depended on English strings</li><li>recheck every screen for layout overflow</li><li>repeat QA for forms, errors, dialogs, and empty states</li></ul><p>The app may still work, but the migration becomes noisy.</p><p>It is much easier to start with the right structure.</p><h3>Centralize App Contracts Early</h3><p>This idea is bigger than localization.</p><p>In a production Flutter app, important app contracts should not be scattered randomly.</p><p>Centralize them:</p><ul><li>strings</li><li>colors</li><li>text styles</li><li>spacing</li><li>routes</li><li>asset paths</li><li>API endpoints</li><li>analytics event names</li><li>feature flags</li></ul><p>Why?</p><p>Because centralization gives the app one source of truth.</p><pre>Colors should come from theme.<br>Routes should come from route constants.<br>Assets should come from asset constants.<br>Analytics events should come from an analytics layer.<br>User-facing strings should come from localization.</pre><p>If you are absolutely sure the app will never support multiple languages, you can still centralize strings in a simple string constants file.</p><p>But if there is even a reasonable chance the app will support localization later, start with ARB and generated localization from day one.</p><pre>Small app with no localization plan:<br>  centralize strings at minimum.</pre><pre>Production app or future multilingual app:<br>  use ARB localization from the beginning.</pre><h3>What We Are Building</h3><p>We will build a clean Flutter localization setup with:</p><p>The full demo project used for this article is available on GitHub: <a href="https://github.com/meahdev/flutter_localization_demo">github.com/meahdev/flutter_localization_demo</a>.</p><ul><li>ARB translation files</li><li>l10n.yaml configuration</li><li>generated AppLocalizations classes</li><li>context.translate extension</li><li>multiple languages</li><li>placeholders</li><li>plurals</li><li>runtime locale switching for demo/testing</li></ul><p>The architecture looks like this:</p><pre>ARB files<br>  -&gt; flutter gen-l10n<br>  -&gt; generated AppLocalizations<br>  -&gt; BuildContext extension<br>  -&gt; widgets use context.translate<br>  -&gt; MaterialApp declares delegates and supported locales</pre><h3>Step 0: Create a Real Flutter Project</h3><p>If you are starting from scratch, create a full Flutter project first.</p><pre>flutter create flutter_localization_demo<br>cd flutter_localization_demo</pre><p>This matters because a runnable Flutter app needs platform folders such as:</p><pre>android/<br>ios/<br>lib/<br>pubspec.yaml</pre><p>If you only create a lib/ folder manually, the app may analyze as Dart code but it will not run on Android or iOS.</p><h3>Why ARB?</h3><p>ARB stands for Application Resource Bundle. In Flutter, ARB files are the common way to store localizable strings.</p><p>Each language gets its own file:</p><pre>lib/app/localization/l10n/<br>  intl_en.arb<br>  intl_es.arb<br>  intl_fr.arb<br>  intl_de.arb<br>  intl_hi.arb</pre><p>The English file is usually the template. Other languages follow the same keys.</p><p>This gives you one source of truth for UI text instead of scattered strings across the app.</p><h3>Step 1: Add Dependencies</h3><p>In pubspec.yaml, add Flutter localization support.</p><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>  flutter_localizations:<br>    sdk: flutter<br>  intl: ^0.20.0</pre><pre>flutter:<br>  uses-material-design: true<br>  generate: true</pre><p>The important line is:</p><pre>generate: true</pre><p>That tells Flutter that this project uses generated localization files.</p><h3>Step 2: Configure l10n.yaml</h3><p>Create l10n.yaml at the project root.</p><pre>arb-dir: lib/app/localization/l10n<br>template-arb-file: intl_en.arb<br>output-localization-file: app_localizations.dart<br>output-class: AppLocalizations<br>output-dir: lib/app/localization/generated</pre><p>This file tells Flutter:</p><ul><li>where ARB files live</li><li>which file is the template language</li><li>what generated class should be called</li><li>where generated localization files should be written</li></ul><p>This structure scales well in large apps because localization files stay in one predictable folder.</p><h3>Step 3: Create the English ARB File</h3><p>Create intl_en.arb.</p><pre>{<br>  &quot;@@locale&quot;: &quot;en&quot;,<br>  &quot;appTitle&quot;: &quot;Localization Demo&quot;,<br>  &quot;@appTitle&quot;: {<br>    &quot;description&quot;: &quot;Title displayed in the app bar.&quot;<br>  },<br>  &quot;headline&quot;: &quot;Build multilingual Flutter apps&quot;,<br>  &quot;@headline&quot;: {<br>    &quot;description&quot;: &quot;Main screen headline.&quot;<br>  },<br>  &quot;subtitle&quot;: &quot;ARB files keep UI text organized, generated strings keep code safe, and context extensions keep widgets clean.&quot;,<br>  &quot;@subtitle&quot;: {<br>    &quot;description&quot;: &quot;Short explanation of the localization approach.&quot;<br>  },<br>  &quot;selectedLanguage&quot;: &quot;Selected language&quot;,<br>  &quot;welcomeUser&quot;: &quot;Welcome, {name}!&quot;,<br>  &quot;@welcomeUser&quot;: {<br>    &quot;description&quot;: &quot;Welcome message with the user&#39;s display name.&quot;,<br>    &quot;placeholders&quot;: {<br>      &quot;name&quot;: {<br>        &quot;type&quot;: &quot;String&quot;,<br>        &quot;example&quot;: &quot;Asha&quot;<br>      }<br>    }<br>  },<br>  &quot;itemCount&quot;: &quot;{count, plural, =0{No tasks} =1{1 task} other{{count} tasks}}&quot;,<br>  &quot;@itemCount&quot;: {<br>    &quot;description&quot;: &quot;Pluralized task count.&quot;,<br>    &quot;placeholders&quot;: {<br>      &quot;count&quot;: {<br>        &quot;type&quot;: &quot;int&quot;,<br>        &quot;example&quot;: &quot;3&quot;<br>      }<br>    }<br>  },<br>  &quot;emptyStateTitle&quot;: &quot;No reports yet&quot;,<br>  &quot;emptyStateMessage&quot;: &quot;When new reports arrive, they will appear here.&quot;,<br>  &quot;primaryAction&quot;: &quot;Create report&quot;<br>}</pre><p>There are three important ideas here.</p><p>First, every normal key becomes a generated Dart getter or method.</p><pre>&quot;appTitle&quot;: &quot;Localization Demo&quot;</pre><p>becomes:</p><pre>context.translate.appTitle</pre><p>Second, metadata keys start with @. They document the string for translators and tooling.</p><p>Third, placeholders and plurals should be defined in ARB, not manually concatenated inside widgets.</p><h3>Step 4: Add More Languages</h3><p>Every translated file should keep the same keys.</p><p>Spanish:</p><pre>{<br>  &quot;@@locale&quot;: &quot;es&quot;,<br>  &quot;appTitle&quot;: &quot;Demo de localización&quot;,<br>  &quot;headline&quot;: &quot;Crea apps Flutter multilingües&quot;,<br>  &quot;subtitle&quot;: &quot;Los archivos ARB organizan el texto, las cadenas generadas hacen el código seguro y las extensiones de contexto mantienen los widgets limpios.&quot;,<br>  &quot;selectedLanguage&quot;: &quot;Idioma seleccionado&quot;,<br>  &quot;welcomeUser&quot;: &quot;Bienvenida, {name}!&quot;,<br>  &quot;itemCount&quot;: &quot;{count, plural, =0{Sin tareas} =1{1 tarea} other{{count} tareas}}&quot;,<br>  &quot;emptyStateTitle&quot;: &quot;Aún no hay informes&quot;,<br>  &quot;emptyStateMessage&quot;: &quot;Cuando lleguen nuevos informes, aparecerán aquí.&quot;,<br>  &quot;primaryAction&quot;: &quot;Crear informe&quot;<br>}</pre><p>French:</p><pre>{<br>  &quot;@@locale&quot;: &quot;fr&quot;,<br>  &quot;appTitle&quot;: &quot;Démo de localisation&quot;,<br>  &quot;headline&quot;: &quot;Créez des apps Flutter multilingues&quot;,<br>  &quot;subtitle&quot;: &quot;Les fichiers ARB organisent le texte, les chaînes générées sécurisent le code et les extensions de contexte gardent les widgets propres.&quot;,<br>  &quot;selectedLanguage&quot;: &quot;Langue sélectionnée&quot;,<br>  &quot;welcomeUser&quot;: &quot;Bienvenue, {name} !&quot;,<br>  &quot;itemCount&quot;: &quot;{count, plural, =0{Aucune tâche} =1{1 tâche} other{{count} tâches}}&quot;,<br>  &quot;emptyStateTitle&quot;: &quot;Aucun rapport pour le moment&quot;,<br>  &quot;emptyStateMessage&quot;: &quot;Lorsque de nouveaux rapports arriveront, ils apparaîtront ici.&quot;,<br>  &quot;primaryAction&quot;: &quot;Créer un rapport&quot;<br>}</pre><p>You can add as many languages as your product supports. The important rule is simple:</p><pre>Every locale file must contain the same keys as the template file.</pre><h3>Step 5: Generate Localization Classes</h3><p>After creating or editing ARB files, generate the Dart localization classes.</p><p>First get packages:</p><pre>flutter pub get</pre><p>Then run:</p><pre>flutter gen-l10n</pre><p>Flutter generates files similar to this:</p><pre>lib/app/localization/generated/<br>  app_localizations.dart<br>  app_localizations_en.dart<br>  app_localizations_es.dart<br>  app_localizations_fr.dart<br>  app_localizations_de.dart<br>  app_localizations_hi.dart</pre><p>These files should be treated as generated output. Do not manually edit them.</p><p>The normal workflow is:</p><pre>1. Add or edit keys in intl_en.arb.<br>2. Add the same keys to every translated ARB file.<br>3. Run flutter gen-l10n.<br>4. Use the generated getters or methods in widgets.<br>5. Run analyzer and tests.</pre><p>If a generated getter does not appear, check these first:</p><ul><li>flutter: generate: true exists in pubspec.yaml</li><li>l10n.yaml points to the correct ARB folder</li><li>the ARB file contains valid JSON</li><li>all locale files use the same key names</li><li>flutter gen-l10n was run after editing ARB files</li></ul><h3>Step 6: Add a Context Extension</h3><p>Generated localization works like this:</p><pre>AppLocalizations.of(context)!.appTitle</pre><p>That is fine, but it becomes noisy when used everywhere.</p><p>Create a small BuildContext extension:</p><pre>import &#39;package:flutter/widgets.dart&#39;;</pre><pre>import &#39;generated/app_localizations.dart&#39;;</pre><pre>extension LocalizationExtension on BuildContext {<br>  AppLocalizations get translate =&gt; AppLocalizations.of(this)!;<br>}</pre><p>Now widgets can use:</p><pre>context.translate.appTitle<br>context.translate.welcomeUser(&#39;Asha&#39;)<br>context.translate.itemCount(3)</pre><p>This keeps UI code cleaner and avoids repeated calls to AppLocalizations.of(context)!.</p><h3>Step 7: Wire MaterialApp</h3><p>Your app must tell Flutter which localization delegates and locales it supports.</p><p>Add these imports where your MaterialApp is declared:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_localizations/flutter_localizations.dart&#39;;</pre><pre>import &#39;app/localization/generated/app_localizations.dart&#39;;</pre><pre>MaterialApp(<br>  supportedLocales: AppLocalizations.supportedLocales,<br>  localizationsDelegates: const [<br>    AppLocalizations.delegate,<br>    GlobalMaterialLocalizations.delegate,<br>    GlobalCupertinoLocalizations.delegate,<br>    GlobalWidgetsLocalizations.delegate,<br>  ],<br>  home: const HomeScreen(),<br>);</pre><p>The generated AppLocalizations.supportedLocales comes from your ARB files.</p><p>If you have intl_en.arb, intl_es.arb, and intl_fr.arb, Flutter knows those locales are supported.</p><p>If your app uses MaterialApp.router, the same localization properties still apply:</p><pre>MaterialApp.router(<br>  supportedLocales: AppLocalizations.supportedLocales,<br>  localizationsDelegates: const [<br>    AppLocalizations.delegate,<br>    GlobalMaterialLocalizations.delegate,<br>    GlobalCupertinoLocalizations.delegate,<br>    GlobalWidgetsLocalizations.delegate,<br>  ],<br>  routerConfig: router,<br>);</pre><h3>Step 8: Use Localized Strings in Widgets</h3><p>Here is a simple screen using generated strings.</p><pre>class DemoHomeScreen extends StatelessWidget {<br>  const DemoHomeScreen({super.key});</pre><pre>  @override<br>  Widget build(BuildContext context) {<br>    final t = context.translate;</pre><pre>    return Scaffold(<br>      appBar: AppBar(title: Text(t.appTitle)),<br>      body: ListView(<br>        padding: const EdgeInsets.all(24),<br>        children: [<br>          Text(<br>            t.headline,<br>            style: Theme.of(context).textTheme.headlineMedium,<br>          ),<br>          const SizedBox(height: 12),<br>          Text(t.subtitle),<br>          const SizedBox(height: 24),<br>          Text(t.welcomeUser(&#39;Asha&#39;)),<br>          Text(t.itemCount(3)),<br>          const SizedBox(height: 24),<br>          FilledButton(<br>            onPressed: () {},<br>            child: Text(t.primaryAction),<br>          ),<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><p>Notice that the widget does not know anything about English, Spanish, French, or Hindi.</p><p>It only knows about generated keys.</p><h3>Step 9: Add Runtime Language Switching</h3><p>Most production apps use the device locale by default. But for demos, QA, and settings screens, it is useful to switch language at runtime.</p><pre>class LocalizationDemoApp extends StatefulWidget {<br>  const LocalizationDemoApp({super.key});</pre><pre>  @override<br>  State&lt;LocalizationDemoApp&gt; createState() =&gt;<br>      _LocalizationDemoAppState();<br>}</pre><pre>class _LocalizationDemoAppState extends State&lt;LocalizationDemoApp&gt; {<br>  Locale _locale = const Locale(&#39;en&#39;);</pre><pre>  void _changeLocale(Locale locale) {<br>    setState(() =&gt; _locale = locale);<br>  }</pre><pre>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      locale: _locale,<br>      supportedLocales: AppLocalizations.supportedLocales,<br>      localizationsDelegates: const [<br>        AppLocalizations.delegate,<br>        GlobalMaterialLocalizations.delegate,<br>        GlobalCupertinoLocalizations.delegate,<br>        GlobalWidgetsLocalizations.delegate,<br>      ],<br>      home: DemoHomeScreen(<br>        selectedLocale: _locale,<br>        onLocaleChanged: _changeLocale,<br>      ),<br>    );<br>  }<br>}</pre><p>Then create a language selector.</p><pre>class LanguageSelector extends StatelessWidget {<br>  const LanguageSelector({<br>    super.key,<br>    required this.selectedLocale,<br>    required this.onLocaleChanged,<br>  });</pre><pre>  final Locale selectedLocale;<br>  final ValueChanged&lt;Locale&gt; onLocaleChanged;</pre><pre>  static const languages = &lt;String, Locale&gt;{<br>    &#39;English&#39;: Locale(&#39;en&#39;),<br>    &#39;Español&#39;: Locale(&#39;es&#39;),<br>    &#39;Français&#39;: Locale(&#39;fr&#39;),<br>    &#39;Deutsch&#39;: Locale(&#39;de&#39;),<br>    &#39;हिन्दी&#39;: Locale(&#39;hi&#39;),<br>  };</pre><pre>  @override<br>  Widget build(BuildContext context) {<br>    return DropdownButton&lt;Locale&gt;(<br>      value: selectedLocale,<br>      isExpanded: true,<br>      items: languages.entries.map((entry) {<br>        return DropdownMenuItem&lt;Locale&gt;(<br>          value: entry.value,<br>          child: Text(entry.key),<br>        );<br>      }).toList(),<br>      onChanged: (locale) {<br>        if (locale != null) onLocaleChanged(locale);<br>      },<br>    );<br>  }<br>}</pre><p>In a real app, you can store the selected locale using local storage and restore it on startup.</p><h3>Placeholders</h3><p>Never build dynamic localized strings with manual concatenation.</p><p>Avoid this:</p><pre>Text(&#39;Welcome, &#39; + name + &#39;!&#39;)</pre><p>Use placeholders instead:</p><pre>&quot;welcomeUser&quot;: &quot;Welcome, {name}!&quot;,<br>&quot;@welcomeUser&quot;: {<br>  &quot;placeholders&quot;: {<br>    &quot;name&quot;: {<br>      &quot;type&quot;: &quot;String&quot;,<br>      &quot;example&quot;: &quot;Asha&quot;<br>    }<br>  }<br>}</pre><p>Then call:</p><pre>context.translate.welcomeUser(&#39;Asha&#39;)</pre><p>This gives translators control over word order. That matters because not every language follows English sentence structure.</p><h3>Plurals</h3><p>Pluralization is another place where hardcoded strings fail.</p><p>Do not write:</p><pre>count == 1 ? &#39;1 task&#39; : &#39;$count tasks&#39;</pre><p>Use ICU plural syntax in ARB:</p><pre>&quot;itemCount&quot;: &quot;{count, plural, =0{No tasks} =1{1 task} other{{count} tasks}}&quot;</pre><p>Then call:</p><pre>context.translate.itemCount(0)<br>context.translate.itemCount(1)<br>context.translate.itemCount(5)</pre><p>Flutter generates a method that handles the correct plural form for the active locale.</p><h3>Folder Structure</h3><p>A scalable localization folder can look like this:</p><pre>lib/<br>  app/<br>    localization/<br>      generated/<br>        app_localizations.dart<br>        app_localizations_en.dart<br>        app_localizations_es.dart<br>      l10n/<br>        intl_en.arb<br>        intl_es.arb<br>        intl_fr.arb<br>      localization_extension.dart</pre><p>This keeps source translation files separate from generated Dart files.</p><h3>Run and Verify</h3><p>After wiring everything, run the full loop:</p><pre>flutter pub get<br>flutter gen-l10n<br>dart analyze<br>flutter test<br>flutter run</pre><p>Use flutter run to test the app on Android, iOS, web, or desktop depending on your environment.</p><p>If you add a new language later, the workflow is the same:</p><pre>1. Add intl_xx.arb.<br>2. Add the same keys as intl_en.arb.<br>3. Run flutter gen-l10n.<br>4. Check AppLocalizations.supportedLocales.<br>5. Run the app and verify screens manually.</pre><h3>Production Rules</h3><p>Here are useful rules for production Flutter apps:</p><ul><li>No hardcoded user-facing strings inside widgets.</li><li>Use ARB keys for labels, buttons, validation messages, empty states, dialogs, and errors.</li><li>Use placeholders for dynamic values.</li><li>Use plurals for counts.</li><li>Keep key names descriptive.</li><li>Do not manually edit generated localization files.</li><li>Run flutter gen-l10n after editing ARB files.</li><li>Use context.translate to keep widgets clean.</li><li>Test long translated text on small screens.</li><li>Ask translators to review context, not only isolated strings.</li></ul><h3>Common Mistakes</h3><h3>1. Hardcoding fallback English</h3><p>This usually happens in validation or error states.</p><pre>return &#39;Please enter a valid email&#39;;</pre><p>That should be:</p><pre>return context.translate.enterValidEmail;</pre><h3>2. Concatenating translated text</h3><pre>Text(context.translate.welcome + &#39;, &#39; + user.name)</pre><p>Use placeholders instead. Word order changes across languages.</p><h3>3. Forgetting Material localization delegates</h3><p>If you forget GlobalMaterialLocalizations.delegate, built-in widgets like date pickers, dialogs, menus, and text fields may not localize correctly.</p><h3>4. Not testing long strings</h3><p>German, French, Hindi, and many other languages can be longer than English. Make sure buttons, cards, tabs, and dialogs can handle translated text.</p><h3>5. Translating keys inconsistently</h3><p>Every ARB file should contain the same keys. Missing keys break generation or cause runtime gaps.</p><h3>Testing Checklist</h3><ul><li>Run flutter gen-l10n.</li><li>Run analyzer after generation.</li><li>Open the app in every supported language.</li><li>Check small devices.</li><li>Check large text accessibility settings.</li><li>Check forms and validation messages.</li><li>Check empty states and error states.</li><li>Check dialogs, bottom sheets, and snack bars.</li><li>Check placeholders with real values.</li><li>Check plural counts for zero, one, and many.</li></ul><h3>Conclusion</h3><p>Localization is not just translation. It is a system for managing product language across the entire app.</p><p>ARB files keep content organized. Generated localization classes make strings type-safe. Context extensions keep widgets readable. Placeholders and plurals protect you from English-only assumptions.</p><p>The biggest shift is simple:</p><pre>Do not let every widget own its own words.<br>Give the app one localization system.<br>Then let every screen speak through that system.</pre><p>That is how a Flutter app grows from hardcoded text to production-ready multi-language support.</p><p>You can explore the complete sample project here: <a href="https://github.com/meahdev/flutter_localization_demo">github.com/meahdev/flutter_localization_demo</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04d238aab7f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Scattering Firebase Analytics in Flutter: Build a Clean Event Tracking Layer Instead]]></title>
            <link>https://medium.com/@muhmmdshabeer/stop-scattering-firebase-analytics-in-flutter-build-a-clean-event-tracking-layer-instead-ea3fa69f3c44?source=rss-dc9ac9b74141------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea3fa69f3c44</guid>
            <dc:creator><![CDATA[Muhammed Shabeer]]></dc:creator>
            <pubDate>Mon, 15 Jun 2026 18:13:51 GMT</pubDate>
            <atom:updated>2026-06-15T18:13:51.654Z</atom:updated>
            <content:encoded><![CDATA[<p>A production approach to centralized analytics, event taxonomy, funnel tracking, BLoC listeners, GA4 events, and clean UI separation.</p><p>This article uses Firebase Analytics as the provider, but the architecture is not Firebase-specific. The same pattern works if your team later adds Amplitude, Mixpanel, Segment, a custom backend, or multiple analytics destinations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*CtjuAwO0UCYlfV9j_lKCkA.gif" /></figure><p>Most Flutter apps start analytics in the same way.</p><pre>FirebaseAnalytics.instance.logEvent(<br>  name: &#39;button_clicked&#39;,<br>);</pre><p>At the beginning, this feels fine.</p><p>Then the app grows.</p><p>Analytics calls begin to appear inside buttons, screens, dialogs, BLoCs, Cubits, services, bottom sheets, onboarding flows, payment flows, and error handlers. Event names become inconsistent. Parameters change between screens. Some events fire twice. Some important events never fire. Nobody fully trusts the dashboard.</p><p>That is when analytics stops being helpful and becomes noise.</p><p>In production apps, analytics should be treated like an architecture concern, not like random logging.</p><h3>The Problem</h3><p>Direct analytics calls inside UI code create several problems:</p><ul><li>event names are duplicated across files</li><li>parameters are inconsistent</li><li>business funnels become difficult to query</li><li>changing analytics providers becomes expensive</li><li>UI widgets become responsible for product reporting</li><li>events can fire multiple times during rebuilds</li><li>success, failure, cancel, restore, and dismiss states are often tracked incorrectly</li></ul><p>For example, this looks harmless:</p><pre>ElevatedButton(<br>  onPressed: () {<br>    FirebaseAnalytics.instance.logEvent(<br>      name: &#39;subscribe_clicked&#39;,<br>    );</pre><pre>    context.read&lt;SubscriptionBloc&gt;().add(<br>      BuySubscription(productId: productId),<br>    );<br>  },<br>  child: const Text(&#39;Subscribe&#39;),<br>);</pre><p>But what did this event actually mean?</p><ul><li>Did the user tap the button?</li><li>Did the native purchase sheet open?</li><li>Did the user cancel?</li><li>Did payment become pending?</li><li>Did backend verification start?</li><li>Did the purchase become active?</li><li>Did restore purchases succeed?</li></ul><p>One event cannot answer all of that.</p><h3>The Goal</h3><p>A clean analytics layer should give the team one reliable language for product behavior.</p><p>The goal is not only to send events. The goal is to answer questions:</p><ul><li>Where do users drop in signup?</li><li>Which paywall entry point converts?</li><li>Are users canceling checkout or failing verification?</li><li>Which features are actually used?</li><li>Do users complete 2FA setup?</li><li>Does an A/B test variant change conversion?</li><li>Are support and bug report flows being used?</li></ul><p>That requires a system.</p><h3>Architecture</h3><p>The clean version looks like this:</p><pre>UI / BLoC / Cubit / Service<br>        |<br>        v<br>AnalyticsService<br>        |<br>        v<br>FirebaseAnalyticsService<br>        |<br>        v<br>Firebase Analytics / GA4</pre><p>The app code should not know the Firebase event name in most places. It should call a domain method:</p><pre>analytics.logSignupOtpVerified();<br>analytics.logPurchaseCanceled(reason: &#39;user_cancel&#39;);<br>analytics.logFeatureUsed(featureName: &#39;security_check&#39;);</pre><p>That reads like product language, not vendor-specific logging.</p><h3>Central Analytics API</h3><p>Start with an abstract service. This gives the app one analytics contract.</p><pre>abstract class AnalyticsService {<br>  Future&lt;void&gt; logFeatureUsed({<br>    required String featureName,<br>    String? source,<br>  });</pre><pre>  Future&lt;void&gt; logPaywallViewed({<br>    required String source,<br>    required String surface,<br>  });</pre><pre>  Future&lt;void&gt; logCheckoutStarted({<br>    required String source,<br>    required String surface,<br>    required String planId,<br>    required String billingPeriod,<br>    required int priceUsdCents,<br>  });</pre><pre>  Future&lt;void&gt; logPurchaseCanceled({<br>    required String planId,<br>    required String source,<br>    required String cancelReason,<br>  });</pre><pre>  Future&lt;void&gt; logSubscriptionSuccess({<br>    required String planId,<br>    required int? price,<br>    required String source,<br>    String? billingPeriod,<br>    String? transactionId,<br>  });</pre><pre>  Future&lt;void&gt; logSignupEmailSubmitted();<br>  Future&lt;void&gt; logSignupOtpVerified();<br>  Future&lt;void&gt; logLoginSuccess({required String method});<br>  Future&lt;void&gt; logTwoFaSetupCompleted({required String method});<br>  Future&lt;void&gt; logFeatureSetupCompleted({<br>    required String featureName,<br>  });<br>}</pre><p>This contract can grow by product area:</p><ul><li>onboarding</li><li>login</li><li>forgot password</li><li>subscription</li><li>2FA</li><li>security features</li><li>profile and account management</li><li>feature adoption</li><li>support and bug reports</li></ul><p>The important point is that the app does not scatter raw event names everywhere.</p><h3>Firebase Implementation</h3><p>The Firebase-specific code stays in one implementation.</p><pre>class FirebaseAnalyticsService implements AnalyticsService {<br>  FirebaseAnalyticsService(this._analytics);</pre><pre>  final FirebaseAnalytics _analytics;</pre><pre>  static const int _maxReasonLength = 100;</pre><pre>  String _truncateReason(String value) {<br>    if (value.length &lt;= _maxReasonLength) return value;<br>    return value.substring(0, _maxReasonLength);<br>  }</pre><pre>  @override<br>  Future&lt;void&gt; logFeatureUsed({<br>    required String featureName,<br>    String? source,<br>  }) async {<br>    final params = &lt;String, Object&gt;{<br>      &#39;feature_name&#39;: featureName,<br>    };</pre><pre>    if (source != null &amp;&amp; source.isNotEmpty) {<br>      params[&#39;source&#39;] = source;<br>    }</pre><pre>    await _analytics.logEvent(<br>      name: &#39;feature_used&#39;,<br>      parameters: params,<br>    );<br>  }</pre><pre>  @override<br>  Future&lt;void&gt; logPurchaseCanceled({<br>    required String planId,<br>    required String source,<br>    required String cancelReason,<br>  }) async {<br>    await _analytics.logEvent(<br>      name: &#39;subscription_purchase_canceled&#39;,<br>      parameters: {<br>        &#39;plan_id&#39;: planId,<br>        &#39;source&#39;: source,<br>        &#39;cancel_reason&#39;: cancelReason,<br>      },<br>    );<br>  }</pre><pre>  @override<br>  Future&lt;void&gt; logSubscriptionFailed({<br>    required String planId,<br>    required String reason,<br>    required String source,<br>  }) async {<br>    await _analytics.logEvent(<br>      name: &#39;subscription_purchase_failed&#39;,<br>      parameters: {<br>        &#39;plan_id&#39;: planId,<br>        &#39;reason&#39;: _truncateReason(reason),<br>        &#39;source&#39;: source,<br>      },<br>    );<br>  }<br>}</pre><p>Two production details are worth noticing.</p><p>First, event names and parameter names are centralized. If the team changes subscription_purchase_failed, it changes in one place.</p><p>Second, long error messages are truncated before going to analytics. Analytics tools are not log storage. Keep parameters clean, short, and queryable.</p><h3>Dependency Injection</h3><p>Register the analytics service once in dependency injection.</p><pre>sl.registerLazySingleton&lt;AnalyticsService&gt;(<br>  () =&gt; FirebaseAnalyticsService(<br>    FirebaseAnalytics.instance,<br>  ),<br>);</pre><p>Now the app depends on AnalyticsService, not directly on Firebase.</p><pre>final analytics = sl&lt;AnalyticsService&gt;();</pre><pre>await analytics.logLoginSuccess(method: &#39;password&#39;);</pre><p>This is small, but it changes the maintainability of the whole app.</p><h3>Event Taxonomy</h3><p>An analytics layer is only useful if the team agrees on event names.</p><p>A production app should keep an event taxonomy document that defines:</p><ul><li>event name</li><li>when it fires</li><li>required parameters</li><li>allowed parameter values</li><li>which screen or state owns the event</li><li>how product teams should query it</li></ul><p>Example:</p><pre>| Event | When it fires | Parameters |<br>|---|---|---|<br>| subscription_paywall_viewed | Paywall screen or sheet mounted | source, surface |<br>| subscription_checkout_started | User taps Subscribe | source, surface, plan_id, billing_period |<br>| subscription_iap_sheet_shown | State becomes purchasing | plan_id, source |<br>| subscription_purchase_canceled | State becomes canceled | plan_id, source, cancel_reason |<br>| subscription_purchase_success | Backend verifies purchase | plan_id, price, source, transaction_id |<br>| subscription_restore_success | Restore verified | plan_id, source |</pre><p>This prevents random event naming such as:</p><pre>subscribe_clicked<br>subscriptionClicked<br>purchase_button_tap<br>iap_started<br>plan_purchase</pre><p>Those names may look similar to a developer, but in analytics dashboards they are different events.</p><h3>Event Families in a Real App</h3><p>A mature analytics layer usually grows by product area. Do not keep everything as random one-off events.</p><p>Here is a practical event family map:</p><pre>Onboarding<br>  onboarding_started<br>  onboarding_step_completed<br>  onboarding_completed</pre><pre>Signup<br>  signup_email_submitted<br>  signup_email_failed<br>  signup_otp_submitted<br>  signup_otp_verified<br>  signup_otp_failed<br>  signup_password_submitted<br>  signup_completed</pre><pre>Login<br>  login_email_submitted<br>  login_email_not_found<br>  login_password_submitted<br>  login_success<br>  login_failed<br>  social_login_started<br>  social_login_success<br>  social_login_failed</pre><pre>Forgot Password<br>  forgot_password_email_submitted<br>  forgot_password_otp_verified<br>  forgot_password_completed</pre><pre>Two-Factor Authentication<br>  two_fa_setup_started<br>  two_fa_method_selected<br>  two_fa_authenticator_verified<br>  two_fa_phone_otp_verified<br>  two_fa_setup_completed<br>  two_fa_login_verified</pre><pre>Subscription Funnel<br>  subscription_paywall_viewed<br>  subscription_plan_viewed<br>  subscription_checkout_started<br>  subscription_iap_sheet_shown<br>  subscription_purchase_success<br>  subscription_purchase_failed<br>  subscription_restore_success</pre><pre>Security Feature<br>  security_item_add_submitted<br>  security_item_added<br>  security_item_add_failed<br>  security_action_submitted<br>  security_action_completed</pre><pre>Account Management<br>  profile_updated<br>  account_setting_changed<br>  account_member_invited<br>  account_member_removed</pre><pre>Feature Adoption<br>  feature_used<br>  feature_setup_started<br>  feature_setup_completed<br>  feature_action_failed</pre><pre>Support<br>  support_contact_submitted<br>  bug_report_submitted</pre><pre>Lifecycle / Growth<br>  share<br>  user_signed_out<br>  experiment_impression</pre><p>The exact event names depend on your product, but the structure is the important part. Each feature should have its own small vocabulary, and every vocabulary should still follow the same naming rules.</p><p>This makes analytics easier to search, easier to document, and easier to query in GA4.</p><h3>Use Canonical Constants</h3><p>For important parameters, use constants instead of free-text strings.</p><pre>class SubscriptionSource {<br>  const SubscriptionSource._();</pre><pre>  static const String homeUpgradeBanner = &#39;home_upgrade_banner&#39;;<br>  static const String profileUpgradeBanner = &#39;profile_upgrade_banner&#39;;<br>  static const String featureLock = &#39;feature_lock&#39;;<br>  static const String settingsPage = &#39;settings_page&#39;;<br>  static const String onboardingScreen = &#39;onboarding_screen&#39;;</pre><pre>  static const String unknown = &#39;unknown&#39;;<br>}</pre><pre>class SubscriptionSurface {<br>  const SubscriptionSurface._();</pre><pre>  static const String plansScreen = &#39;plans_screen&#39;;<br>  static const String bottomSheet = &#39;bottom_sheet&#39;;<br>}</pre><pre>class SubscriptionCancelReason {<br>  const SubscriptionCancelReason._();</pre><pre>  static const String userCancel = &#39;user_cancel&#39;;<br>  static const String timeout = &#39;timeout&#39;;<br>}</pre><p>This matters because analytics is only useful when values are consistent.</p><p>For example, these should not all exist in your dashboard:</p><pre>profile<br>Profile<br>profile_screen<br>profile upgrade<br>profile_upgrade_banner</pre><p>Pick one vocabulary and force the codebase to use it.</p><h3>Separate User Actions from State Transitions</h3><p>This is one of the most important parts.</p><p>Some events are user actions. They should fire immediately when the user does something.</p><p>Example: user taps Subscribe.</p><pre>void onCheckoutPressed(SubscriptionPlan plan) {<br>  analytics.logCheckoutStarted(<br>    source: SubscriptionSource.profileUpgradeBanner,<br>    surface: SubscriptionSurface.bottomSheet,<br>    planId: plan.id,<br>    billingPeriod: plan.billingPeriod,<br>    priceUsdCents: plan.priceUsdCents,<br>  );</pre><pre>  context.read&lt;SubscriptionBloc&gt;().add(<br>    BuySubscription(productId: plan.storeProductId),<br>  );<br>}</pre><p>This event means “the user showed purchase intent.”</p><p>But other events should not be fired from the button. They should be fired from workflow state transitions.</p><pre>purchasing  -&gt; native IAP sheet should be visible<br>pending     -&gt; payment is waiting for confirmation<br>verifying   -&gt; backend receipt validation started<br>canceled    -&gt; user canceled or watchdog timed out<br>success     -&gt; backend confirmed premium access<br>error       -&gt; purchase or verification failed</pre><p>If you fire all of these from button handlers, your analytics will lie.</p><h3>State-Transition Analytics Listener</h3><p>For event-driven flows, a listener is cleaner than scattering analytics across every UI branch.</p><p>Here is the simplified idea:</p><pre>class SubscriptionAnalyticsListener extends StatefulWidget {<br>  const SubscriptionAnalyticsListener({<br>    super.key,<br>    required this.source,<br>    required this.surface,<br>    required this.child,<br>  });</pre><pre>  final String source;<br>  final String surface;<br>  final Widget child;</pre><pre>  @override<br>  State&lt;SubscriptionAnalyticsListener&gt; createState() =&gt;<br>      _SubscriptionAnalyticsListenerState();<br>}</pre><pre>class _SubscriptionAnalyticsListenerState<br>    extends State&lt;SubscriptionAnalyticsListener&gt; {<br>  SubscriptionStatus _lastStatus = SubscriptionStatus.idle;<br>  bool _didFireSuccess = false;<br>  bool _didFirePlanViewed = false;<br>  String? _lastSelectedPlanId;<br>  late final int _viewedAtMs;</pre><pre>  AnalyticsService get analytics =&gt; sl&lt;AnalyticsService&gt;();</pre><pre>  @override<br>  void initState() {<br>    super.initState();<br>    _viewedAtMs = DateTime.now().millisecondsSinceEpoch;<br>    analytics.logPaywallViewed(<br>      source: widget.source,<br>      surface: widget.surface,<br>    );<br>  }</pre><pre>  @override<br>  void dispose() {<br>    if (!_didFireSuccess) {<br>      final dwellMs =<br>          DateTime.now().millisecondsSinceEpoch - _viewedAtMs;</pre><pre>      analytics.logPaywallDismissed(<br>        source: widget.source,<br>        surface: widget.surface,<br>        dwellMs: dwellMs,<br>        lastStatus: _lastStatus.name,<br>        hadPlanSelection: _lastSelectedPlanId != null,<br>      );<br>    }</pre><pre>    super.dispose();<br>  }</pre><pre>  void handle(SubscriptionState state) {<br>    if (!_didFirePlanViewed &amp;&amp; state.plans.isNotEmpty) {<br>      _didFirePlanViewed = true;<br>      analytics.logPlanViewed(<br>        source: widget.source,<br>        surface: widget.surface,<br>        defaultPlanId: state.selectedPlanId,<br>        defaultBillingPeriod: state.billingPeriod,<br>      );<br>    }</pre><pre>    if (state.selectedPlanId != _lastSelectedPlanId) {<br>      _lastSelectedPlanId = state.selectedPlanId;<br>      analytics.logPlanSelected(<br>        source: widget.source,<br>        surface: widget.surface,<br>        planId: state.selectedPlanId,<br>        billingPeriod: state.billingPeriod,<br>        isFamily: state.isFamilySelected,<br>      );<br>    }</pre><pre>    if (state.status == _lastStatus) return;</pre><pre>    final previousStatus = _lastStatus;<br>    _lastStatus = state.status;</pre><pre>    switch (state.status) {<br>      case SubscriptionStatus.purchasing:<br>        analytics.logIapSheetShown(<br>          planId: state.selectedPlanId,<br>          source: widget.source,<br>        );<br>        break;</pre><pre>      case SubscriptionStatus.pending:<br>        analytics.logIapPending(<br>          planId: state.selectedPlanId,<br>          source: widget.source,<br>        );<br>        break;</pre><pre>      case SubscriptionStatus.verifying:<br>        analytics.logPurchaseVerifying(<br>          planId: state.selectedPlanId,<br>          source: widget.source,<br>        );<br>        break;</pre><pre>      case SubscriptionStatus.purchaseVerified:<br>        _didFireSuccess = true;<br>        analytics.logSubscriptionSuccess(<br>          planId: state.selectedPlanId,<br>          price: state.selectedAmount,<br>          source: widget.source,<br>          transactionId: state.transactionId,<br>        );<br>        break;</pre><pre>      case SubscriptionStatus.error:<br>        if (previousStatus == SubscriptionStatus.restoring) {<br>          analytics.logRestoreFailed(<br>            source: widget.source,<br>            reason: state.failureMessage ?? &#39;&#39;,<br>          );<br>        } else {<br>          analytics.logSubscriptionFailed(<br>            planId: state.selectedPlanId,<br>            source: widget.source,<br>            reason: state.failureMessage ?? &#39;&#39;,<br>          );<br>        }<br>        break;</pre><pre>      default:<br>        break;<br>    }<br>  }</pre><pre>  @override<br>  Widget build(BuildContext context) {<br>    return BlocListener&lt;SubscriptionBloc, SubscriptionState&gt;(<br>      listenWhen: (previous, current) =&gt;<br>          previous.status != current.status ||<br>          previous.selectedPlanId != current.selectedPlanId ||<br>          previous.plans.length != current.plans.length,<br>      listener: (_, state) =&gt; handle(state),<br>      child: widget.child,<br>    );<br>  }<br>}</pre><p>This pattern gives you better analytics because events are tied to actual state changes.</p><p>A button tap tells you what the user tried to do. A state transition tells you what actually happened.</p><h3>Prevent Double-Firing</h3><p>Analytics bugs are often silent. The app works, but the dashboard is wrong.</p><p>Common double-fire cases:</p><ul><li>a widget rebuilds and fires an event again</li><li>a bottom sheet opens on top of a screen and both listen to the same BLoC</li><li>default plan selection fires as if the user manually selected it</li><li>success fires and then dismiss also fires</li><li>restore failure is counted as purchase failure</li></ul><p>Use local guards for important funnel events.</p><pre>bool _didFirePlanViewed = false;<br>bool _didFireSuccess = false;<br>bool _didFireFirstSelection = false;</pre><pre>String? _lastSelectedPlanId;<br>SubscriptionStatus _lastStatus = SubscriptionStatus.idle;</pre><p>Then be intentional:</p><pre>// Fire once when plans are actually loaded.<br>if (!_didFirePlanViewed &amp;&amp; hasPlans &amp;&amp; !state.isLoading) {<br>  _didFirePlanViewed = true;<br>  analytics.logPlanViewed(...);<br>}</pre><pre>// Suppress first default selection.<br>if (selectionChanged &amp;&amp; state.selectedPlanId != null) {<br>  if (_didFireFirstSelection) {<br>    analytics.logPlanSelected(...);<br>  } else {<br>    _didFireFirstSelection = true;<br>  }<br>}</pre><pre>// Do not log dismissal after success.<br>if (!_didFireSuccess) {<br>  analytics.logPaywallDismissed(...);<br>}</pre><p>These details look small, but they protect the quality of your funnel data.</p><h3>Track Source and Surface Separately</h3><p>A paywall can open from many places:</p><ul><li>home upgrade banner</li><li>profile upgrade banner</li><li>feature lock</li><li>settings page</li><li>onboarding screen</li><li>premium feature screen</li></ul><p>The paywall can also render in different ways:</p><ul><li>full plans screen</li><li>bottom sheet</li><li>modal</li></ul><p>Do not mix these into one string.</p><pre>analytics.logPaywallViewed(<br>  source: SubscriptionSource.homeUpgradeBanner,<br>  surface: SubscriptionSurface.bottomSheet,<br>);</pre><p>Now product can ask better questions:</p><ul><li>Which source opens the paywall most?</li><li>Which source converts best?</li><li>Does the bottom sheet convert better than the full screen?</li><li>Do feature-lock paywalls convert better than dashboard banners?</li></ul><h3>Use GA4 Standard Events Carefully</h3><p>Firebase Analytics gives you standard events such as begin_checkout, purchase, login, and share.</p><p>Use them when they match the meaning.</p><pre>Future&lt;void&gt; logCheckoutStarted({<br>  required String source,<br>  required String surface,<br>  required String planId,<br>  required String billingPeriod,<br>  required int priceUsdCents,<br>}) async {<br>  final value = priceUsdCents / 100.0;</pre><pre>  await _analytics.logBeginCheckout(<br>    currency: &#39;USD&#39;,<br>    value: value,<br>    items: [<br>      AnalyticsEventItem(<br>        itemId: planId,<br>        itemName: planId,<br>        itemCategory: billingPeriod,<br>        price: value,<br>        quantity: 1,<br>      ),<br>    ],<br>  );</pre><pre>  await _analytics.logEvent(<br>    name: &#39;subscription_checkout_started&#39;,<br>    parameters: {<br>      &#39;source&#39;: source,<br>      &#39;surface&#39;: surface,<br>      &#39;plan_id&#39;: planId,<br>      &#39;billing_period&#39;: billingPeriod,<br>      &#39;price_usd_cents&#39;: priceUsdCents,<br>    },<br>  );<br>}</pre><p>This gives you both:</p><ul><li>GA4’s standard ecommerce event for reporting</li><li>a domain-specific event with your own source and surface parameters</li></ul><p>The same idea works for login and share:</p><pre>await _analytics.logLogin(loginMethod: method);</pre><pre>await _analytics.logEvent(<br>  name: &#39;login_success&#39;,<br>  parameters: {&#39;method&#39;: method},<br>);</pre><p>Standard events are useful, but do not let them replace your domain vocabulary.</p><h3>Screen Views Are Not Enough</h3><p>Adding a FirebaseAnalyticsObserver to your router is useful.</p><pre>GoRouter(<br>  observers: [<br>    FirebaseAnalyticsObserver(<br>      analytics: FirebaseAnalytics.instance,<br>    ),<br>  ],<br>  routes: [<br>    // feature routes<br>  ],<br>);</pre><p>But screen views do not tell you whether users completed important actions.</p><p>A user can view a feature screen and do nothing. Another user can start the feature setup, complete it, and perform a meaningful action. Those are very different product behaviors.</p><p>That is why the app still needs domain events:</p><pre>analytics.logFeatureSetupStarted(featureName: &#39;security_check&#39;);<br>analytics.logFeatureSetupCompleted(featureName: &#39;security_check&#39;);<br>analytics.logFeatureUsed(<br>  featureName: &#39;security_check&#39;,<br>  source: &#39;dashboard_card&#39;,<br>);</pre><p>Screen analytics tells you where users went. Domain analytics tells you what users accomplished.</p><h3>Where Should Analytics Calls Live?</h3><p>A simple rule:</p><pre>User intent events can live near the user action.<br>Business result events should live near the state/result.<br>Provider details should live only inside AnalyticsService.</pre><p>Examples:</p><ul><li>checkout_started: button tap, because it represents user intent</li><li>purchase_success: BLoC/listener state transition, because it represents verified result</li><li>signup_otp_failed: BLoC, because it depends on API result</li><li>feature_used: navigation action or feature entry point</li><li>share: share button handler, because it represents user action</li></ul><p>This keeps analytics honest.</p><h3>A/B Testing Hook</h3><p>Analytics also becomes more useful when connected to Remote Config or A/B testing.</p><p>When the app reads a variant, log an exposure event once per session.</p><pre>Future&lt;void&gt; logExperimentExposure({<br>  required String experimentId,<br>  required String variantId,<br>}) async {<br>  await _analytics.logEvent(<br>    name: &#39;experiment_impression&#39;,<br>    parameters: {<br>      &#39;experiment_id&#39;: experimentId,<br>      &#39;variant_id&#39;: variantId,<br>    },<br>  );<br>}</pre><p>Then every later funnel event can be segmented by experiment and variant.</p><p>This lets product answer:</p><ul><li>Did variant B increase checkout starts?</li><li>Did it improve verified purchases?</li><li>Did it increase dismissals?</li><li>Did it improve one source but hurt another?</li></ul><h3>Disable Telemetry When Needed</h3><p>Analytics should be intentional. In some cases, you may want to disable telemetry.</p><p>For example, if a production device appears compromised or instrumented, you may choose not to initialize analytics and crash reporting, so your dashboards are not polluted with unreliable data.</p><pre>final isDeviceCompromised =<br>    kReleaseMode &amp;&amp; await isDeviceCompromised();</pre><pre>if (!isDeviceCompromised) {<br>  await Firebase.initializeApp();</pre><pre>  if (kReleaseMode) {<br>    await FirebaseAnalytics.instance<br>        .setAnalyticsCollectionEnabled(true);<br>  }<br>}</pre><p>This is not required for every app, but it shows a useful principle: telemetry quality matters.</p><h3>Testing Analytics</h3><p>Analytics should be tested like behavior, not just hoped for.</p><p>At minimum, test:</p><ul><li>service methods produce the expected event names</li><li>required parameters are included</li><li>long reason strings are truncated</li><li>state-transition listeners do not double-fire</li><li>success prevents dismissal events</li><li>restore failures are not counted as purchase failures</li><li>first default plan selection is suppressed</li></ul><p>For unit testing, wrap the analytics provider behind an interface.</p><pre>class AnalyticsEventRecord {<br>  const AnalyticsEventRecord(this.name, this.parameters);</pre><pre>  final String name;<br>  final Map&lt;String, Object?&gt; parameters;<br>}</pre><pre>class FakeAnalyticsService implements AnalyticsService {<br>  final events = &lt;AnalyticsEventRecord&gt;[];</pre><pre>  @override<br>  Future&lt;void&gt; logFeatureUsed({<br>    required String featureName,<br>    String? source,<br>  }) async {<br>    events.add(<br>      AnalyticsEventRecord(<br>        &#39;feature_used&#39;,<br>        {<br>          &#39;feature_name&#39;: featureName,<br>          &#39;source&#39;: source,<br>        },<br>      ),<br>    );<br>  }</pre><pre>  // Implement only what the test needs.<br>}</pre><p>For manual QA, use Firebase DebugView and verify the full funnel on a real device.</p><h3>Production Checklist</h3><p>Before shipping analytics, check these:</p><ul><li>All event names are documented.</li><li>All parameters use snake_case.</li><li>Important parameter values use constants.</li><li>Raw Firebase calls are not scattered through the UI.</li><li>Funnel events distinguish user intent from business result.</li><li>State-transition events are fired once.</li><li>Dismiss events do not fire after success.</li><li>Failure reasons are short enough for analytics tools.</li><li>GA4 standard events are paired with domain events where needed.</li><li>DebugView has been checked before release.</li><li>Dashboards are updated when taxonomy changes.</li></ul><h3>Final Takeaway</h3><p>Analytics is not just logging.</p><p>In a production Flutter app, analytics is part of the architecture.</p><p>A clean analytics layer gives you:</p><ul><li>consistent event names</li><li>consistent parameters</li><li>provider flexibility</li><li>testable behavior</li><li>reliable funnels</li><li>clean UI code</li><li>better product decisions</li></ul><p>The biggest mindset shift is this:</p><pre>Do not ask every widget to understand analytics.<br>Give the app one analytics language.<br>Then make every feature speak that language.</pre><p>That is the difference between random Firebase events and a production-grade analytics system.</p><h3>Conclusion</h3><p>Good analytics is not about adding more events everywhere. It is about adding the right events in the right place.</p><p>When analytics is centralized, documented, and connected to real workflow states, the data becomes easier to trust. Developers know where events belong. Product teams know what each event means. Growth teams can build funnels without guessing. QA can verify behavior in DebugView before release.</p><p>The biggest improvement is separation of responsibility. UI handles user interaction. State management handles workflow changes. The analytics layer translates product behavior into clean, consistent events.</p><p>That is how analytics moves from random tracking code to production engineering.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea3fa69f3c44" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Production-Grade Flutter Subscription Funnel with IAP, Receipt Retry, Restore, and…]]></title>
            <link>https://medium.com/@muhmmdshabeer/building-a-production-grade-flutter-subscription-funnel-with-iap-receipt-retry-restore-and-2f7d8633ed60?source=rss-dc9ac9b74141------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f7d8633ed60</guid>
            <dc:creator><![CDATA[Muhammed Shabeer]]></dc:creator>
            <pubDate>Tue, 09 Jun 2026 13:39:06 GMT</pubDate>
            <atom:updated>2026-06-09T13:51:27.998Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Production-Grade Flutter Subscription Funnel with IAP, Receipt Retry, Restore, and Analytics</h3><p>RevenueCat vs custom backend validation, free trials, Apple/Google account ownership, server-side entitlements, and the edge cases you should plan for in 2026.</p><p>This article is written for Flutter subscription apps as of June 2026. Store rules and SDK behavior can change, so always confirm final implementation details with Apple, Google Play, and RevenueCat documentation before release.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dkt7wVQPsQMmG9hNHDr7Dg.gif" /></figure><p>Adding a subscription button is easy.</p><p>Building a production subscription system is not.</p><p>The hard part is not only opening the Apple or Google payment sheet. The hard part is deciding who gets premium access, when that access starts, when it ends, how it restores on another device, what happens when billing fails, and how your backend stays in sync.</p><p>In a real Flutter app, the subscription funnel usually touches:</p><ul><li>Flutter UI</li><li>Apple App Store / Google Play Billing</li><li>backend receipt validation</li><li>user profile / entitlement state</li><li>analytics events</li><li>restore purchases</li><li>retry logic when verification fails</li><li>free trial eligibility</li></ul><p>This article explains both approaches, where RevenueCat fits, where custom backend validation fits, and what edge cases should not be ignored.</p><h3>What Is a Subscription Funnel?</h3><p>A subscription funnel is the full path from a user seeing a premium offer to the app confirming that the user has premium access.</p><p>It is not only the payment screen.</p><p>A real subscription funnel usually looks like this:</p><pre>User sees premium entry point<br>  -&gt; paywall opens<br>  -&gt; plans are loaded<br>  -&gt; user selects monthly / yearly / family<br>  -&gt; user taps subscribe<br>  -&gt; Apple or Google purchase sheet opens<br>  -&gt; user pays, cancels, or payment becomes pending<br>  -&gt; app receives purchase update<br>  -&gt; backend or RevenueCat verifies the transaction<br>  -&gt; app unlocks premium or shows the correct recovery state</pre><p>This is why analytics matters. If 10,000 users see the upgrade banner but only 500 reach the purchase sheet, the problem may be the paywall. If many users reach the purchase sheet but cancel, the issue may be pricing, trust, copy, or store payment friction. If users pay but do not unlock premium, the issue is probably verification, retry, or backend sync.</p><p>So when this article says “funnel,” it means product flow plus technical reliability:</p><pre>Discovery<br>  -&gt; Paywall<br>  -&gt; Plan selection<br>  -&gt; Checkout<br>  -&gt; Store purchase<br>  -&gt; Verification<br>  -&gt; Entitlement<br>  -&gt; Restore / retention</pre><h3>The Most Important Mental Model</h3><p>A subscription purchase belongs to the user’s Apple ID or Google account.</p><p>It does not naturally belong to your app login.</p><p>Your app login is your identity system. Apple and Google are payment identity systems. They are related only because you map them together after a successful purchase.</p><p>This distinction explains many subscription bugs.</p><p>For example:</p><ul><li>A user can log out from your app and log into another app account on the same device.</li><li>The Apple ID or Google account on the device may still own an active subscription.</li><li>A user can buy on one device and expect access on another device.</li><li>A user can delete and reinstall your app, but their store subscription still exists.</li><li>Your backend can say “free user” while the store says “active subscriber” until you sync correctly.</li></ul><p>So the production rule is:</p><pre>Store account owns the payment.<br>Your backend owns the app entitlement.</pre><p>The job of your subscription system is to keep those two worlds in sync.</p><p>One important clarification: choosing RevenueCat or choosing your own backend validation is usually not an individual developer decision.</p><p>It depends on the company, product stage, budget, compliance needs, backend ownership, analytics needs, and how much subscription infrastructure the team wants to maintain. RevenueCat can save a lot of engineering time, but it is also a commercial platform. Apple and Google also have their own store fees and rules. So the decision should be made with product, backend, finance, and engineering together.</p><p>As Flutter engineers, our duty is to implement the selected approach correctly.</p><h3>Two Common Approaches</h3><h3>Approach 1: Custom Backend Validation</h3><p>In this setup, Flutter starts the purchase, receives the purchase token or receipt, sends it to your backend, and your backend validates it with Apple or Google.</p><p>If validation succeeds, your backend updates the user record:</p><pre>User purchases subscription<br>        |<br>        v<br>Flutter receives receipt / purchase token<br>        |<br>        v<br>App sends receipt/token to backend<br>        |<br>        v<br>Backend validates with Apple / Google<br>        |<br>        v<br>Backend marks user as premium<br>        |<br>        v<br>App refreshes profile / entitlement state</pre><p>This setup makes sense when the backend already owns user plans, billing status, access control, limits, invoices, family plans, or business rules.</p><p>Your backend becomes the source of truth for your app’s entitlement.</p><p>Apple and Google remain the source of truth for whether the store purchase is valid.</p><h3>Approach 2: RevenueCat</h3><p>RevenueCat wraps StoreKit, Google Play Billing, subscription state, entitlements, product fetching, restore purchases, webhooks, and analytics in a much simpler developer experience.</p><p>RevenueCat’s Flutter SDK is designed to sit above iOS and Android purchase APIs and expose a unified customer/entitlement model. Their Flutter docs describe RevenueCat as providing SDKs and backend infrastructure around StoreKit, Google Play Billing, and RevenueCat Web Billing.</p><p>In a RevenueCat flow, your app usually checks whether a RevenueCat entitlement is active:</p><pre>CustomerInfo customerInfo = await Purchases.getCustomerInfo();</pre><pre>final isPremium =<br>    customerInfo.entitlements.active.containsKey(&#39;premium&#39;);</pre><p>Instead of writing your own Apple/Google subscription-status engine, you configure products and entitlements in RevenueCat.</p><h3>Why Use RevenueCat?</h3><p>RevenueCat is valuable because subscriptions are state machines, not just payments.</p><p>A mature subscription system needs to understand:</p><ul><li>active subscriptions</li><li>expired subscriptions</li><li>free trials</li><li>introductory offers</li><li>billing retry</li><li>grace period</li><li>refunds</li><li>cancellations</li><li>restore purchases</li><li>cross-device access</li><li>cross-platform entitlements</li><li>server notifications</li></ul><p>RevenueCat gives you a ready-made entitlement layer, SDK methods, dashboard, webhook support, and analytics around that lifecycle.</p><p>The biggest advantages are:</p><ul><li>less native billing code</li><li>one entitlement model across iOS and Android</li><li>restore purchase handling is simpler</li><li>no need to build a full subscription-status engine immediately</li><li>webhooks can sync RevenueCat state back to your backend</li><li>better visibility into trial conversion, churn, and renewals</li></ul><p>RevenueCat is especially useful when your team wants to ship subscriptions quickly and avoid spending weeks on App Store Server API, Google Play Developer API, server notifications, receipt parsing, renewal events, and edge-case handling.</p><h3>Why Not Always Use RevenueCat?</h3><p>RevenueCat is not wrong. Custom backend validation is not wrong either.</p><p>The right choice depends on who should own the entitlement state.</p><p>Custom backend validation fits when:</p><ul><li>your backend already has a strong subscription model</li><li>you need custom account-level access rules</li><li>you need full control over validation and audit history</li><li>you already process store notifications server-side</li><li>you do not want a third-party dependency in the billing entitlement path</li><li>your product has complex B2B, family, or account-seat logic</li></ul><p>RevenueCat fits when:</p><ul><li>you want faster implementation</li><li>you want built-in entitlements</li><li>you do not want to maintain Apple/Google receipt verification yourself</li><li>you need subscription analytics quickly</li><li>you want webhooks to update your backend instead of writing the entire billing backend</li></ul><p>A practical decision rule:</p><pre>If billing state is core backend infrastructure, validate on your backend.<br>If speed, analytics, and cross-platform entitlement simplicity matter more, use RevenueCat.<br>If you use RevenueCat but still have your own backend, sync RevenueCat events into your backend.</pre><h3>Production Architecture</h3><p>For apps where the backend must mark the user as purchased, the architecture usually looks like this:</p><pre>Flutter app<br>  -&gt; Store purchase sheet<br>  -&gt; Purchase success callback<br>  -&gt; Backend verify endpoint<br>  -&gt; Apple / Google verification<br>  -&gt; Backend updates subscription table<br>  -&gt; App refreshes user profile<br>  -&gt; UI unlocks premium features</pre><p>In this model, the Flutter app should not permanently unlock premium just because the purchase callback fired.</p><p>The app can show a loading state such as “Verifying purchase…” and unlock only after the backend confirms the entitlement.</p><h3>Implementation Shape in Flutter</h3><p>The implementation below is intentionally generic, but it is based on a real Flutter architecture: in_app_purchase in the app, a backend verification endpoint, BLoC for workflow state, secure local storage for pending receipts, and Firebase Analytics for the funnel.</p><p>The snippets are simplified for explanation. They are not meant to be pasted as a complete package. The goal is to show the production structure, responsibilities, and edge-case handling that should exist in a real app.</p><p>The UI should not call Apple, Google, RevenueCat, or your backend directly. The UI should dispatch an event such as BuySubscription and react to state changes.</p><p>At a high level, the app can be separated like this:</p><pre>Paywall UI<br>  -&gt; SubscriptionBloc<br>  -&gt; SubscriptionService<br>  -&gt; Apple / Google purchase sheet<br>  -&gt; purchaseStream callback<br>  -&gt; SubscriptionBloc verifies receipt<br>  -&gt; VerifySubscriptionUseCase<br>  -&gt; SubscriptionRepository<br>  -&gt; RemoteDataSource<br>  -&gt; Backend /subscription/verify<br>  -&gt; Backend validates with Apple or Google<br>  -&gt; Backend updates user entitlement<br>  -&gt; App refreshes profile and unlocks premium</pre><p>This separation matters because every layer has one job:</p><ul><li>UI shows plans and dispatches user actions.</li><li>BLoC owns workflow state.</li><li>Subscription service talks to the store SDK.</li><li>Use case expresses the business action.</li><li>Repository converts failures into a predictable result type.</li><li>Remote data source performs the HTTP call.</li><li>Backend validates the transaction and updates entitlement.</li></ul><pre>enum SubscriptionStatus {<br>  idle,<br>  purchasing,<br>  restoring,<br>  noRestoreAvailable,<br>  verifying,<br>  retrying,<br>  purchaseVerified,<br>  purchaseRestoreVerified,<br>  purchaseRetryVerified,<br>  pending,<br>  canceled,<br>  error,<br>  duplicatePurchase,<br>}</pre><p>This is more useful than a simple isLoading boolean because the paywall has many different states. A pending payment is not the same as a canceled payment. A duplicate purchase is not the same as a backend failure. A restore success is not the same as a new purchase success.</p><p>That state enum becomes the language shared by the UI, analytics, restore flow, retry flow, and error handling. When the state is precise, the UI can show the right message and analytics can record the right event.</p><h3>Product IDs Should Come from Configuration</h3><p>Do not hardcode store product IDs across the UI. Keep platform product IDs in configuration and query the store based on the current platform.</p><pre>class IapProductConfig {<br>  static final iosProductIds = {<br>    env[&#39;IOS_PERSONAL_MONTHLY&#39;]!,<br>    env[&#39;IOS_PERSONAL_YEARLY&#39;]!,<br>    env[&#39;IOS_FAMILY_MONTHLY&#39;]!,<br>    env[&#39;IOS_FAMILY_YEARLY&#39;]!,<br>  };</pre><pre>  static final androidProductIds = {<br>    env[&#39;ANDROID_PERSONAL_MONTHLY&#39;]!,<br>    env[&#39;ANDROID_PERSONAL_YEARLY&#39;]!,<br>    env[&#39;ANDROID_FAMILY_MONTHLY&#39;]!,<br>    env[&#39;ANDROID_FAMILY_YEARLY&#39;]!,<br>  };<br>}</pre><p>This helps when Apple and Google product IDs are not identical, or when Android uses lowercase IDs while iOS keeps a different naming style.</p><h3>Subscription Service: Own the Store Listener</h3><p>The store purchase stream should be initialized once and owned by a service. This service listens to purchase updates, deduplicates purchase callbacks, completes pending purchases, and forwards only meaningful purchase events to the BLoC.</p><pre>class SubscriptionService {<br>  final InAppPurchase _iap = InAppPurchase.instance;<br>  final Set&lt;String&gt; _processedPurchaseIds = {};</pre><pre>  StreamSubscription&lt;List&lt;PurchaseDetails&gt;&gt;? _subscription;<br>  List&lt;ProductDetails&gt;? _cachedProducts;</pre><pre>  void Function(List&lt;PurchaseDetails&gt; purchases)? onPurchaseUpdate;<br>  VoidCallback? onResetRequested;</pre><pre>  Future&lt;void&gt; init() async {<br>    _subscription ??= _iap.purchaseStream.listen(<br>      _handlePurchases,<br>      onError: (error) {<br>        // Report purchase stream errors to the workflow layer.<br>      },<br>    );<br>  }</pre><pre>  Future&lt;List&lt;ProductDetails&gt;&gt; fetchProducts() async {<br>    if (!await _iap.isAvailable()) return [];</pre><pre>    final productIds = Platform.isAndroid<br>        ? IapProductConfig.androidProductIds<br>        : IapProductConfig.iosProductIds;</pre><pre>    final response = await _iap.queryProductDetails(productIds);<br>    _cachedProducts = response.productDetails;<br>    return _cachedProducts!;<br>  }</pre><pre>  Future&lt;void&gt; purchaseProduct(<br>    String productId, {<br>    PurchaseDetails? oldPurchase,<br>  }) async {<br>    if (!await _iap.isAvailable()) {<br>      throw Exception(&#39;Billing is not available on this device.&#39;);<br>    }</pre><pre>    _cachedProducts ??= await fetchProducts();</pre><pre>    final product = _cachedProducts!.firstWhere(<br>      (item) =&gt; item.id == productId,<br>      orElse: () =&gt; throw Exception(&#39;Product not found: $productId&#39;),<br>    );</pre><pre>    final PurchaseParam purchaseParam;</pre><pre>    if (Platform.isAndroid &amp;&amp; oldPurchase is GooglePlayPurchaseDetails) {<br>      purchaseParam = GooglePlayPurchaseParam(<br>        productDetails: product,<br>        changeSubscriptionParam: ChangeSubscriptionParam(<br>          oldPurchaseDetails: oldPurchase,<br>          replacementMode: ReplacementMode.withTimeProration,<br>        ),<br>      );<br>    } else {<br>      purchaseParam = PurchaseParam(productDetails: product);<br>    }</pre><pre>    await _iap.buyNonConsumable(purchaseParam: purchaseParam);<br>  }</pre><pre>  void _handlePurchases(List&lt;PurchaseDetails&gt; purchases) {<br>    final newPurchases = &lt;PurchaseDetails&gt;[];</pre><pre>    for (final purchase in purchases) {<br>      final id = purchase.purchaseID ?? purchase.productID;</pre><pre>      if (purchase.status == PurchaseStatus.error ||<br>          purchase.status == PurchaseStatus.canceled) {<br>        onResetRequested?.call();<br>      } else if (_processedPurchaseIds.contains(id) &amp;&amp;<br>          purchase.status != PurchaseStatus.restored) {<br>        continue;<br>      }</pre><pre>      _processedPurchaseIds.add(id);</pre><pre>      if (purchase.status == PurchaseStatus.purchased ||<br>          purchase.status == PurchaseStatus.restored) {<br>        newPurchases.add(purchase);<br>      }</pre><pre>      if (purchase.pendingCompletePurchase) {<br>        _iap.completePurchase(purchase);<br>      }<br>    }</pre><pre>    if (newPurchases.isNotEmpty) {<br>      onPurchaseUpdate?.call(newPurchases);<br>    }<br>  }<br>}</pre><p>Two details matter here.</p><p>First, Android upgrades or downgrades need the old purchase when changing a subscription. That is why the purchase method accepts oldPurchase and passes a ChangeSubscriptionParam.</p><p>Second, duplicate purchase callbacks can happen. Deduplication protects the app from verifying the same transaction many times or firing analytics repeatedly.</p><p>Notice what this service does not do: it does not decide whether the user is premium. It only talks to the store and reports purchase updates. The entitlement decision stays with the backend verification flow.</p><h3>BLoC: Turn Store Events into Business States</h3><p>The snippets below use BLoC because this style works well for event-driven purchase flows: buy, pending, canceled, verifying, restored, retrying, and verified are all explicit events or states.</p><p>You do not have to use BLoC specifically. The same idea can be implemented with Cubit, Riverpod, Provider, MobX, or another state management approach. What matters is the separation:</p><pre>UI should not verify receipts.<br>UI should not call store APIs directly.<br>UI should not decide premium access.</pre><pre>State layer should coordinate the workflow.<br>Service layer should talk to Apple / Google.<br>Backend should validate and own entitlement.</pre><p>The BLoC owns the subscription workflow. It starts purchases, handles platform exceptions, starts a watchdog timer, verifies receipts, saves failed verification receipts, restores purchases, and emits states for the UI.</p><pre>Future&lt;void&gt; onBuySubscription(<br>  BuySubscription event,<br>  Emitter&lt;SubscriptionState&gt; emit,<br>) async {<br>  if (state.status == SubscriptionStatus.purchasing) return;</pre><pre>  emit(state.copyWith(<br>    status: SubscriptionStatus.purchasing,<br>    failureMessage: null,<br>  ));</pre><pre>  purchaseWatchdog?.cancel();<br>  purchaseWatchdog = Timer(const Duration(seconds: 180), () {<br>    add(const PurchaseTimeoutDetected());<br>  });</pre><pre>  try {<br>    await subscriptionService.purchaseProduct(<br>      event.productId,<br>      oldPurchase: event.oldPurchase,<br>    );<br>  } on PlatformException catch (error) {<br>    purchaseWatchdog?.cancel();</pre><pre>    if (error.code == &#39;storekit2_purchase_cancelled&#39; ||<br>        error.code == &#39;purchase_canceled&#39;) {<br>      emit(state.copyWith(<br>        status: SubscriptionStatus.canceled,<br>        cancelReason: &#39;user_cancel&#39;,<br>      ));<br>      return;<br>    }</pre><pre>    emit(state.copyWith(<br>      status: SubscriptionStatus.error,<br>      failureMessage: error.message ?? &#39;Unknown platform error&#39;,<br>    ));<br>  } catch (_) {<br>    purchaseWatchdog?.cancel();<br>    emit(state.copyWith(<br>      status: SubscriptionStatus.error,<br>      failureMessage: &#39;Unable to continue the purchase.&#39;,<br>    ));<br>  }<br>}</pre><p>The 180-second watchdog is a practical production detail. Sometimes the user leaves the app for 3DS, UPI, net banking, or another payment confirmation flow. Sometimes the store callback can be delayed or never arrive cleanly. A watchdog prevents the paywall from staying in purchasing forever.</p><p>This is also why the app should distinguish a user cancellation from a timeout. A user cancellation is a normal decision. A timeout is a recovery path. They should not be analyzed as the same thing.</p><h3>Backend Verification After Store Purchase</h3><p>When the store reports a successful purchase, the app should move to verifying and send the platform receipt or purchase token to the backend.</p><pre>Future&lt;void&gt; onPurchaseSuccess(<br>  PurchaseDetails purchase,<br>  Emitter&lt;SubscriptionState&gt; emit,<br>) async {<br>  purchaseWatchdog?.cancel();</pre><pre>  emit(state.copyWith(<br>    status: SubscriptionStatus.verifying,<br>    failureMessage: null,<br>  ));</pre><pre>  final platform = Platform.isIOS ? &#39;ios&#39; : &#39;android&#39;;<br>  final receipt = purchase.verificationData.serverVerificationData;</pre><pre>  if (receipt.isEmpty) {<br>    emit(state.copyWith(status: SubscriptionStatus.idle));<br>    return;<br>  }</pre><pre>  final result = await verifySubscriptionUseCase.execute(<br>    platform: platform,<br>    receipt: receipt,<br>    productId: purchase.productID,<br>  );</pre><pre>  result.fold(<br>    (failure) async {<br>      await pendingReceiptService.save(<br>        productId: purchase.productID,<br>        receipt: receipt,<br>        platform: platform,<br>        userId: currentUserId,<br>      );</pre><pre>      emit(state.copyWith(<br>        status: SubscriptionStatus.error,<br>        failureMessage: failure.message,<br>      ));<br>    },<br>    (response) async {<br>      await pendingReceiptService.remove(<br>        productId: purchase.productID,<br>        receipt: receipt,<br>        platform: platform,<br>        userId: currentUserId,<br>      );</pre><pre>      if (response.isDuplicatePurchase) {<br>        emit(state.copyWith(<br>          status: SubscriptionStatus.duplicatePurchase,<br>          failureMessage: response.message,<br>        ));<br>      } else {<br>        emit(state.copyWith(<br>          status: SubscriptionStatus.purchaseVerified,<br>          activePlanId: purchase.productID,<br>          activePurchaseDetails: purchase,<br>        ));<br>      }<br>    },<br>  );<br>}</pre><p>This is where the app stops being a simple payment button and becomes a subscription system.</p><p>The purchase is not considered fully active just because Apple or Google returned a success callback. The backend still needs to validate the receipt or purchase token and update the user’s account.</p><p>The important idea is this:</p><pre>Store success means: &quot;payment event happened.&quot;<br>Backend verification means: &quot;this app user can access premium.&quot;</pre><h3>Backend API Shape</h3><p>The app should send different fields depending on platform. Android commonly sends a purchase token. iOS sends receipt data.</p><pre>Future&lt;BaseResponse&gt; verifySubscription({<br>  required String platform,<br>  required String receipt,<br>  required String productId,<br>}) async {<br>  final data = {<br>    &#39;platform&#39;: platform,<br>    &#39;product_id&#39;: productId,<br>  };</pre><pre>  if (Platform.isAndroid) {<br>    data[&#39;purchase_token&#39;] = receipt;<br>    data[&#39;product_original_id&#39;] = mapAndroidIdToServerPlan(productId);<br>  } else {<br>    data[&#39;receipt&#39;] = receipt;<br>  }</pre><pre>  final response = await dio.post(<br>    &#39;/subscription/verify&#39;,<br>    data: data,<br>  );</pre><pre>  return BaseResponse.fromJson(response.data);<br>}</pre><p>The repository can wrap this with Either&lt;Failure, T&gt; so the BLoC does not need to catch raw Dio exceptions.</p><pre>class SubscriptionRepository {<br>  Future&lt;Either&lt;Failure, BaseResponse&gt;&gt; verifySubscription({<br>    required String platform,<br>    required String receipt,<br>    required String productId,<br>  }) {<br>    return safeApiCall(() async {<br>      return remoteDataSource.verifySubscription(<br>        platform: platform,<br>        receipt: receipt,<br>        productId: productId,<br>      );<br>    });<br>  }<br>}</pre><h3>Receipt Retry Is Not Optional</h3><p>If backend verification fails after a successful store purchase, save the receipt securely and retry later.</p><p>The painful edge case is simple:</p><ol><li>User pays successfully.</li><li>Apple or Google returns a valid transaction.</li><li>Your app sends the receipt to your backend.</li><li>The network fails.</li><li>Your backend never marks the user as premium.</li></ol><p>The user paid, but your app still shows free access. That is both a bad user experience and a support problem.</p><pre>class PendingReceiptService {<br>  static const key = &#39;pending_receipts&#39;;</pre><pre>  PendingReceiptService(this.secureStorage);</pre><pre>  final SecureStorage secureStorage;</pre><pre>  Future&lt;void&gt; save({<br>    required String productId,<br>    required String receipt,<br>    required String platform,<br>    required String userId,<br>  }) async {<br>    final pending = await getPendingReceipts();</pre><pre>    final exists = pending.any((item) =&gt;<br>        item.productId == productId &amp;&amp;<br>        item.receipt == receipt &amp;&amp;<br>        item.platform == platform &amp;&amp;<br>        item.userId == userId);</pre><pre>    if (exists) return;</pre><pre>    pending.add(PendingReceipt(<br>      productId: productId,<br>      receipt: receipt,<br>      platform: platform,<br>      userId: userId,<br>      createdAt: DateTime.now(),<br>    ));</pre><pre>    await secureStorage.write(key: key, value: jsonEncode(pending));<br>  }<br>}</pre><p>Retry should be tied to the current logged-in user. Otherwise, one user’s pending receipt could accidentally be retried under another app account.</p><pre>Future&lt;void&gt; retryVerification() async {<br>  final userId = await authService.currentUserId();<br>  if (userId == null) return;</pre><pre>  final allReceipts = await pendingReceiptService.getPendingReceipts();<br>  final receipts = allReceipts.where((item) =&gt; item.userId == userId);</pre><pre>  for (final receipt in receipts) {<br>    if (!validProductIds.contains(receipt.productId)) {<br>      await pendingReceiptService.remove(receipt);<br>      continue;<br>    }</pre><pre>    final result = await verifySubscriptionUseCase.execute(<br>      platform: receipt.platform,<br>      receipt: receipt.receipt,<br>      productId: receipt.productId,<br>    );</pre><pre>    result.fold(<br>      (failure) {<br>        if (failure.message.toLowerCase().contains(&#39;expired&#39;)) {<br>          pendingReceiptService.remove(receipt);<br>        }<br>      },<br>      (response) {<br>        pendingReceiptService.remove(receipt);</pre><pre>        if (response.isDuplicatePurchase) {<br>          add(HandleDuplicatePurchase(response.message));<br>        } else {<br>          add(PurchaseRetryVerified(receipt.productId));<br>        }<br>      },<br>    );<br>  }<br>}</pre><p>The key is not the exact class names. The key is that failed backend verification should not punish a paid user.</p><p>A simplified state machine looks like this:</p><pre>idle<br>  -&gt; purchasing<br>  -&gt; verifying<br>  -&gt; purchased<br>  -&gt; premium_active</pre><p>Failure states matter too:</p><pre>purchasing<br>  -&gt; canceled</pre><pre>purchasing<br>  -&gt; pending</pre><pre>verifying<br>  -&gt; verification_failed<br>  -&gt; save_receipt_for_retry</pre><pre>restore<br>  -&gt; restored<br>  -&gt; verifying<br>  -&gt; premium_active</pre><h3>Restore Purchases</h3><p>Restore purchases is not just a nice button for iOS review. It is a required part of a good subscription experience.</p><p>A user may:</p><ul><li>reinstall the app</li><li>switch devices</li><li>log into a different app account</li><li>lose local app storage</li><li>expect their Apple/Google purchase to unlock again</li></ul><p>Restore should ask the store for existing purchases and then verify them with your backend.</p><pre>User taps Restore<br>        |<br>        v<br>Store returns previous purchases<br>        |<br>        v<br>App sends receipt/token to backend<br>        |<br>        v<br>Backend validates<br>        |<br>        v<br>Backend links entitlement to current app user<br>        |<br>        v<br>App refreshes profile</pre><p>The tricky part is account linking.</p><p>If the same Apple ID subscription is restored while the user is logged into a different app account, you need a business rule:</p><ul><li>allow transfer?</li><li>block as duplicate purchase?</li><li>ask user to log into the original account?</li><li>let support resolve it manually?</li></ul><p>Do not ignore this. It will happen.</p><h3>Restore Implementation Detail</h3><p>A production restore flow should not simply trust that the store returned a previous purchase. It should verify each restored purchase with the backend and then decide which state to show.</p><pre>Future&lt;void&gt; restorePurchases() async {<br>  emit(state.copyWith(status: SubscriptionStatus.restoring));</pre><pre>  final restoredPurchases = await subscriptionService.restorePurchases();</pre><pre>  if (restoredPurchases.isEmpty) {<br>    emit(state.copyWith(status: SubscriptionStatus.noRestoreAvailable));<br>    return;<br>  }</pre><pre>  final results = &lt;RestoreVerificationResult&gt;[];</pre><pre>  for (final purchase in restoredPurchases) {<br>    final result = await verifyRestoredPurchase(purchase);<br>    results.add(result);<br>  }</pre><pre>  final success = results.where((item) =&gt; item.isSuccess).firstOrNull;<br>  final duplicate = results.where((item) =&gt; item.isDuplicate).firstOrNull;<br>  final error = results.where((item) =&gt; item.isError).firstOrNull;</pre><pre>  if (success != null) {<br>    emit(state.copyWith(status: SubscriptionStatus.purchaseRestoreVerified));<br>  } else if (duplicate != null) {<br>    emit(state.copyWith(<br>      status: SubscriptionStatus.duplicatePurchase,<br>      failureMessage: duplicate.message,<br>    ));<br>  } else if (error != null) {<br>    emit(state.copyWith(<br>      status: SubscriptionStatus.error,<br>      failureMessage: error.message,<br>    ));<br>  } else {<br>    emit(state.copyWith(status: SubscriptionStatus.noRestoreAvailable));<br>  }<br>}</pre><p>This flow handles the real cases: restore success, empty restore, duplicate purchase linked to another account, and backend verification failure.</p><h3>Free Trials Are Store Configuration, Not App Login Logic</h3><p>This is another important point.</p><p>Free trial eligibility is primarily handled by Apple and Google based on the store account and subscription configuration.</p><p>It is not simply your app login saying “this user has never tried premium.”</p><p>If a person used a free trial with the same Apple ID or Google account before, your new app account may still be ineligible.</p><p>That is why trial text should be careful. Use wording like:</p><pre>Start free trial if eligible.<br>Then auto-renews at $X/month unless canceled.</pre><p>Do not promise a free trial to every app account if the store may decide the Apple/Google account is not eligible.</p><h3>Apple Free Trial Setup</h3><p>For iOS, free trials are configured as introductory offers for auto-renewable subscriptions in App Store Connect.</p><p>Apple supports introductory offer types such as free trial, pay up front, and pay as you go. Apple also notes that a customer is generally eligible to redeem one introductory offer per subscription group.</p><p>For a Flutter app, the practical setup is:</p><ol><li>Create an auto-renewable subscription in App Store Connect.</li><li>Put related plans in the correct subscription group.</li><li>Add an introductory offer.</li><li>Select free trial as the offer type.</li><li>Choose the trial duration allowed for the subscription duration.</li><li>Make sure the app UI clearly explains trial duration, renewal price, renewal period, and cancellation behavior.</li><li>Validate subscription state server-side or through RevenueCat before unlocking permanent access.</li></ol><p>Do not hardcode trial availability only from your own database. The store account’s eligibility matters.</p><h3>Google Play Free Trial Setup</h3><p>Google Play subscriptions are configured with subscriptions, base plans, and offers.</p><p>For a free trial in Play Console:</p><ol><li>Create a subscription product.</li><li>Create and activate at least one base plan.</li><li>Add an offer linked to that base plan.</li><li>Add a free trial phase to the offer.</li><li>Configure eligibility, regions, pricing, and tags if needed.</li><li>Clearly show the post-trial recurring price in your app UI.</li></ol><p>Google Play’s subscription model is powerful, but the base plan and offer structure means your app must be careful about which offer it shows and purchases.</p><p>Again, this is store-account logic. Your app login is not the final authority on whether Google allows a trial.</p><h3>Backend Validation</h3><p>If you are doing your own backend validation, your backend needs to validate with the correct store.</p><p>For Apple, modern server-side validation should use the App Store Server API. Apple describes it as a REST API for managing App Store transactions and subscription status from your server.</p><p>For Google, your backend usually validates purchase tokens through the Google Play Developer API and listens for lifecycle changes through server-side notifications or scheduled rechecks.</p><p>Your backend should store:</p><ul><li>app user ID</li><li>platform: iOS or Android</li><li>product ID</li><li>original transaction ID or purchase token</li><li>transaction ID</li><li>subscription status</li><li>expiration date</li><li>environment: sandbox or production</li><li>latest verification response timestamp</li></ul><p>And your app should not decide premium access only from local state.</p><pre>final profile = await backend.fetchUserProfile();<br>final isPremium = profile.subscriptionStatus == &#39;active&#39;;</pre><p>The backend should be the entitlement source of truth for your application.</p><h3>RevenueCat with Your Backend</h3><p>If you use RevenueCat but still need your backend to mark the user as purchased, use webhooks.</p><p>RevenueCat webhooks can notify your server about subscription events. RevenueCat recommends authenticating webhook requests and responding quickly. Their docs also recommend calling the subscriber API after receiving a webhook so your system syncs from a consistent customer state.</p><p>The architecture becomes:</p><pre>Flutter app<br>  -&gt; RevenueCat purchase<br>  -&gt; RevenueCat entitlement active<br>  -&gt; RevenueCat webhook to backend<br>  -&gt; Backend updates user subscription<br>  -&gt; App refreshes profile</pre><p>This is a strong hybrid approach.</p><p>RevenueCat handles store complexity. Your backend still owns application access.</p><h3>Testing Before Release</h3><p>Subscription testing is different from normal API testing because Apple and Google decide which account is allowed to make a test purchase.</p><p>Do not test subscriptions only with your normal personal Apple ID or Google account and assume everything is correct.</p><h3>Google Play Testing</h3><p>For Google Play Billing, add tester emails in Play Console as license testers. Google uses those email addresses to recognize that the purchase is a test purchase.</p><p>The practical checklist is:</p><ol><li>Add tester email addresses in Play Console license testing.</li><li>Make sure the tester joins the correct internal, closed, or open testing track.</li><li>Install the app from Google Play using that tester account.</li><li>Use a product or subscription that is active in Play Console.</li><li>Confirm the purchase sheet shows a test payment method.</li><li>Send the purchase token to your backend and validate the sandbox/test transaction path.</li><li>Test purchase success, cancellation, pending payment, restore/reinstall, upgrade, downgrade, and duplicate account cases.</li></ol><p>If the email is not added correctly, Google may treat the account like a normal user or may not expose the expected test purchase flow.</p><h3>iOS Sandbox Testing</h3><p>For iOS, use Sandbox Apple Accounts from App Store Connect. Apple provides a sandbox environment for testing In-App Purchases without real charges.</p><p>The practical checklist is:</p><ol><li>Create Sandbox Apple Accounts in App Store Connect.</li><li>Install the app using Xcode or TestFlight depending on the flow being tested.</li><li>When the purchase sheet asks for an account, sign in with the Sandbox Apple Account.</li><li>Do not confuse the device’s normal Apple ID with the sandbox purchase account.</li><li>Verify that the purchase prompt indicates the sandbox environment when applicable.</li><li>Send the sandbox receipt to your backend and make sure the backend validates against the correct Apple environment.</li><li>Test purchase success, cancellation, restore, renewal behavior, expired subscription, refund/revocation handling, and account switching.</li></ol><p>One common mistake is validating a sandbox receipt against production only. Your backend should understand the transaction environment and handle sandbox and production separately.</p><h3>Testing RevenueCat</h3><p>If the company uses RevenueCat, you still test through Apple and Google sandbox/test purchase environments. RevenueCat simplifies entitlement handling, but the store account setup still matters.</p><p>The minimum test matrix should include:</p><ul><li>new subscription purchase</li><li>free trial purchase</li><li>trial eligibility failure</li><li>restore with same app account</li><li>restore with different app account</li><li>backend webhook received</li><li>backend profile updated after webhook</li><li>app refreshed entitlement after webhook/profile sync</li></ul><p>Testing should prove the full chain, not only the payment sheet:</p><pre>Store test account<br>  -&gt; test purchase<br>  -&gt; app receives receipt/token<br>  -&gt; backend or RevenueCat validates<br>  -&gt; webhook/server sync runs<br>  -&gt; user profile becomes premium<br>  -&gt; analytics event is recorded<br>  -&gt; restore works after reinstall</pre><h3>Analytics Events to Track</h3><p>A subscription funnel without analytics is guesswork.</p><p>Useful events to track include:</p><ul><li>subscription_paywall_viewed</li><li>subscription_plan_viewed</li><li>subscription_plan_selected</li><li>subscription_checkout_started</li><li>subscription_iap_sheet_shown</li><li>subscription_iap_pending</li><li>subscription_purchase_canceled</li><li>subscription_purchase_verifying</li><li>subscription_purchase_success</li><li>subscription_purchase_failed</li><li>subscription_restore_started</li><li>subscription_restore_success</li><li>subscription_restore_empty</li><li>subscription_purchase_duplicate</li><li>subscription_paywall_dismissed</li></ul><p>Also track where the paywall opened from:</p><ul><li>home screen upgrade banner</li><li>profile screen</li><li>feature lock</li><li>onboarding trial screen</li><li>settings / billing screen</li></ul><p>This tells you which entry points actually convert.</p><p>A clean way to implement this is to keep analytics in a listener that watches subscription state transitions. This avoids scattering analytics calls across every button and dialog.</p><pre>class SubscriptionAnalyticsListener extends StatefulWidget {<br>  const SubscriptionAnalyticsListener({<br>    super.key,<br>    required this.source,<br>    required this.surface,<br>    required this.child,<br>  });</pre><pre>  final String source;<br>  final String surface;<br>  final Widget child;</pre><pre>  @override<br>  State&lt;SubscriptionAnalyticsListener&gt; createState() =&gt;<br>      _SubscriptionAnalyticsListenerState();<br>}</pre><pre>class _SubscriptionAnalyticsListenerState<br>    extends State&lt;SubscriptionAnalyticsListener&gt; {<br>  SubscriptionStatus _lastStatus = SubscriptionStatus.idle;<br>  bool _didFireSuccess = false;</pre><pre>  @override<br>  void initState() {<br>    super.initState();<br>    analytics.logPaywallViewed(<br>      source: widget.source,<br>      surface: widget.surface,<br>    );<br>  }</pre><pre>  @override<br>  void dispose() {<br>    if (!_didFireSuccess) {<br>      analytics.logPaywallDismissed(<br>        source: widget.source,<br>        surface: widget.surface,<br>        lastStatus: _lastStatus.name,<br>      );<br>    }<br>    super.dispose();<br>  }</pre><pre>  void _handle(SubscriptionState state) {<br>    if (state.status == _lastStatus) return;</pre><pre>    _lastStatus = state.status;</pre><pre>    switch (state.status) {<br>      case SubscriptionStatus.purchasing:<br>        analytics.logIapSheetShown(planId: state.selectedPlanId);<br>        break;<br>      case SubscriptionStatus.pending:<br>        analytics.logIapPending(planId: state.selectedPlanId);<br>        break;<br>      case SubscriptionStatus.canceled:<br>        analytics.logPurchaseCanceled(reason: state.cancelReason);<br>        break;<br>      case SubscriptionStatus.verifying:<br>        analytics.logPurchaseVerifying(planId: state.selectedPlanId);<br>        break;<br>      case SubscriptionStatus.purchaseVerified:<br>        _didFireSuccess = true;<br>        analytics.logSubscriptionSuccess(<br>          planId: state.activePlanId,<br>          transactionId: state.activePurchaseDetails?.purchaseID,<br>        );<br>        break;<br>      case SubscriptionStatus.purchaseRestoreVerified:<br>        _didFireSuccess = true;<br>        analytics.logRestoreSuccess(planId: state.activePlanId);<br>        break;<br>      case SubscriptionStatus.duplicatePurchase:<br>        analytics.logPurchaseDuplicate(message: state.failureMessage);<br>        break;<br>      case SubscriptionStatus.noRestoreAvailable:<br>        analytics.logRestoreEmpty();<br>        break;<br>      case SubscriptionStatus.error:<br>        analytics.logSubscriptionFailed(reason: state.failureMessage);<br>        break;<br>      default:<br>        break;<br>    }<br>  }</pre><pre>  @override<br>  Widget build(BuildContext context) {<br>    return BlocListener&lt;SubscriptionBloc, SubscriptionState&gt;(<br>      listenWhen: (previous, current) =&gt;<br>          previous.status != current.status ||<br>          previous.selectedPlanId != current.selectedPlanId,<br>      listener: (_, state) =&gt; _handle(state),<br>      child: widget.child,<br>    );<br>  }<br>}</pre><p>This pattern makes analytics more trustworthy because events are tied to actual workflow transitions, not only to user taps.</p><h3>Edge Cases You Should Handle</h3><p>Here is the checklist a production app should not skip.</p><h3>1. User cancels purchase</h3><p>The user closes the payment sheet. Do not show an error as if the app failed. Return to idle state.</p><h3>2. Purchase is pending</h3><p>Some payment methods can stay pending. Show a pending state and wait for confirmation.</p><h3>3. Purchase succeeds but backend verification fails</h3><p>Save the receipt/token and retry later.</p><h3>4. Backend says duplicate purchase</h3><p>The store subscription may already be linked to another app account. Show a clear message or support path.</p><h3>5. User logs into another app account</h3><p>Do not blindly transfer premium unless your business rules allow it.</p><h3>6. User reinstalls the app</h3><p>Local storage may be gone, but the store subscription still exists. Support restore and profile refresh.</p><h3>7. User buys on another device</h3><p>Your backend or RevenueCat should sync entitlement state across devices.</p><h3>8. Refund or revocation</h3><p>Access should be removed when the store says the transaction is refunded or revoked.</p><h3>9. Grace period</h3><p>When billing fails but the store keeps entitlement active during grace period, your backend should represent that state correctly.</p><h3>10. Account hold or billing retry</h3><p>Do not treat every billing issue as immediate cancellation. Store lifecycle state matters.</p><h3>11. Upgrade or downgrade</h3><p>Changing from monthly to yearly, or personal to family, may require proration/replacement handling.</p><h3>12. Free trial eligibility</h3><p>Eligibility is tied to the store account and subscription configuration, not only your app account.</p><h3>13. Sandbox vs production</h3><p>Do not mix sandbox and production transactions in the same backend logic without storing environment clearly.</p><h3>14. App review</h3><p>Make sure subscriptions are visible, metadata is complete, restore works, and trial terms are clear.</p><h3>15. Paywall copy</h3><p>Always show trial duration, post-trial price, billing period, auto-renewal behavior, and cancellation route clearly.</p><h3>What to Build First</h3><p>For a Flutter subscription funnel in 2026, start with:</p><ol><li>Store products configured correctly in App Store Connect and Play Console.</li><li>A backend endpoint: POST /subscription/verify.</li><li>A backend subscription table.</li><li>Flutter purchase flow with states: idle, purchasing, verifying, success, error, canceled, pending.</li><li>Pending receipt retry.</li><li>Restore purchases.</li><li>Analytics event taxonomy.</li><li>Clear paywall copy.</li><li>Server notifications or RevenueCat webhooks.</li></ol><p>Then decide as a team whether RevenueCat should own part of the subscription lifecycle or whether the backend should own the complete validation flow.</p><h3>Final Takeaway</h3><p>If a backend must validate purchases and update the user as purchased, that backend should remain the final app entitlement source of truth.</p><p>But do not underestimate how much work subscription lifecycle handling requires.</p><p>RevenueCat is worth considering because it gives you a mature subscription layer, entitlements, restore handling, analytics, and webhooks. It can reduce a lot of Apple/Google edge-case work.</p><p>Custom backend validation gives more control. RevenueCat gives more speed and lifecycle abstraction.</p><p>The most production-ready answer is often not “RevenueCat or backend.”</p><p>It is:</p><pre>Use Apple/Google as the payment source of truth.<br>Use RevenueCat or your backend as the subscription lifecycle layer.<br>Use your backend as the app entitlement source of truth.<br>Never trust local app state alone.</pre><p>That is the difference between a subscription button and a production subscription system.</p><h3>Useful References</h3><ul><li><a href="https://www.revenuecat.com/docs/getting-started/installation/flutter">RevenueCat Flutter SDK documentation</a></li><li><a href="https://www.revenuecat.com/docs/integrations/webhooks">RevenueCat webhooks documentation</a></li><li><a href="https://developer.apple.com/help/app-store-connect/manage-subscriptions/set-up-introductory-offers-for-auto-renewable-subscriptions/">Apple: Set up introductory offers for auto-renewable subscriptions</a></li><li><a href="https://developer.apple.com/help/app-store-connect/test-in-app-purchases/overview-of-testing-in-sandbox">Apple: Overview of testing In-App Purchases in sandbox</a></li><li><a href="https://developer.apple.com/documentation/StoreKit/testing-in-app-purchases-with-sandbox">Apple: Testing In-App Purchases with sandbox</a></li><li><a href="https://developer.apple.com/documentation/appstoreserverapi">Apple App Store Server API</a></li><li><a href="https://support.google.com/googleplay/android-developer/answer/6062777">Google Play: Test in-app billing with application licensing</a></li><li><a href="https://support.google.com/googleplay/android-developer/answer/140504">Google Play: Create and manage subscriptions</a></li><li><a href="https://developer.android.com/google/play/billing/lifecycle/subscriptions">Google Play Billing subscription lifecycle</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f7d8633ed60" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Study: My Journey and Observations as a Software Developer]]></title>
            <link>https://medium.com/@muhmmdshabeer/ai-study-my-journey-and-observations-as-a-software-developer-b686827653ca?source=rss-dc9ac9b74141------2</link>
            <guid isPermaLink="false">https://medium.com/p/b686827653ca</guid>
            <dc:creator><![CDATA[Muhammed Shabeer]]></dc:creator>
            <pubDate>Sun, 07 Jun 2026 11:00:32 GMT</pubDate>
            <atom:updated>2026-06-07T11:00:32.108Z</atom:updated>
            <content:encoded><![CDATA[<p>Over the past few years, I have used several AI tools in my software development journey, including ChatGPT, Gemini, Perplexity, Cursor, Claude, and Codex. This article is based on my personal experience and a few observations I have made while working with these tools.</p><p>I am not writing this to say one AI tool is always better than another. Every tool has strengths and weaknesses. The result also depends on the use case, the developer, the quality of the prompt, and how well the developer understands the project.</p><blockquote><em>AI is powerful, but it becomes dangerous when developers stop reviewing, stop learning, and start accepting code blindly.</em></blockquote><h3>How My AI Journey Started</h3><p>The first AI tool I used seriously was ChatGPT. In the beginning, I used it for small but useful software tasks: optimizing small functions, fixing bugs, understanding code, improving logic, and getting help when I was stuck.</p><p>At that stage, the workflow was very controlled. I had to understand the codebase, explain the context, read the answer, review the suggestion, and manually apply the change. Because I was doing the final implementation myself, I naturally had to think about the flow and functionality.</p><p>That helped me become faster, but it still kept me involved in the engineering process.</p><h3>Gemini and Perplexity for Research</h3><p>After ChatGPT, I started using Gemini and Perplexity. From my experience, Perplexity is very strong for research. It is useful when I want to collect information, compare sources, or understand a topic quickly.</p><p>I also noticed that Gemini was sometimes better at fetching latest information compared to ChatGPT, especially for information-based questions. However, when it came to coding-related tasks, I personally found ChatGPT more useful in many situations.</p><p>This is only my experience. Other developers may feel differently depending on what they are building and how they use each tool.</p><h3>Moving to Cursor</h3><p>Later, I started using Cursor. Cursor introduced a different workflow because it can work directly inside the code editor. It has options such as Plan Mode, Ask Before Edit, and automatic editing.</p><p>Plan Mode is useful because it explains the approach before changing the code. This gives the developer a chance to understand the direction, correct the AI if needed, and review the plan before implementation.</p><p>Automatic Edit Mode is both useful and risky. It can save time, but it can also make developers too comfortable. The AI changes files, runs tests, and then reports that everything passed. That sounds good, but it does not always mean the change is correct for the business logic, architecture, edge cases, or production behavior.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*SdFR6rvo29TtXHm8DBOvWg.gif" /></figure><h3>The Biggest Change I Noticed in Developers</h3><p>Earlier, when I used ChatGPT, I had to manually change the code and review everything. With AI-powered editors, the AI can make the change directly. Because of that, I started noticing a different behavior in some developers.</p><p>At first, they review the AI-generated changes carefully. But gradually, when the AI keeps saying the tests passed and the implementation is complete, they start trusting it too much. Over time, they may stop checking the deeper details.</p><p>In production projects, this can become a serious problem.</p><h3>Two Risks I See</h3><p>From what I have seen, there are two main risks when AI is used blindly:</p><ul><li>Developers become lazy about reviewing code and stop checking edge cases.</li><li>Developers use code without fully understanding what it is doing.</li></ul><p>The second risk is more dangerous.</p><p>Software development is not only about writing code. A developer should understand the codebase, architecture, business requirement, performance, scalability, security, testing, and maintainability. This is even more important for senior developers and technical leads.</p><p>AI can help, but it cannot replace the responsibility of understanding the system. If we blindly accept code without knowing what it does, future bugs can become very hard to fix. Sometimes the issue will not appear immediately. It may appear later when the flow becomes bigger, the product grows, or another developer needs to change the same area.</p><h3>You Need Skill to Correct AI</h3><p>One thing I noticed is that AI often agrees when we say something is wrong. But to say something is wrong, the developer must have enough knowledge. If the developer does not understand the code, architecture, or requirement, they may not even know what question to ask.</p><p>This is why developers should continue practicing coding, learning architecture, improving debugging skills, and understanding systems deeply. AI works best when the human using it is also skilled.</p><h3>Claude, Cursor, and Codex</h3><p>I have also used Claude, Cursor, and Codex. I have premium access to all of these tools, so I have spent a lot of time comparing how they behave in real workflows.</p><p>In my experience, Claude is very good for reasoning, explanation, and discussing ideas. It can explain concepts clearly and help think through a problem deeply. But sometimes, when I ask for a small continuous change, it struggles to make the exact iterative update I want.</p><p>Cursor, on the other hand, can sometimes handle small editor-based changes more smoothly because it is directly connected to the codebase and editing flow. I am not sure whether this is because of memory, context management, editor integration, or how the tools are designed.</p><p>Codex is also useful when working in a coding-agent style workflow where it can inspect files, make changes, run checks, and keep track of implementation steps. Again, the value depends on how clearly we guide the tool and how carefully we review the output.</p><h3>Where AI Works Well Depends on the Use Case</h3><p>My current view is that AI works very well for constant, repetitive, predictable, or clearly defined tasks. If the work follows a known pattern, AI can save a lot of human time.</p><p>But this does not mean AI is the right solution for every task. It depends on the use case, the risk, the project stage, and how much human review is needed.</p><p>Good examples are:</p><ul><li>Localization and translations</li><li>Documentation generation</li><li>Pull Request review assistance</li><li>Code formatting</li><li>Boilerplate code generation</li><li>Test case generation</li><li>Static analysis and rule checking</li><li>Finding repeated code patterns</li></ul><p>For example, a team can create a document that defines architecture rules, coding standards, naming conventions, folder structure, and common violations. Then AI can help review Pull Requests against those rules. In this kind of workflow, AI provides value because the rules are clear and repeated.</p><p>But for dynamic business flows, complex product decisions, architecture changes, performance-sensitive areas, and production-critical logic, the situation is different. Developers still need to review carefully, understand the impact, and sometimes write the code manually.</p><h3>A Real Project Lesson</h3><p>In a recent project I worked on, the project had many issues when I joined. The previous developer was skilled and used AI even more than I did. I am not saying he was a bad developer. He was a good developer. But many problems had accumulated because AI-generated changes were trusted too much and not reviewed deeply enough.</p><p>When I took over the project, I reviewed the flow, fixed the issues, stabilized the application, and successfully delivered it. That experience taught me an important lesson: AI can help us move fast, but blind trust can create long-term problems.</p><p>Sometimes we learn these lessons only after mistakes happen. That is part of the journey.</p><h3>When AI-Built Products Grow</h3><p>I also have a friend who built a project with the help of AI. The product received more than one million visits, which is a great achievement. I really appreciate what he built.</p><p>But as the product grew, new problems started appearing. There were UI issues, performance issues, maintainability problems, and areas where the system needed deeper architectural thinking. At that stage, simply asking AI to fix everything was not enough.</p><p>This changed his perspective. Yes, we can create many things using AI. But when a project grows to an enterprise level or becomes more serious, reviewing, maintaining, scaling, and understanding the system becomes much harder.</p><h3>I Am Not Against AI</h3><p>I want to be clear: I am not against AI. I use AI every day. I believe AI is one of the most useful tools developers have today.</p><p>My point is simple: do not take AI-generated code blindly.</p><ul><li>Learn continuously.</li><li>Review the code.</li><li>Understand the implementation.</li><li>Check edge cases.</li><li>Guide the AI with clear context.</li><li>Use AI where it saves time.</li><li>Do manual thinking where the system is complex.</li></ul><p>When a skilled developer works with an intelligent AI tool, the result can be very powerful. But if only the tool is intelligent and the developer is not reviewing or understanding, the result can fail.</p><h3>Conclusion</h3><p>I do not know exactly what the future will look like for humans and AI in software development. AI is a major invention, so naturally there is a lot of hype around it. Maybe the future will change even more, and maybe some parts of software development will become much easier than they are today.</p><p>But based on the AI tools I have used, the projects I have worked on, and the discussions I have had with friends and colleagues, my current belief is that we still need both: human intelligence and artificial intelligence. AI can help us move faster, but human understanding, review, judgment, and ownership are what make the final product useful.</p><p>The goal is not to replace developers. The goal is to help developers move from 1x productivity to 10x productivity while still delivering quality work.</p><p>Use AI where it adds value. Use it for repetitive tasks, research, reviews, documentation, and faster development. But never stop learning how to build software yourself.</p><p>AI should make you stronger as a developer, not weaker.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b686827653ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Dio in Flutter: Clean Architecture for Multiple APIs and Third-Party Integrations]]></title>
            <link>https://medium.com/@muhmmdshabeer/advanced-dio-in-flutter-clean-architecture-for-multiple-apis-and-third-party-integrations-644b43087851?source=rss-dc9ac9b74141------2</link>
            <guid isPermaLink="false">https://medium.com/p/644b43087851</guid>
            <dc:creator><![CDATA[Muhammed Shabeer]]></dc:creator>
            <pubDate>Sat, 06 Jun 2026 08:59:18 GMT</pubDate>
            <atom:updated>2026-06-06T08:59:18.519Z</atom:updated>
            <content:encoded><![CDATA[<p>Most Flutter Dio examples show one client, one token, one API call, and one response. That is useful for learning, but production apps usually need more.</p><p>Not every app needs this setup. Many apps are perfectly fine with one backend and one access token. But sometimes you need to integrate a third-party API independently from your main backend. That third-party API may have its own base URL, access token, timeout requirements, refresh behavior, logging needs, and cache rules.</p><p>When that situation happens, we should not handle each API directly inside widgets. That makes the app hard to maintain. Instead, we should centralize the network setup, keep feature logic separated, and let Bloc handle presentation state.</p><blockquote><em>The goal is not only to call an API. The goal is to build a networking layer that is clean, centralized, testable, and easy to explain.</em></blockquote><h3>Why Does This Matter?</h3><p>Imagine your app already has a normal backend for profile, authentication, settings, and dashboard data. Later, you need to connect an independent third-party service for products, privacy scans, payments, maps, analytics, or identity verification.</p><p>That external service may not behave like your backend. It may require a separate token. It may expire that token differently. It may need a longer timeout. It may have a different retry rule. It may return errors in another shape. You do not want those rules mixed into your normal app API client.</p><p>This is why multiple Dio clients matter. You can keep your main API stable while adding a separate client for the third-party API. Each client gets its own configuration, but the app still uses one clean architecture.</p><h3>What This Demo Covers</h3><ul><li>Clean architecture folder structure</li><li>Centralized dependency injection with get_it</li><li>Bloc-driven presentation state</li><li>Multiple Dio clients</li><li>Separate access tokens per API</li><li>Different timeout policies</li><li>Request, response, error, and retry logs</li><li>Redacted authorization headers</li><li>Token refresh on 401</li><li>Retrying the original request only once</li><li>Repository-level cache fallback</li><li>Safe Dio error mapping into domain failures</li></ul><h3>How the Demo Matches the Architecture</h3><p>The demo screen is intentionally simple, but each button proves one part of the architecture.</p><ul><li><strong>Call APIs</strong> runs the normal flow. Bloc dispatches the request, use cases call repositories, repositories call remote data sources, and Dio clients attach the correct tokens.</li><li><strong>Force 401 retry</strong> expires only the products token. The products interceptor catches the 401, refreshes that token, retries the original request once, and leaves the users API untouched.</li><li><strong>Load from cache</strong> asks the products repository to use cached data when available. This proves cache logic stays in the data layer instead of the widget.</li></ul><p>This is important because the UI should not know how tokens refresh, which Dio client has a longer timeout, or whether products came from cache or remote API. The UI only sends an event and renders state.</p><h3>Clean Architecture First</h3><p>The project is split into layers so every file has a clear responsibility.</p><pre>lib/<br>  app/<br>    bootstrap.dart<br>    di/<br>      injection_container.dart<br>      core_injection.dart<br>      datasources_injection.dart<br>      repositories_injection.dart<br>      usecases_injection.dart<br>      blocs_injection.dart</pre><pre>  core/<br>    network/<br>    storage/<br>    error/</pre><pre>  features/<br>    profile/<br>      data/<br>      domain/<br>    products/<br>      data/<br>      domain/<br>    api_demo/<br>      presentation/<br>        bloc/<br>        screens/<br>        widgets/</pre><p>The meaning is simple:</p><ul><li>core contains reusable infrastructure such as Dio, logging, token store, cache, and failures.</li><li>data contains models, data sources, and repository implementations.</li><li>domain contains entities, repository contracts, and use cases.</li><li>presentation contains Bloc, screens, and widgets.</li><li>app/di centralizes dependency setup.</li></ul><h3>Keep main.dart Small</h3><p>main.dart should not manually create every Dio client, repository, use case, and Bloc. It should start the app.</p><pre>Future&lt;void&gt; main() async {<br>  await bootstrap();<br>  runApp(const MyApp());<br>}</pre><p>bootstrap() initializes Flutter and registers dependencies:</p><pre>Future&lt;void&gt; bootstrap() async {<br>  WidgetsFlutterBinding.ensureInitialized();<br>  await setupDependencies();<br>}</pre><h3>Centralize Dependency Injection with get_it</h3><p>The dependency container is grouped like a real app:</p><pre>final sl = GetIt.instance;</pre><pre>Future&lt;void&gt; setupDependencies() async {<br>  await setupCore(sl);<br>  await setupDataSources(sl);<br>  await setupRepositories(sl);<br>  await setupUseCases(sl);<br>  await setupBlocs(sl);<br>}</pre><p>The registration order matters. Core services come first. Data sources need core services. Repositories need data sources. Use cases need repositories. Bloc needs use cases.</p><h3>Core Registration</h3><pre>Future&lt;void&gt; setupCore(GetIt sl) async {<br>  sl.registerLazySingleton&lt;InMemoryTokenStore&gt;(<br>    () =&gt; InMemoryTokenStore()<br>      ..appToken = &#39;demo-app-token&#39;<br>      ..productsToken = &#39;expired-products-token&#39;,<br>  );</pre><pre>  sl.registerLazySingleton&lt;ApiClientFactory&gt;(<br>    () =&gt; ApiClientFactory(<br>      tokenStore: sl&lt;InMemoryTokenStore&gt;(),<br>      appAdapter: sl&lt;FakeBackendAdapter&gt;(),<br>      productsAdapter: sl&lt;FakeBackendAdapter&gt;(),<br>    ),<br>  );</pre><pre>  sl.registerLazySingleton&lt;Dio&gt;(<br>    () =&gt; sl&lt;ApiClientFactory&gt;().usersApi(),<br>    instanceName: &#39;usersDio&#39;,<br>  );</pre><pre>  sl.registerLazySingleton&lt;Dio&gt;(<br>    () =&gt; sl&lt;ApiClientFactory&gt;().productsApi(),<br>    instanceName: &#39;productsDio&#39;,<br>  );<br>}</pre><p>Named Dio registrations are important because this app has more than one Dio client.</p><h3>Bloc for Presentation State</h3><p>The screen does not own API logic. It dispatches events and renders state.</p><pre>context.read&lt;ApiDemoBloc&gt;().add(const ApiDemoCallApisRequested());<br>context.read&lt;ApiDemoBloc&gt;().add(const ApiDemoForce401RetryRequested());<br>context.read&lt;ApiDemoBloc&gt;().add(const ApiDemoLoadFromCacheRequested());</pre><p>The Bloc owns:</p><ul><li>loading state</li><li>failure state</li><li>profile data</li><li>product data</li><li>product source: remote refresh or cache allowed</li><li>products token</li><li>token refresh count</li></ul><p>The widget only renders ApiDemoState. That makes the screen easier to test and easier to maintain.</p><h3>Multiple Dio Clients</h3><p>The app uses two clients:</p><ul><li><strong>Users API:</strong> app token, short timeout.</li><li><strong>Products API:</strong> products token, longer timeout, refresh and retry.</li></ul><pre>class ApiClientFactory {<br>  static const usersConnectTimeout = Duration(seconds: 5);<br>  static const usersReceiveTimeout = Duration(seconds: 10);<br>  static const productsConnectTimeout = Duration(seconds: 20);<br>  static const productsReceiveTimeout = Duration(seconds: 45);</pre><pre>  Dio usersApi() {<br>    final dio = Dio(BaseOptions(<br>      baseUrl: ApiBase.usersApi,<br>      connectTimeout: usersConnectTimeout,<br>      receiveTimeout: usersReceiveTimeout,<br>    ));</pre><pre>    dio.interceptors.addAll([<br>      AppApiInterceptor(_tokenStore),<br>      ApiLogInterceptor(&#39;USERS_API&#39;),<br>    ]);<br>    return dio;<br>  }</pre><pre>  Dio productsApi() {<br>    final dio = Dio(BaseOptions(<br>      baseUrl: ApiBase.productsApi,<br>      connectTimeout: productsConnectTimeout,<br>      receiveTimeout: productsReceiveTimeout,<br>    ));</pre><pre>    final retryClient = Dio(BaseOptions(<br>      connectTimeout: productsConnectTimeout,<br>      receiveTimeout: productsReceiveTimeout,<br>    ));</pre><pre>    retryClient.interceptors.add(ApiLogInterceptor(&#39;PRODUCTS_API_RETRY&#39;));</pre><pre>    dio.interceptors.addAll([<br>      ProductsApiInterceptor(tokenStore: _tokenStore, retryClient: retryClient),<br>      ApiLogInterceptor(&#39;PRODUCTS_API&#39;),<br>    ]);<br>    return dio;<br>  }<br>}</pre><p>This is the main idea: every API can have its own base URL, token, timeout, interceptors, logger, and retry behavior.</p><h3>Separate Tokens</h3><p>The users API uses appToken. The products API uses productsToken. In the demo, tokens are stored in memory so the flow is easy to see.</p><pre>class InMemoryTokenStore {<br>  String? appToken;<br>  String? productsToken;<br>  int refreshCount = 0;</pre><pre>  Future&lt;String?&gt; getAppToken() async =&gt; appToken;<br>  Future&lt;String?&gt; getProductsToken() async =&gt; productsToken;</pre><pre>  Future&lt;void&gt; expireProductsToken() async {<br>    productsToken = &#39;expired-products-token&#39;;<br>  }</pre><pre>  Future&lt;void&gt; refreshProductsToken() async {<br>    refreshCount++;<br>    await Future&lt;void&gt;.delayed(const Duration(milliseconds: 200));<br>    productsToken = &#39;fresh-products-token&#39;;<br>  }<br>}</pre><p>In production, this should be replaced with secure storage and a real refresh endpoint.</p><h3>401 Refresh and Retry</h3><p>The products API starts with an expired token. When the fake backend returns 401, the interceptor refreshes the token and retries the original request.</p><pre>final alreadyRetried = err.requestOptions.extra[&#39;retry&#39;] == true;<br>final shouldRefresh = err.response?.statusCode == 401 &amp;&amp; !alreadyRetried;</pre><pre>if (!shouldRefresh) {<br>  handler.next(err);<br>  return;<br>}</pre><pre>err.requestOptions.extra[&#39;retry&#39;] = true;</pre><pre>await _refreshTokenSingleFlight();</pre><pre>final newToken = await _tokenStore.getProductsToken();<br>final options = err.requestOptions;<br>final retryHeaders = Map&lt;String, dynamic&gt;.from(options.headers);<br>retryHeaders[&#39;Authorization&#39;] = &#39;Bearer $newToken&#39;;</pre><pre>final response = await _retryClient.request&lt;dynamic&gt;(<br>  options.uri.toString(),<br>  data: options.data,<br>  queryParameters: options.queryParameters,<br>  options: Options(<br>    method: options.method,<br>    headers: retryHeaders,<br>    contentType: options.contentType,<br>    responseType: options.responseType,<br>  ),<br>);</pre><pre>handler.resolve(response);</pre><p>There are three safety rules:</p><ol><li>Retry only once using extra[&#39;retry&#39;].</li><li>Use a single-flight refresh so multiple requests do not refresh the token at the same time.</li><li>Preserve the original request method, body, query params, headers, content type, and response type.</li></ol><h3>Request and Response Logs</h3><p>The logger prints requests, responses, errors, and retry lifecycle. Authorization headers are redacted.</p><pre>[DIO] [PRODUCTS_API] REQUEST GET https://dummyjson.com/products<br>[DIO] [PRODUCTS_API] Headers: {<br>  &quot;Authorization&quot;: &quot;Bearer expi...oken&quot;<br>}<br>[DIO] [PRODUCTS_API_AUTH] TOKEN_FAILURE 401 https://dummyjson.com/products<br>[DIO] [PRODUCTS_API_AUTH] REFRESH_START productsToken<br>[DIO] [PRODUCTS_API_AUTH] REFRESH_SUCCESS productsToken=fres...oken<br>[DIO] [PRODUCTS_API_AUTH] RETRY_START GET https://dummyjson.com/products<br>[DIO] [PRODUCTS_API_RETRY] RESPONSE 200 https://dummyjson.com/products<br>[DIO] [PRODUCTS_API_AUTH] RETRY_RESOLVED 200 https://dummyjson.com/products</pre><p>This log tells the full story: expired token, 401, refresh, retry, and success.</p><h3>Cache API Response in the Repository</h3><p>Cache logic should not live in the screen. The repository decides whether to return cached data or call remote data.</p><pre>Future&lt;Either&lt;Failure, List&lt;ProductEntity&gt;&gt;&gt; fetchProducts({<br>  bool forceRefresh = false,<br>}) async {<br>  if (!forceRefresh) {<br>    final cached = await _local.getCachedProducts();<br>    if (cached != null &amp;&amp; cached.isNotEmpty) {<br>      return Right(cached.map((model) =&gt; model.toEntity()).toList());<br>    }<br>  }</pre><pre>  return safeApiCall(() async {<br>    final remoteModels = await _remote.fetchProducts();<br>    await _local.cacheProducts(remoteModels);<br>    return remoteModels.map((model) =&gt; model.toEntity()).toList();<br>  });<br>}</pre><p>In the UI, <strong>Call APIs</strong> writes products into cache. <strong>Load from cache</strong> reads the saved products and skips the products API call.</p><h3>Safe Error Mapping</h3><p>The UI should not deal with raw DioException. The repository converts errors into domain failures such as:</p><ul><li>NetworkFailure</li><li>TokenFailure</li><li>ClientFailure</li><li>ServerFailure</li></ul><p>The Bloc receives a clean Failure object and the screen simply renders it.</p><h3>What Changes in Production?</h3><ul><li>Replace InMemoryTokenStore with secure storage or an auth service.</li><li>Replace FakeBackendAdapter with real HTTP.</li><li>Replace the fake refresh method with a real refresh endpoint.</li><li>Keep token redaction in logs.</li><li>Disable console logs in release or send sanitized logs to a logging service.</li><li>Remove <strong>Force 401 retry</strong> from production UI or keep it debug-only.</li><li>Replace in-memory cache with Hive, Isar, SQLite, SharedPreferences, or another real cache layer.</li></ul><h3>The Main Lesson</h3><p>The advanced part is not only the Dio interceptor. The advanced part is the whole system working together:</p><ul><li>Clean architecture separates responsibilities.</li><li>get_it centralizes object creation.</li><li>Bloc owns presentation state.</li><li>Dio clients are configured per API.</li><li>Interceptors attach the correct token.</li><li>Token failure refreshes and retries safely.</li><li>Repositories hide cache and remote decisions.</li><li>Safe API calls protect the UI from raw Dio exceptions.</li><li>Logs explain what happened without leaking secrets.</li></ul><p>Once this structure is in place, adding another API becomes much easier. You create another Dio client, another token strategy if needed, another data source, another repository, and register everything centrally.</p><p>That is the real benefit: the networking layer becomes understandable, testable, and ready to grow.</p><h3>Conclusion</h3><p>This setup is useful when your Flutter app grows beyond one simple backend. You may not need separate Dio clients, separate tokens, retry handling, cache, and custom timeouts in every project. But when you integrate an independent third-party API, this structure gives you a clean way to handle that complexity without mixing network rules into widgets.</p><p>The final architecture combines clean architecture, centralized get_it registration, Bloc state management, Dio interceptors, safe retry, cache, logging, and failure mapping. Each part has a clear responsibility, so the project stays easier to understand as it grows.</p><h3>Source Code</h3><p>You can find the complete project on GitHub:</p><p><a href="https://github.com/meahdev/advanced_dio_with_clean_architecture"><strong>github.com/meahdev/advanced_dio_with_clean_architecture</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=644b43087851" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When Flutter Secure Storage Fails in Production: Keychain, Keystore, Crashlytics, and Safe Recovery]]></title>
            <link>https://medium.com/@muhmmdshabeer/when-flutter-secure-storage-fails-in-production-keychain-keystore-crashlytics-and-safe-recovery-788b2344124e?source=rss-dc9ac9b74141------2</link>
            <guid isPermaLink="false">https://medium.com/p/788b2344124e</guid>
            <dc:creator><![CDATA[Muhammed Shabeer]]></dc:creator>
            <pubDate>Sat, 30 May 2026 10:47:04 GMT</pubDate>
            <atom:updated>2026-05-30T10:47:04.833Z</atom:updated>
            <content:encoded><![CDATA[<p>A real-world Flutter pattern for handling auth tokens safely when iOS Keychain or Android Keystore does not behave the way your happy-path code expects.</p><p>Most Flutter apps treat secure storage as a simple key-value box:</p><pre>await storage.write(key: &#39;token&#39;, value: token);<br>final token = await storage.read(key: &#39;token&#39;);</pre><p>That is fine for demos.</p><p>In production, secure storage is not always that calm.</p><p>On iOS, Keychain data can survive app reinstall. On Android, Keystore-backed values can become unreadable after reinstall, OS upgrade, device restore, or key invalidation. Sometimes reads throw PlatformException. Sometimes the real native reason is buried inside details. Sometimes the app starts in the background while the device is locked.</p><p>If this happens in an authentication flow, a small storage issue can become a crash, a stuck splash screen, or a user who appears logged in after reinstall.</p><p>This article walks through a production pattern I use in Flutter apps to make secure storage safer:</p><ul><li>Clear stale Keychain data on first launch after install</li><li>Catch Keychain/Keystore platform failures</li><li>Report non-fatal storage issues to Crashlytics</li><li>Return safe fallbacks instead of crashing the app</li><li>Separate sensitive and non-sensitive storage clearly</li></ul><p>The goal is not to hide errors. The goal is to make the app recover while still giving engineering enough observability to fix real issues.</p><h3>The Problem</h3><p>Secure storage is usually used for data like:</p><ul><li>Auth tokens</li><li>User IDs</li><li>OAuth credentials</li><li>Refresh tokens</li><li>Pending payment receipts</li></ul><p>In a production app, I usually keep sensitive values behind a small wrapper around flutter_secure_storage.</p><p>Non-sensitive flags live in SharedPreferences through a separate wrapper.</p><p>That separation matters.</p><p>For example, an auth token belongs in secure storage. But a flag like is_first_install can live in local storage because it is not secret. We can use that non-sensitive flag to decide whether secure storage needs cleanup during bootstrap.</p><h3>Secure Storage Wrapper</h3><p>Here is the central wrapper:</p><pre>class AppSecureStorage {<br>  static final AppSecureStorage _instance = AppSecureStorage._internal();</pre><pre>  static const FlutterSecureStorage _storage = FlutterSecureStorage(<br>    iOptions: IOSOptions(<br>      accessibility: KeychainAccessibility.unlocked_this_device,<br>    ),<br>  );</pre><pre>  factory AppSecureStorage() =&gt; _instance;</pre><pre>  AppSecureStorage._internal();<br>}</pre><p>The wrapper gives the app one place to control secure storage behavior.</p><p>This is important because you do not want every feature making its own decision about how to handle Keychain or Keystore failures.</p><p>Auth, subscriptions, onboarding, and API clients should all go through the same storage policy.</p><h3>Why iOS Reinstall Is Tricky</h3><p>On iOS, Keychain values may survive app uninstall/reinstall.</p><p>That can be surprising.</p><p>Imagine this flow:</p><ol><li>User installs the app.</li><li>User logs in.</li><li>App stores token in Keychain.</li><li>User deletes the app.</li><li>User reinstalls the app.</li><li>The old token may still be available.</li></ol><p>From the user’s perspective, reinstalling should feel clean.</p><p>So during app startup, I use a local first-install flag to decide whether secure storage should be wiped:</p><pre>Future&lt;void&gt; clearAllIfFirstInstall() async {<br>  final appLocalStorage = sl&lt;AppLocalStorage&gt;();<br>  final isFirstInstall =<br>      appLocalStorage.getBool(StorageKeys.isFirstInstall) ?? true;</pre><pre>  if (isFirstInstall) {<br>    try {<br>      await _storage.deleteAll();<br>    } on PlatformException catch (e) {<br>      debugPrint(&#39;[AppSecureStorage] deleteAll failed: ${e.code}&#39;);<br>    }</pre><pre>    await appLocalStorage.setBool(StorageKeys.isFirstInstall, false);<br>  }<br>}</pre><p>The logic is simple:</p><ul><li>If the local storage flag says this is the first launch after install, delete all secure storage values.</li><li>Then mark first install as false.</li><li>If delete fails, do not crash startup.</li></ul><p>This protects users from accidentally inheriting stale tokens from a previous install.</p><h3>Where This Runs in App Startup</h3><p>The cleanup happens during bootstrap:</p><pre>await sl&lt;AppLocalStorage&gt;().init();<br>await sl&lt;AppSecureStorage&gt;().clearAllIfFirstInstall();</pre><p>This order matters.</p><p>AppLocalStorage must be initialized before reading the first-install flag. Only after that should secure storage cleanup run.</p><h3>The Read Path Must Never Crash the App</h3><p>Reading secure storage is more dangerous than it looks.</p><p>On Android, a value may exist but fail during decryption if the Keystore key is no longer valid. In that case, treating secure storage as a normal map can crash the app during login, splash validation, or API token injection.</p><p>The safer approach is:</p><pre>Future&lt;String?&gt; read({required String key}) async {<br>  try {<br>    return await _storage.read(key: key);<br>  } on PlatformException catch (e, stack) {<br>    _logSecureStorageFailure(&#39;read&#39;, key, e, stack);</pre><pre>    try {<br>      await _storage.deleteAll();<br>    } on PlatformException catch (_) {}</pre><pre>    return null;<br>  }<br>}</pre><p>The important decisions:</p><ul><li>Catch only PlatformException here</li><li>Log the native failure</li><li>Clear secure storage because existing encrypted values may be unreadable</li><li>Return null</li></ul><p>Returning null lets the app fall back to the normal unauthenticated path.</p><p>For example, the auth service reads the token like this:</p><pre>Future&lt;String?&gt; getToken() async {<br>  final token = await secureStorage.read(<br>    key: StorageKeys.userTokenKey,<br>  );</pre><pre>  return (token == null || token.isEmpty) ? null : token;<br>}</pre><p>If secure storage fails, getToken() returns null. The app can route the user to login instead of crashing.</p><p>That is a much better failure mode.</p><h3>Write, Delete, and Contains Should Also Be Defensive</h3><p>The same policy applies to writes:</p><pre>Future&lt;void&gt; write({<br>  required String key,<br>  required String value,<br>}) async {<br>  try {<br>    await _storage.write(key: key, value: value);<br>  } on PlatformException catch (e, stack) {<br>    _logSecureStorageFailure(&#39;write&#39;, key, e, stack);<br>  }<br>}</pre><p>Deletes:</p><pre>Future&lt;void&gt; delete({required String key}) async {<br>  try {<br>    await _storage.delete(key: key);<br>  } on PlatformException catch (e, stack) {<br>    _logSecureStorageFailure(&#39;delete&#39;, key, e, stack);<br>  }<br>}</pre><p>And existence checks:</p><pre>Future&lt;bool&gt; containsKey({required String key}) async {<br>  try {<br>    return await _storage.containsKey(key: key);<br>  } on PlatformException catch (e, stack) {<br>    _logSecureStorageFailure(&#39;containsKey&#39;, key, e, stack);<br>    return false;<br>  }<br>}</pre><p>The app treats storage as best-effort infrastructure.</p><p>If it fails, user-facing flows should still recover.</p><h3>Crashlytics Should Get the Native Context</h3><p>Swallowing secure storage errors silently is dangerous.</p><p>You want the app to recover, but you also want to know:</p><ul><li>Which operation failed</li><li>Which logical key failed</li><li>What native error code came back</li><li>How often this happens in release builds</li></ul><p>The wrapper logs failures like this:</p><pre>void _logSecureStorageFailure(<br>  String operation,<br>  String key,<br>  PlatformException e,<br>  StackTrace stack,<br>) {<br>  debugPrint(<br>    &#39;[AppSecureStorage] PlatformException on $operation &#39;<br>    &#39;(key=$key) code=${e.code} message=${e.message} &#39;<br>    &#39;details=${e.details}&#39;,<br>  );</pre><pre>  if (kReleaseMode) {<br>    try {<br>      FirebaseCrashlytics.instance<br>        ..setCustomKey(&#39;secure_storage_op&#39;, operation)<br>        ..setCustomKey(&#39;secure_storage_key&#39;, key)<br>        ..setCustomKey(&#39;secure_storage_code&#39;, e.code);</pre><pre>      FirebaseCrashlytics.instance.recordError(<br>        e,<br>        stack,<br>        fatal: false,<br>        reason: &#39;Secure storage $operation failed&#39;,<br>      );<br>    } catch (_) {<br>      // Logging must never crash the app.<br>    }<br>  }<br>}</pre><p>This gives Crashlytics useful production context while keeping the issue non-fatal.</p><p>That distinction is important.</p><p>A secure storage read failure should not be reported as an app crash if the app recovered by clearing storage and sending the user to login.</p><h3>Separating Sensitive and Non-Sensitive Storage</h3><p>A simple AppLocalStorage wrapper can handle non-sensitive preferences:</p><pre>class AppLocalStorage {<br>  static final AppLocalStorage _instance = AppLocalStorage._internal();</pre><pre>  factory AppLocalStorage() =&gt; _instance;</pre><pre>  SharedPreferences? _prefs;</pre><pre>  AppLocalStorage._internal();</pre><pre>  Future&lt;void&gt; init() async {<br>    _prefs ??= await SharedPreferences.getInstance();<br>  }</pre><pre>  String? getString(String key) =&gt; _prefs?.getString(key);<br>  bool? getBool(String key) =&gt; _prefs?.getBool(key);<br>  int? getInt(String key) =&gt; _prefs?.getInt(key);<br>}</pre><p>This is used for values like:</p><ul><li>First install flags</li><li>Theme preferences</li><li>2FA enabled flags</li><li>Social login flags</li><li>Onboarding helper values</li></ul><p>Sensitive values stay in AppSecureStorage:</p><pre>Future&lt;void&gt; saveToken(String token) async {<br>  await secureStorage.write(<br>    key: StorageKeys.userTokenKey,<br>    value: token,<br>  );<br>}</pre><p>That separation makes the storage model easier to reason about:</p><ul><li>SharedPreferences: app preferences and flow flags</li><li>Secure storage: credentials and sensitive identifiers</li></ul><h3>Recovery Strategy</h3><p>The recovery strategy is intentionally boring:</p><pre>Secure read fails<br>        |<br>        v<br>Log non-fatal Crashlytics event<br>        |<br>        v<br>Clear secure storage<br>        |<br>        v<br>Return null<br>        |<br>        v<br>App behaves like user is logged out</pre><p>This is the behavior most users understand.</p><p>If the app cannot safely read the token, it should not try to pretend the session is valid.</p><p>It should clear the broken state and ask the user to authenticate again.</p><h3>A Note About Background Launches</h3><p>Another real-world case is iOS Keychain access during background launches:</p><pre>// iOS Keychain `errSecInteractionNotAllowed` can happen<br>// when the device is locked during a background launch.</pre><p>This is one of those bugs that rarely shows up in local development.</p><p>The app may launch in the background because of notifications, system events, or OS behavior. If the device is locked, Keychain access can fail depending on accessibility configuration.</p><p>The wrapper uses:</p><pre>IOSOptions(<br>  accessibility: KeychainAccessibility.unlocked_this_device,<br>)</pre><p>That is a conscious security choice: values are only available after the device has been unlocked, and they do not migrate to another device backup.</p><p>The tradeoff is that the app must be ready for access failures.</p><h3>What I Would Avoid</h3><p>I would avoid this:</p><pre>final token = await storage.read(key: &#39;token&#39;);</pre><p>directly inside UI, BLoC, interceptors, or feature code.</p><p>That spreads secure-storage assumptions everywhere.</p><p>Instead, use a wrapper:</p><pre>final token = await authService.getToken();</pre><p>And let AuthService decide how to interpret missing or unreadable secure values.</p><h3>Final Pattern</h3><p>The production pattern is:</p><ol><li>Wrap flutter_secure_storage.</li><li>Run first-install cleanup during bootstrap.</li><li>Catch PlatformException on every secure operation.</li><li>Log native failures as non-fatal Crashlytics events.</li><li>Return safe fallback values.</li><li>Keep sensitive and non-sensitive storage separate.</li><li>Let auth/session logic recover naturally.</li></ol><p>This is not complicated code.</p><p>But it is the kind of defensive code that makes a Flutter app feel production-ready.</p><p>Happy-path storage is easy. Reliable storage is about deciding what happens when the platform says no.</p><h3>Suggested File Structure</h3><p>If you want to use this pattern, this structure works well:</p><pre>lib/<br>  core/<br>    storage/<br>      app_secure_storage.dart<br>      app_local_storage.dart<br>      storage_keys.dart<br>    services/<br>      auth_service.dart<br>  app/<br>    bootstrap.dart</pre><p>The exact names do not matter. What matters is the boundary:</p><ul><li>Secure storage wrapper owns Keychain/Keystore behavior</li><li>Local storage wrapper owns non-sensitive preferences</li><li>Auth service owns session interpretation</li><li>The app startup layer owns startup cleanup</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=788b2344124e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter CI/CD]]></title>
            <link>https://medium.com/@muhmmdshabeer/flutter-ci-cd-5141db57af83?source=rss-dc9ac9b74141------2</link>
            <guid isPermaLink="false">https://medium.com/p/5141db57af83</guid>
            <dc:creator><![CDATA[Muhammed Shabeer]]></dc:creator>
            <pubDate>Fri, 06 Sep 2024 09:15:35 GMT</pubDate>
            <atom:updated>2024-09-06T09:25:54.147Z</atom:updated>
            <content:encoded><![CDATA[<p>In this section, I will explain CI/CD integration using Codemagic. It’s important to note that in real-world projects, Codemagic typically requires a paid subscription, or you’ll need your own DevOps team. Alternatively, tools like Jenkins, GitHub Actions, and many others can be used to achieve similar results, depending on your preferred solution.</p><h3>Codemagic?</h3><p>Codemagic is a mobile-focused continuous integration and delivery (CI/CD) platform that provides DevOps services tailored for mobile development teams.</p><p><strong>CI (Continuous Integration):</strong><br>CI is responsible for automating the build process, running automated tests, and performing other quality checks, such as linting and code formatting.</p><p><strong>CD (Continuous Delivery):</strong><br>At this stage, the app is automatically prepared for deployment. This typically involves creating release builds (e.g., APK, AAB, IPA) and signing them.</p><p><strong>CD (Continuous Deployment):</strong><br>In this stage, the app is automatically deployed to the production environment, such as the App Store, Google Play Store, or a private server, without any manual intervention.</p><p>Go to <a href="https://codemagic.io/login">Codemagic</a> and log in using your GitHub, Bitbucket, or GitLab account. Make sure that your app repository is hosted on one of these platforms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z3Nhooc_YyaK9jjQMxrP5g.png" /></figure><p>Once you’re logged in, you’ll see an option to add your application. From there, you can select your app from the available repositories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nF7ZbRkxxuqmNaLIRaab5w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pAc5Z60aqZJDkX3vhKCG-A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J5g4MUPHzCDh6hGLbowk9Q.png" /></figure><p>Once your app is successfully added to Codemagic, you’ll see several options such as Build, Test, Dependency Caching, and Distribution. Thanks to Codemagic’s user-friendly interface, each option is clearly labeled and easy to understand, so I won’t go into detail as their purposes are quite straightforward.</p><h3>Custom workflow vs Default workflow</h3><p>In <strong>Codemagic</strong>, you can either use a <strong>Default workflow</strong> or set up a <strong>Custom workflow</strong>. Here’s a comparison of both:</p><h4>Default Workflow:</h4><ul><li><strong>Pre-configured steps</strong>: Codemagic offers a pre-defined set of steps for building, testing, and distributing apps. It automatically detects your project type (Flutter, iOS, Android, etc.) and sets up the environment accordingly.</li><li><strong>Simplicity</strong>: This is ideal for those who want a straightforward setup without needing to specify many details. It provides a good out-of-the-box experience.</li><li><strong>Minimal customization</strong>: While you can specify some basic options (like which devices to test on or the distribution platforms), you won’t have granular control over the steps or the environment.</li><li><strong>No configuration file</strong>: You don’t need a codemagic.yaml file, making it easy for users who don’t want to manage a configuration.</li></ul><h4>Custom Workflow:</h4><ul><li><strong>Flexibility</strong>: With a custom workflow, you define every step of the build, test, and deployment processes in a codemagic.yaml file. This allows you to specify commands, environment variables, and integrate more complex setups like custom scripts, multiple stages, and even dependencies.</li><li><strong>Control over environment</strong>: You can control the build environment, dependencies, and even perform advanced setups like caching, or custom notifications. It’s highly customizable to meet specific project needs.</li><li><strong>Customizable build triggers</strong>: You can set specific triggers for builds, such as on pull requests, commits, or scheduled intervals.</li><li><strong>Better for complex projects</strong>: If your project involves multiple build flavors, platforms, or custom deployment needs, the custom workflow offers the necessary flexibility.</li></ul><h3>When to Use Each:</h3><p><strong>Use Default Workflow</strong>:</p><ul><li>For simple Flutter, Android, or iOS apps where the default configuration suffices.</li><li>When you want to quickly set up CI/CD without worrying about customization.</li></ul><p><strong>Use Custom Workflow</strong>:</p><ul><li>For complex projects needing specific build setups (e.g., multiple flavors, different build environments).</li><li>If you need custom scripts, additional dependencies, or advanced testing and deployment options.</li><li>When working with multiple teams and want to set up environments or workflows that align closely with the project’s needs.</li></ul><p><strong>Custom Workflow Example</strong>:</p><p>Create a `codemagic.yaml` file in the root folder</p><pre>workflows:<br>  # Workflow for feature branches<br>  test_and_merge_feature:<br>    name: Test Feature Branch<br>    environment:<br>      flutter: stable<br>    triggering:<br>      events:<br>        - push<br>      branch_patterns:<br>        - pattern: &#39;feature/*&#39;<br>          include: true<br>          source: true<br>    scripts:<br>      - name: Run Unit and Widget Tests<br>        script: flutter test<br>    publishing:<br>      email:<br>        recipients:<br>          - muhmmdshabeer@gmail.com<br><br>  # Workflow for the development branch<br>  test_and_build_development:<br>    name: Test and Build Development Branch<br>    environment:<br>      flutter: stable<br>    triggering:<br>      events:<br>        - push<br>      branch_patterns:<br>        - pattern: &#39;development&#39;<br>          include: true<br>          source: true<br>    scripts:<br>      - name: Run Unit and Widget Tests<br>        script: flutter test<br>      - name: Build Android Debug APK<br>        script: flutter build apk --release<br>      - name: Build iOS Debug IPA<br>        script: flutter build ios --debug --no-codesign<br>    artifacts:<br>      - build/**/outputs/**/*.apk<br>      - build/ios/iphonesimulator/*.app<br>    publishing:<br>      email:<br>        recipients:<br>          - muhmmdshabeer@gmail.com<br><br>  # Workflow for the main branch<br>  build_and_deploy_main:<br>    name: Build and Deploy Main Branch<br>    environment:<br>      flutter: stable<br>    triggering:<br>      events:<br>        - push<br>      branch_patterns:<br>        - pattern: &#39;main&#39;<br>          include: true<br>          source: true<br>    scripts:<br>      - name: Run Unit and Widget Tests<br>        script: flutter test<br>      - name: Build Android Release APK<br>        script: flutter build apk --release<br>      - name: Build iOS Release IPA<br>        script: flutter build ios --release --no-codesign<br>    artifacts:<br>      - build/**/outputs/**/*.apk<br>      - build/ios/ipa/*.ipa<br>    publishing:<br>      email:<br>        recipients:<br>          - muhmmdshabeer@gmail.com</pre><p><strong>test_and_merge_feature</strong></p><ul><li><strong>Purpose:</strong> This workflow ensures that feature branches are tested before being merged to avoid introducing issues into the main codebase.</li><li><strong>Trigger:</strong> Activated on pushes to branches matching feature/*.</li><li><strong>Actions:</strong></li><li>Runs unit and widget tests.</li><li>Sends an email with the results to muhmmdshabeer@gmail.com.</li></ul><p><strong>test_and_build_development</strong></p><ul><li><strong>Purpose:</strong> Focuses on testing and building debug versions from the development branch to ensure changes are validated in a development environment.</li><li><strong>Trigger:</strong> Activated on pushes to the developement branch (note: should be corrected to development).</li><li><strong>Actions:</strong></li><li>Runs unit and widget tests.</li><li>Builds debug APK for Android.</li><li>Builds debug IPA for iOS.</li><li>Collects and stores these files.</li><li>Sends an email with build and test results to muhmmdshabeer@gmail.com.</li></ul><p><strong>build_and_deploy_main</strong></p><ul><li><strong>Purpose:</strong> Handles the final build and deployment of the production-ready app from the main branch.</li><li><strong>Trigger:</strong> Activated on pushes to the main branch.</li><li><strong>Actions:</strong></li><li>Runs unit and widget tests.</li><li>Builds release APK for Android.</li><li>Builds release IPA for iOS.</li><li>Collects and stores these files.</li><li>Sends an email with build results to muhmmdshabeer@gmail.com.</li></ul><h4>Custom Workflow Example: In Summary<strong>:</strong></h4><ul><li><strong>Feature Branches:</strong> Test before merging.</li><li><strong>Development Branch:</strong> Test and build versions.</li><li><strong>Main Branch:</strong> Build and deploy production versions.</li></ul><h4>Conclusion</h4><p>Codemagic is a dedicated CI/CD solution specifically designed for Flutter apps. It enables you to build, test, and publish Flutter apps with minimal configuration. Additionally, you can run builds in controlled environments using custom workflows.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5141db57af83" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Unit Test And Widget Test]]></title>
            <link>https://medium.com/@muhmmdshabeer/flutter-unit-test-and-widget-test-37a51d80c136?source=rss-dc9ac9b74141------2</link>
            <guid isPermaLink="false">https://medium.com/p/37a51d80c136</guid>
            <dc:creator><![CDATA[Muhammed Shabeer]]></dc:creator>
            <pubDate>Mon, 19 Aug 2024 11:16:19 GMT</pubDate>
            <atom:updated>2024-08-19T11:21:15.300Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we’re going to explore both unit and widget testing. However, it’s important to note that writing comprehensive tests can sometimes exceed the estimated development time. This creates a trade-off between thorough testing and meeting tight project deadlines, which is why some companies may choose to skip tests due to the time required to cover all possible cases.</p><p><strong>Why Testing ?</strong></p><ul><li><strong>Early Bug Detection</strong>: Unit and widget tests help catch bugs early in the development process, reducing the cost and effort needed to fix issues later.</li><li><strong>Improved Code Quality</strong>: Writing tests encourages developers to write more modular, maintainable code, leading to better overall code quality.</li><li><strong>Confidence in Refactoring</strong>: With a solid suite of tests, developers can refactor code with confidence, knowing that tests will catch any unintended side effects.</li><li><strong>Faster Development Over Time</strong>: Although writing tests initially takes time, it can speed up development in the long run by reducing manual testing and preventing regressions.</li><li><strong>Documentation of Expected Behavior</strong>: Tests serve as living documentation, making it clear how different parts of the codebase are expected to behave.</li><li><strong>Consistent UI Performance</strong>: Widget tests ensure that UI components behave consistently across different devices and states, enhancing the user experience.</li></ul><p>Before we begin, I will provide an introduction to unit testing, widget testing, and their components.</p><h4><strong>Unit Testing </strong>:</h4><ul><li>Focus on testing small parts of the application in isolation.</li><li>The typical process follows three steps: <strong>Arrange</strong>, <strong>Act</strong>, and <strong>Assert</strong>.</li></ul><p><strong>Testing Lifecycle</strong>:</p><ul><li><strong>Setup</strong>: Executed before every test to prepare the environment.</li><li><strong>SetupAll</strong>: Called once before all tests, used for global setup.</li><li><strong>when</strong>: Used to specify the behavior of a mock method in unit tests, determining what it should return when called with specific arguments.</li><li><strong>except</strong>: Used to specify the behavior of a mock method in unit tests, determining what it should return when called with specific arguments.</li><li><strong>tearDown</strong>: Runs after each test to clean up.</li><li><strong>tearDownAll</strong>: Executed after all tests are completed for global cleanup.</li></ul><p><strong>API Call Testing with Mocking</strong>:</p><ul><li>Use <strong>mocking</strong> to simulate API calls with fake responses.This allows testing of application behavior without making real network requests.</li></ul><h4>Widget Testing :</h4><p>Widget tests focus on the behavior and appearance of UI components, particularly how users interact with the interface. For example, when a user presses a button or performs an action, widget tests ensure that the correct output is produced.</p><ul><li><strong>Pump Widget</strong>: Renders the UI based on the widget you pass in, building and creating a widget tree accordingly.</li><li><strong>pump</strong>: Re-renders the widget tree, causing it to rebuild based on any changes.</li><li><strong>pumpAndSettle</strong>: Waits until all animations and scheduled tasks are complete, ensuring that the UI has stabilized before proceeding with the test.</li><li><strong>runAsync</strong>: Manages asynchronous operations and pending timers, ensuring that all async tasks are completed and handled correctly during the test.</li><li><strong>find.byKey</strong>: Locates a widget using a specific key, allowing you to target and test specific components.</li><li><strong>find.byType</strong>: Finds widgets by their type, useful for identifying all instances of a particular widget in the UI.</li><li><strong>find.byText</strong>: Searches for widgets that display a specific text, useful for validating that the correct text is rendered on the screen.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*ZDxi2fcy81h_sq8ZNclO6w.gif" /></figure><blockquote>To perform unit testing with asynchronous functions, you need to add the `mocktail` dependency to the `pubspec.yaml` file. Be sure to include it under `dev_dependencies`.</blockquote><pre>mocktail:latest version</pre><p>You can check out the `starter_point` branch from [this repository](<a href="https://github.com/meahdev/flutter_unit_widget_test.git">https://github.com/meahdev/flutter_unit_widget_test.git</a>).</p><p>I am using <a href="https://jsonplaceholder.typicode.com/">JSONPlaceholder</a> to retrieve a list of posts. We will perform specific unit tests and widget tests. When writing unit tests, ensure you cover as many possible cases as you can. Also, include tests for screen names with underscores.</p><blockquote>To start, you need to mock the API client to simulate API calls with fake data. This can be done using a mocking library or framework that integrates with your testing setup</blockquote><pre>import &#39;package:flutter_test_sample/network/api_client.dart&#39;;<br>import &#39;package:mocktail/mocktail.dart&#39;;<br><br>class MockClient extends Mock implements ApiClient {}</pre><blockquote>Next, we need to mock the connectivity service to simulate checking the internet connection</blockquote><pre><br>import &#39;package:flutter_test_sample/core/connectivity.dart&#39;;<br>import &#39;package:mocktail/mocktail.dart&#39;;<br><br>class MockConnectivityService extends Mock implements ConnectivityService {}</pre><blockquote>Now, we are going to write unit tests covering all possible cases</blockquote><pre>import &#39;package:flutter_test/flutter_test.dart&#39;;<br>import &#39;package:flutter_test_sample/model/sample_response.dart&#39;;<br>import &#39;package:flutter_test_sample/repository/posts/posts_repository.dart&#39;;<br>import &#39;package:mocktail/mocktail.dart&#39;;<br><br>import &#39;../../mock_client.dart&#39;;<br>import &#39;../../mock_connectivity_service.dart&#39;;<br><br>void main() {<br>  late MockClient mockClient;<br>  late PostsRepository mockRepository;<br>  late MockConnectivityService mockConnectivityService;<br>  setUp(() {<br>    mockClient = MockClient();<br>    mockConnectivityService = MockConnectivityService();<br>    mockRepository = PostsRepository(mockClient);<br>  });<br><br>  test(&quot;API Call Response with internet connection&quot;, () async {<br>    // Arrange<br>    when(() =&gt; mockConnectivityService.checkConnection())<br>        .thenAnswer((_) async =&gt; true);<br><br>    when(() =&gt; mockClient.getPost()).thenAnswer((_) async {<br>      return [<br>        SampleResponse(<br>            id: 1, userId: 1001, body: &quot;Test body&quot;, title: &quot;Test title&quot;)<br>      ];<br>    });<br><br>    // Act<br>    final apiResult = await mockRepository.getPosts();<br>    final response = apiResult.data;<br><br>    // Assert<br>    expect(await mockConnectivityService.checkConnection(), isTrue);<br>    expect(response, isA&lt;List&lt;SampleResponse&gt;&gt;());<br>  });<br><br>  test(&quot;API Call Failure due to no internet connection&quot;, () async {<br>    // Arrange<br>    when(() =&gt; mockConnectivityService.checkConnection())<br>        .thenAnswer((_) async =&gt; false);<br>    final bool isConnected = await mockConnectivityService.checkConnection();<br><br>    // Assert<br>    expect(<br>        isConnected, false); // Ensure this matches your actual implementation<br>  });<br><br>  test(&quot;API Call Failure due to server issue&quot;, () async {<br>    // Arrange<br>    when(() =&gt; mockConnectivityService.checkConnection()).thenAnswer(<br>        (_) async =&gt;<br>            true); // Assuming the server issue occurs even when connected<br><br>    when(() =&gt; mockClient.getPost()).thenAnswer((_) async {<br>      throw Exception(&#39;Failed to fetch master data&#39;);<br>    });<br><br>    // Act<br>    final apiResult = await mockRepository.getPosts();<br><br>    // Assert<br>    expect(apiResult.getException, isA&lt;Exception&gt;());<br>  });<br>}</pre><p>From the above steps, we’ve added all possible cases and declared our mock services, returning mock data as well. Once you run the tests, you will see that all of them have passed.</p><blockquote>Now, we are going to add widget tests to check the behavior of our UI.</blockquote><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_test/flutter_test.dart&#39;;<br>import &#39;package:flutter_test_sample/repository/posts/posts_repository.dart&#39;;<br>import &#39;package:flutter_test_sample/screens/posts/posts_screen.dart&#39;;<br>import &#39;package:mocktail/mocktail.dart&#39;;<br>import &#39;package:flutter_test_sample/model/sample_response.dart&#39;;<br><br>import &#39;../../mock_client.dart&#39;;<br>import &#39;../../mock_connectivity_service.dart&#39;;<br><br>void main() {<br>  late MockClient mockClient;<br>  late PostsRepository mockRepository;<br>  late MockConnectivityService mockConnectivityService;<br>  late List&lt;SampleResponse&gt;? mockItems;<br>  group(&quot;Test - Basic loading and scrolling behavior&quot;, () {<br>    // Set up mock data and services<br>    setUp(() async {<br>      mockClient = MockClient();<br>      mockRepository = PostsRepository(mockClient);<br>      mockConnectivityService = MockConnectivityService();<br>      mockItems = List.generate(<br>          100,<br>          (index) =&gt; SampleResponse(<br>              id: index,<br>              title: &#39;Item $index&#39;,<br>              body: &#39;Item Body $index&#39;,<br>              userId: double.parse(&quot;00$index&quot;)));<br><br>      when(() =&gt; mockClient.getPost()).thenAnswer((invocation) async {<br>        return Future.value(mockItems);<br>      });<br>    });<br>    // Test if the mock service is working as expected<br>    test(&#39;Test - Mock Service&#39;, () async {<br>      expect(await mockClient.getPost(), equals(mockItems));<br>    });<br>    testWidgets(&quot;Test - No internet connection&quot;, (tester) async {<br>      // Use runAsync to handle asynchronous operations and pending timers properly<br>      // This ensures that all async tasks complete and are managed correctly during the test<br>      await tester.runAsync(() async {<br>        // Simulate no internet connection<br>        when(() =&gt; mockConnectivityService.checkConnection())<br>            .thenAnswer((_) async =&gt; false);<br>        await tester.pumpWidget(<br>          MaterialApp(<br>            home: Scaffold(<br>              body: PostsScreen(<br>                repository: mockRepository,<br>                connectivityService: mockConnectivityService,<br>              ),<br>            ),<br>          ),<br>        );<br>        // Verify that the loading indicator is shown initially<br>        expect(find.byType(CircularProgressIndicator), findsOneWidget);<br>        // Simulate the delay to allow the connection check to complete<br>        await tester.pumpAndSettle();<br>        // Verify that the loading indicator is no longer visible<br>        expect(find.byType(CircularProgressIndicator), findsNothing);<br>        // Check that the &quot;No internet connection&quot; snack bar is displayed<br>        expect(find.text(&quot;No internet connection&quot;), findsOneWidget);<br>      });<br>    });<br>    testWidgets(&quot;Test - Loading indicator with internet connection&quot;,<br>        (tester) async {<br>      // Simulate a valid internet connection<br>      when(() =&gt; mockConnectivityService.checkConnection())<br>          .thenAnswer((_) async =&gt; true);<br><br>      // Mock API call<br>      when(() =&gt; mockClient.getPost()).thenAnswer((_) async {<br>        await Future.delayed(const Duration(seconds: 2));<br>        return Future.value(mockItems);<br>      });<br>      await tester.pumpWidget(<br>        MaterialApp(<br>          home: Scaffold(<br>            body: PostsScreen(<br>              repository: mockRepository,<br>              connectivityService: mockConnectivityService,<br>            ),<br>          ),<br>        ),<br>      );<br>      // Verify loading indicator is shown initially<br>      expect(find.byType(CircularProgressIndicator), findsOneWidget);<br>      // Simulate the delay to hide the loader and show the content<br>      await tester.pump(const Duration(seconds: 2));<br>      // Wait for the widget tree to settle<br>      await tester.pumpAndSettle();<br>      // Check that the loading indicator is no longer visible<br>      expect(find.byType(CircularProgressIndicator), findsNothing);<br>      // Ensure the SafeArea is now visible<br>      expect(find.byType(SafeArea), findsOneWidget);<br>      // Ensure the ListView is now visible<br>      expect(find.byType(ListView), findsOneWidget);<br>    });<br>    testWidgets(&#39;Test - Scrolling&#39;, (WidgetTester tester) async {<br>      // Mocking the API response<br>      final mockItems = List.generate(<br>          100,<br>          (index) =&gt; SampleResponse(<br>                id: index,<br>                title: &#39;Item $index&#39;,<br>                body: &#39;Item Body $index&#39;,<br>                userId: double.parse(&quot;00$index&quot;),<br>              ));<br>      when(() =&gt; mockConnectivityService.checkConnection())<br>          .thenAnswer((_) async =&gt; true);<br>      when(() =&gt; mockClient.getPost()).thenAnswer((_) async {<br>        await Future.delayed(const Duration(seconds: 2));<br>        return Future.value(mockItems);<br>      });<br>      await tester.pumpWidget(<br>        MaterialApp(<br>          title: &#39;Flutter Demo&#39;,<br>          theme: ThemeData(<br>            colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),<br>            useMaterial3: true,<br>          ),<br>          home: Scaffold(<br>            body: PostsScreen(<br>              repository: mockRepository,<br>              connectivityService: mockConnectivityService,<br>            ),<br>          ),<br>        ),<br>      );<br>      // Wait for the loading to complete<br>      await tester.pumpAndSettle();<br>      // Check if the ListView is present in the widget tree<br>      final listViewFinder = find.byType(ListView);<br>      expect(listViewFinder, findsOneWidget);<br>      // Check initial items are rendered correctly<br>      expect(find.text(&#39;Item 0&#39;), findsOneWidget);<br>      expect(find.text(&#39;Item 99&#39;), findsNothing);<br>      // Perform a scroll to reveal the last item<br>      await tester.drag(<br>          listViewFinder, const Offset(0, -10000)); // Larger offset<br>      // Wait for any remaining animations and frames<br>      await tester.pumpAndSettle();<br>      // Verify that the last item is now in view<br>      expect(find.text(&#39;Item 99&#39;), findsOneWidget);<br>    });<br>  });<br>}</pre><p>We tested our UI behavior by covering all possible cases. Once you run the tests, you will find that all of them have passed.</p><p>Thank you for your patience. As you can see, we performed these automated test cases on a simple page. For larger projects, it’s important to follow this approach to eliminate bugs and improve productivity. However, it can sometimes take more time than expected due to the complexity of test cases, which is why many companies don’t fully utilize automated testing. I hope you found this helpful. You can find the source code at (<a href="https://github.com/meahdev/flutter_unit_widget_test.git">https://github.com/meahdev/flutter_unit_widget_test.git</a>).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37a51d80c136" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Google Login Without Firebase]]></title>
            <link>https://medium.com/@muhmmdshabeer/flutter-google-login-without-firebase-ea41b9c934c8?source=rss-dc9ac9b74141------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea41b9c934c8</guid>
            <dc:creator><![CDATA[Muhammed Shabeer]]></dc:creator>
            <pubDate>Mon, 15 Jul 2024 09:55:37 GMT</pubDate>
            <atom:updated>2024-07-16T04:21:04.452Z</atom:updated>
            <content:encoded><![CDATA[<p>Google login is typically handled through Firebase, but it’s also possible to achieve this using the Google Developer Console. Here’s a step-by-step guide to set up Google login for your Flutter app using the Google Developer Console.</p><blockquote>To work with Google login, you need to add the `google_sign_in` dependency in the `pubspec.yaml` file.</blockquote><pre>google_sign_in:latest version</pre><h4>Android Setup:</h4><p>Go to <a href="https://console.cloud.google.com/cloud-resource-manager">https://console.cloud.google.com/cloud-resource-manager</a> and create your Android and Web client.after that go to your project android/app/src/main/res/strings.xml and add your web client id.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*k6xonfVy3nFPmr9-riGgRw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*ZKKxuxm1oqnjCjZYi5aNlA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bnx5R6mrIjlGSBxWoSFqEw.png" /></figure><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;resources&gt;<br>    &lt;string name=&quot;default_web_client_id&quot;&gt;{your-web-client-id}&lt;/string&gt;<br>&lt;/resources&gt;</pre><p>To authenticate using the backend, you need to pass the ID token. If you don’t define the web client ID, you won’t receive the ID token.</p><h4>IOS Setup:</h4><p>Go to <a href="https://console.cloud.google.com/cloud-resource-manager">https://console.cloud.google.com/cloud-resource-manager</a> and create your iOS and Web client(there is no need to create the web client again if you have already done so.) and download Google-Service-Info.plist file.</p><p>After opening your project in Xcode, locate your GoogleService-Info.plist file. Copy the reverse client ID from there and paste it into the Info.plist file.</p><pre>&lt;array&gt;<br>        &lt;dict&gt;<br>            &lt;key&gt;CFBundleTypeRole&lt;/key&gt;<br>            &lt;string&gt;Editor&lt;/string&gt;<br>            &lt;key&gt;CFBundleURLSchemes&lt;/key&gt;<br>            &lt;array&gt;<br>                &lt;string&gt;&quot;your reverse client-id&quot;&lt;/string&gt;<br>            &lt;/array&gt;<br>        &lt;/dict&gt;<br>    &lt;/array&gt;</pre><p><strong>note :If you don’t add the reverse client id , the iOS application will crash.</strong></p><p>Once you’ve done that, you can declare the Google login variable:</p><pre>late GoogleSignIn _googleSignIn;<br><br>   @override<br>  void initState() {<br>    super.initState();<br>    //here pass clientId as webclient-id<br>    if(Platform.isAndroid){<br>      _googleSignIn = GoogleSignIn(<br>        clientId:&quot;Your Web client id&quot;,<br>        scopes: [<br>          &quot;email&quot;,<br>        ],<br>      );<br>    }else{<br>      //here pass clientId as ios client-id, serverClientId as webclient-id<br>      _googleSignIn = GoogleSignIn(<br>        clientId: &quot;Your IOS Client id &quot;,<br>        serverClientId: &quot;Your Web client id&quot;,<br>        scopes: [<br>          &quot;email&quot;,<br>        ],<br>      );<br>    }<br>  }</pre><p>In Android, we use the web client ID, and in iOS, we pass both the iOS client ID and the web client ID.</p><pre>Future&lt;void&gt; _handleGoogleSignIn() async {<br>    try {<br>      final GoogleSignInAccount? account = await _googleSignIn.signIn();<br>      if (account != null) {<br>        account.authentication.then((googleKey) {<br>          print(&#39;${googleKey.idToken}&#39;);<br>        });<br>        }}catch(_)<br>        {<br><br>        }<br>      }</pre><p>That’s it. You have successfully implemented Google login in your application.</p><h4>Why Use Both IDs?</h4><p>When you register your application in the Google Developer Console, you generate separate OAuth 2.0 client IDs for different platforms (iOS, Android, and Web). Each client ID is tied to your project and platform-specific configuration.</p><ol><li><strong>Platform-specific Authentication</strong>: Google Sign-In SDKs for Android and iOS use platform-specific client IDs to initiate the sign-in process, ensuring that the request is coming from an authenticated source.</li><li><strong>Token Verification</strong>: The web client ID is used to verify the authentication token on the server side, regardless of the platform. This ensures that the token is valid and hasn’t been tampered with.</li></ol><p>Thank you for your cooperation as we walked through this process together. I trust it provided valuable insights. This guide outlines the steps to implement Google login without relying on Firebase, offering an alternative approach for integrating Google authentication into your Flutter application.</p><p>To get started, you can access the project’s source code on GitHub at this link: <a href="https://github.com/meahdev/flutter-google-login-sample.git">https://github.com/meahdev/flutter-google-login-sample.git</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea41b9c934c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Dependency Injection]]></title>
            <link>https://medium.com/@muhmmdshabeer/flutter-dependency-injection-d6153d5a7b3e?source=rss-dc9ac9b74141------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6153d5a7b3e</guid>
            <dc:creator><![CDATA[Muhammed Shabeer]]></dc:creator>
            <pubDate>Tue, 09 Jul 2024 09:42:40 GMT</pubDate>
            <atom:updated>2024-07-09T09:42:40.974Z</atom:updated>
            <content:encoded><![CDATA[<p>Dependency Injection (DI) is a design pattern that promotes loose coupling and enhances the modularity and testability of code. In Flutter, DI can be implemented using the get_it and injectable packages. While get_it alone can be used for DI, managing a large number of services can become cumbersome. Therefore, combining get_it with injectableprovides a more efficient and manageable approach to DI, allowing for seamless registration and management of dependencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*F3PMXOt5QA0jCoXkO5I00w.gif" /></figure><blockquote><em>To work with DI implementation the following dependencies must be added to the pubspec.yaml file</em></blockquote><pre>  dependencies: <br>  get_it: latest version<br>  injectable:latest version<br><br>  dev_dependencies:<br>  build_runner:<br>  injectable_generator:</pre><blockquote><em>Configure the dependencies</em></blockquote><pre>final getIt= GetIt.instance;<br><br>@InjectableInit(<br>  initializerName: &#39;init&#39;, // default<br>  preferRelativeImports: true, // default<br>  asExtension: true<br>)<br>void configureDependencies() =&gt; getIt.init();</pre><p>Once you have completed the setup, generate the injectable file by running the following command in your terminal:</p><pre>flutter pub run build_runner watch --delete-conflicting-outputs  </pre><p>This command will generate the injectable file, and you will see your registered files when you add a new annotation in any class. Ensure that the build runner code is executed.</p><blockquote><em>Call this method in main.dart file</em></blockquote><pre>/// Passing GetIt instance<br>void main() {<br>  <br>  configureDependencies();<br>  runApp(<br>    const MyApp(),<br>  );<br>}</pre><h3><strong>Use Cases</strong></h3><p><strong>Dependency Injection (DI) with Singletons:</strong></p><ul><li><strong>Description:</strong> Using DI with singletons ensures that only one instance of a class (e.g., API service, local storage, database) is created and reused throughout the application.</li><li><strong>Use Case:</strong> This is useful when you need a single shared instance of a class that maintains state or configuration that should be consistent across the entire application.</li><li><strong>Example:</strong> A singleton for an API service can be beneficial because it maintains a single HTTP client instance, which can manage connection pooling and reuse.</li></ul><p><strong>DI with Lazy Singleton Class:</strong></p><ul><li><strong>Description:</strong> A lazy singleton is created only when it is first needed, which can lead to more efficient use of resources.</li><li><strong>Use Case:</strong> This is especially useful for classes that might not be needed immediately at the application startup but might be required later. It ensures that resources are not wasted on initializing instances that might never be used.</li><li><strong>Example:</strong> If you have a feature that is rarely used, you might not want to initialize its dependencies at the start of the application. Instead, you can initialize them when the feature is accessed for the first time.</li></ul><p><strong>Using Abstract Classes with Injectable Package:</strong></p><ul><li><strong>Description:</strong> Creating an abstract class and then implementing it in other classes can provide a layer of abstraction, making it easier to swap implementations without changing the dependent code. The injectable package can automate the process of registering and resolving these dependencies.</li><li><strong>Use Case:</strong> This approach is valuable when you want to decouple the implementation details from the usage. For instance, you can switch between different API service implementations (e.g., mock service for testing vs. real service for production) without modifying the dependent classes.</li><li><strong>Example:</strong> Define an abstract class ApiService and implement it in MockApiService and RealApiService. Using the injectable package, you can register these implementations and resolve them based on the environment or configuration.</li></ul><h3>Examples</h3><h4>1. Singleton</h4><pre>/// Client class<br>@singleton<br>class ApiClient {<br>  Future&lt;void&gt; getData() async {<br>    print(&#39;got the data&#39;);<br>  }<br>} </pre><p>You can access the ApiClient in the following ways:</p><pre>    ApiClient apiClient1 = getIt&lt;ApiClient&gt;();<br>    ApiClient apiClient2 = getIt&lt;ApiClient&gt;();<br>    ApiClient apiClient3 = ApiClient();<br>    print(&#39;API client ${apiClient1.hashCode} ${apiClient2.hashCode} DI with ${apiClient3.hashCode}&#39;);</pre><p>In this example, apiClient1 and apiClient2 will create the same instance, whereas apiClient3 will create a different instance.</p><h4>2. Using a register module (for third party dependencies)</h4><pre>@module<br>abstract class TestModules{<br>  @lazySingleton<br>  AppStorage get appStorage =&gt;AppStorage();<br><br>  @lazySingleton<br>  Dio get dio =&gt;Dio();<br><br>}</pre><p>You can access the ApiClient like this:</p><pre>    final appStorage1 = getIt&lt;AppStorage&gt;();<br>    final dio1 = getIt&lt;Dio&gt;();</pre><h4>3. Using Lazy singleton class</h4><pre>/// Abstract class<br>abstract class ICounterRepo {<br>  Future&lt;void&gt; getData();<br>}<br></pre><pre>///LazySingleton whenever call this ICounterRepo CounterRepo will trigger<br>@LazySingleton(as: ICounterRepo)<br>class CounterRepo implements ICounterRepo {<br>  @override<br>  Future&lt;void&gt; getData() async {<br>    ApiClient apiClient = getIt&lt;ApiClient&gt;();<br>    apiClient.getData();<br>  }<br>}</pre><pre>///Injectable class<br>@injectable<br>class YourControllerClass {<br>  final ICounterRepo iCounterRepo;<br><br>  YourControllerClass(this.iCounterRepo);<br><br>  Future&lt;void&gt; getData() async {<br>    iCounterRepo.getData();<br>  }<br>}</pre><p>You can access it like this:</p><pre>YourControllerClass(getIt&lt;ICounterRepo&gt;()).getData();</pre><p><strong>Conclusion:</strong></p><p>There are several methods in the injectable package that you can explore freely. You can also implement Dependency Injection (DI) using state management. Ultimately, the approach you choose depends on your specific requirements.</p><p>source code : <a href="https://github.com/meahdev/flutter-dependency-injection.git">https://github.com/meahdev/flutter-dependency-injection.git</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6153d5a7b3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>