<?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 Anwar Safy on Medium]]></title>
        <description><![CDATA[Stories by Anwar Safy on Medium]]></description>
        <link>https://medium.com/@anwarsafy15?source=rss-0bea69ba7004------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*n6Z3oXdx16Pw7jthiS3ynA.jpeg</url>
            <title>Stories by Anwar Safy on Medium</title>
            <link>https://medium.com/@anwarsafy15?source=rss-0bea69ba7004------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 19:56:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anwarsafy15/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[Integrating Digital Wallet Passes in Flutter: A Complete Guide for iOS and Android]]></title>
            <link>https://medium.com/@anwarsafy15/integrating-digital-wallet-passes-in-flutter-a-complete-guide-for-ios-and-android-2645f71d302c?source=rss-0bea69ba7004------2</link>
            <guid isPermaLink="false">https://medium.com/p/2645f71d302c</guid>
            <category><![CDATA[apple-wallet]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[google-wallet]]></category>
            <category><![CDATA[nfc]]></category>
            <dc:creator><![CDATA[Anwar Safy]]></dc:creator>
            <pubDate>Sat, 03 Jan 2026 13:18:20 GMT</pubDate>
            <atom:updated>2026-01-03T13:18:20.158Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*-eU3KClDd22t_eZY3xGXhw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1ll6dD2r2oE5MixJal_w0Q.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qrT2N6rm_xEQrkQgoRc3CA.png" /></figure><p><em>A comprehensive guide to implementing Apple Wallet and Google Wallet integration in your Flutter applications</em></p><h3>Introduction</h3><p>Digital wallets have revolutionized how we store and access important information. From boarding passes to loyalty cards, wallet integration has become a standard feature in modern mobile applications. In this comprehensive guide, we’ll explore how to implement wallet pass functionality in a Flutter application, covering both iOS (Apple Wallet) and Android (Google Wallet) implementations.</p><p>This article is based on a real-world NFC-enabled Flutter application that scans NFC tags, detects user profiles, and allows users to add those profiles to their device’s wallet app.</p><p><strong>What you’ll learn:</strong></p><ul><li>Understanding digital wallet systems on iOS and Android</li><li>Complete Flutter implementation for both platforms</li><li>Server-side pass generation with Node.js/Firebase</li><li>Best practices and common pitfalls to avoid</li><li>Real-world troubleshooting scenarios</li></ul><h3>Table of Contents</h3><ol><li><a href="#1-understanding-digital-wallets">Understanding Digital Wallets</a></li><li><a href="#2-architecture-overview">Architecture Overview</a></li><li><a href="#3-ios-implementation-apple-wallet">iOS Implementation (Apple Wallet)</a></li><li><a href="#4-android-implementation-google-wallet">Android Implementation (Google Wallet)</a></li><li><a href="#5-server-side-pass-generation">Server-Side Pass Generation</a></li><li><a href="#6-complete-integration-flow">Complete Integration Flow</a></li><li><a href="#7-best-practices-and-considerations">Best Practices and Considerations</a></li><li><a href="#8-troubleshooting">Troubleshooting</a></li><li><a href="#9-conclusion">Conclusion</a></li></ol><h3>1. Understanding Digital Wallets</h3><p>Before diving into implementation, let’s understand what we’re building.</p><h3>Apple Wallet (iOS)</h3><p>Apple Wallet (formerly Passbook) is Apple’s digital wallet system that allows users to store passes, tickets, coupons, and cards. Passes are distributed as .pkpass files, which are actually ZIP archives containing:</p><ul><li><strong>pass.json</strong> — The pass data in JSON format</li><li><strong>Images</strong> — icon.png, logo.png, background.png (icon.png is required)</li><li><strong>Signatures and certificates</strong> — For security and validation</li></ul><p><strong>Key characteristics:</strong></p><ul><li>Native integration with iOS</li><li>Supports various pass types (boarding passes, store cards, coupons, etc.)</li><li>Automatic updates and location-based notifications</li><li>Requires Apple Developer account and certificates</li></ul><h3>Google Wallet (Android)</h3><p>Google Wallet (formerly Google Pay Passes API) is Google’s equivalent system for Android devices. It uses the Google Wallet API to create and manage passes stored in the user’s Google Wallet app.</p><p><strong>Key characteristics:</strong></p><ul><li>Cloud-based pass management</li><li>RESTful API for pass creation and updates</li><li>Supports loyalty cards, offers, tickets, and more</li><li>Requires Google Cloud project and service account</li></ul><h3>2. Architecture Overview</h3><p>Our implementation follows a clean architecture pattern with clear separation of concerns:</p><p>┌─────────────────────────────────────────────────────────────┐<br>│ User Interface │<br>│ (Read NFC View — Shows detected profile with button) │<br>└───────────────────────┬─────────────────────────────────────┘<br> │<br> ▼<br>┌─────────────────────────────────────────────────────────────┐<br>│ State Management (Cubit) │<br>│ (NFCCubit — Handles NFC scanning and wallet operations) │<br>└───────────────────────┬─────────────────────────────────────┘<br> │<br> ▼<br>┌─────────────────────────────────────────────────────────────┐<br>│ Wallet Service Layer │<br>│ (WalletPassService — Platform-specific operations) │<br>└───────────────────────┬─────────────────────────────────────┘<br> │<br> ┌───────────┴───────────┐<br> │ │<br> ▼ ▼<br> ┌──────────────┐ ┌──────────────┐<br> │ iOS │ │ Android │<br> │ (PassKit) │ │ (Wallet API) │<br> └──────────────┘ └──────────────┘<br> │ │<br> └───────────┬───────────┘<br> │<br> ▼<br>┌─────────────────────────────────────────────────────────────┐<br>│ Backend Server (Firebase Functions) │<br>│ (Generates .pkpass files for iOS / API calls for Android)│<br>└──────────────────────────────────────────────</p><p><strong>Layer responsibilities:</strong></p><ol><li><strong>UI Layer</strong> — Displays profile information and wallet button</li><li><strong>State Management</strong> — Handles business logic and state updates</li><li><strong>Service Layer</strong> — Platform-specific wallet operations</li><li><strong>Native Layer</strong> — iOS PassKit / Android Wallet API</li><li><strong>Backend</strong> — Pass generation and signing</li></ol><h3>3. iOS Implementation (Apple Wallet)</h3><p>Let’s build the iOS implementation step by step.</p><h3>Step 1: Add Dependencies</h3><p>First, add the necessary packages to your pubspec.yaml:</p><p>dependencies:<br> flutter:<br> sdk: flutter<br> apple_passkit: ^1.3.1<br> http: ^1.2.2</p><p>Run flutter pub get to install the dependencies.</p><h3>Step 2: Create the Wallet Service</h3><p>Create a new file lib/services/wallet_pass_service.dart:</p><pre>import &#39;dart:convert&#39;;<br>import &#39;dart:io&#39;;<br>import &#39;dart:typed_data&#39;;<br>import &#39;package:flutter/foundation.dart&#39;;<br>import &#39;package:flutter/services.dart&#39;;<br>import &#39;package:apple_passkit/apple_passkit.dart&#39;;<br>import &#39;package:http/http.dart&#39; as http;<br>import &#39;../models/profile_model.dart&#39;;<br>import &#39;../constants/app_constants.dart&#39;;<br><br>class WalletPassService {<br>  final ApplePassKit _passKit = ApplePassKit();<br><br>  /// Check if wallet is available (iOS only)<br>  Future&lt;bool&gt; isWalletAvailable() async {<br>    if (!Platform.isIOS) {<br>      return false;<br>    }<br><br>    try {<br>      return await _passKit.isPassLibraryAvailable();<br>    } catch (e) {<br>      debugPrint(&#39;Error checking wallet availability: $e&#39;);<br>      return false;<br>    }<br>  }<br><br>  /// Request pass generation from server<br>  Future&lt;String?&gt; _requestPassFromServer(ProfileModel profile) async {<br>    try {<br>      final url = Uri.parse(<br>        &#39;${AppConstants.firebaseFunctionsBaseUrl}/generate-pass&#39;<br>      );<br><br>      final requestBody = {<br>        &#39;name&#39;: profile.name,<br>        &#39;email&#39;: profile.email ?? &#39;&#39;,<br>        &#39;phone&#39;: profile.phone ?? &#39;&#39;,<br>        &#39;companyName&#39;: profile.companyName ?? &#39;&#39;,<br>        &#39;jobTitle&#39;: profile.jobTitle ?? &#39;&#39;,<br>        &#39;logoImageUrl&#39;: profile.logoImageUrl ?? &#39;&#39;,<br>        &#39;profileImageUrl&#39;: profile.profileImageUrl ?? &#39;&#39;,<br>        &#39;profileUrl&#39;: profile.profileUrl,<br>      };<br><br>      debugPrint(&#39;Requesting pass from server: $url&#39;);<br><br>      final response = await http<br>          .post(<br>            url,<br>            headers: {<br>              &#39;Content-Type&#39;: &#39;application/json&#39;,<br>            },<br>            body: jsonEncode(requestBody),<br>          )<br>          .timeout(<br>            const Duration(seconds: 30),<br>            onTimeout: () {<br>              throw Exception(&#39;Request timeout&#39;);<br>            },<br>          );<br><br>      if (response.statusCode == 200) {<br>        final responseData = jsonDecode(response.body) as Map&lt;String, dynamic&gt;;<br>        final passUrl = responseData[&#39;url&#39;] as String?;<br><br>        if (passUrl != null &amp;&amp; passUrl.isNotEmpty) {<br>          debugPrint(&#39;Pass URL received: $passUrl&#39;);<br>          return passUrl;<br>        }<br>      }<br><br>      debugPrint(&#39;Server returned status: ${response.statusCode}&#39;);<br>      return null;<br>    } catch (e) {<br>      debugPrint(&#39;Error requesting pass from server: $e&#39;);<br>      return null;<br>    }<br>  }<br><br>  /// Download .pkpass file from URL<br>  Future&lt;Uint8List?&gt; _downloadPassFile(String url) async {<br>    try {<br>      debugPrint(&#39;Downloading pass file from: $url&#39;);<br><br>      final response = await http<br>          .get(Uri.parse(url))<br>          .timeout(<br>            const Duration(seconds: 30),<br>            onTimeout: () {<br>              throw Exception(&#39;Download timeout&#39;);<br>            },<br>          );<br><br>      if (response.statusCode == 200) {<br>        debugPrint(<br>          &#39;Pass file downloaded successfully, size: ${response.bodyBytes.length} bytes&#39;<br>        );<br>        return response.bodyBytes;<br>      }<br><br>      debugPrint(&#39;Download failed with status: ${response.statusCode}&#39;);<br>      return null;<br>    } catch (e) {<br>      debugPrint(&#39;Error downloading pass file: $e&#39;);<br>      return null;<br>    }<br>  }<br><br>  /// Add pass to wallet (iOS)<br>  Future&lt;bool&gt; addPassToWallet(ProfileModel profile) async {<br>    if (!Platform.isIOS) {<br>      debugPrint(&#39;Wallet passes are only supported on iOS&#39;);<br>      return false;<br>    }<br><br>    try {<br>      // Check if wallet is available<br>      final isAvailable = await isWalletAvailable();<br>      if (!isAvailable) {<br>        throw Exception(&#39;Apple Wallet is not available on this device&#39;);<br>      }<br><br>      // Check if we can add passes<br>      final canAdd = await _passKit.canAddPasses();<br>      if (!canAdd) {<br>        throw Exception(&#39;Cannot add passes to wallet&#39;);<br>      }<br><br>      // Request pass generation from server<br>      final passUrl = await _requestPassFromServer(profile);<br>      if (passUrl == null) {<br>        throw Exception(&#39;Failed to generate pass on server&#39;);<br>      }<br><br>      // Download the .pkpass file<br>      final passData = await _downloadPassFile(passUrl);<br>      if (passData == null) {<br>        throw Exception(&#39;Failed to download pass file&#39;);<br>      }<br><br>      // Add the pass to wallet<br>      try {<br>        await _passKit.addPass(passData);<br>        debugPrint(&#39;Pass added to wallet successfully&#39;);<br>        return true;<br>      } on PlatformException catch (e) {<br>        debugPrint(<br>          &#39;PlatformException adding pass: ${e.code} - ${e.message}&#39;<br>        );<br><br>        // Check for specific error codes<br>        if (e.code == &#39;invalid&#39; ||<br>            e.message?.contains(&#39;not a valid PKPass&#39;) == true ||<br>            e.message?.contains(&#39;icon.png&#39;) == true) {<br>          throw Exception(<br>            &#39;The pass file is invalid. It may be missing required files like icon.png.&#39;<br>          );<br>        }<br><br>        throw Exception(&#39;Failed to add pass: ${e.message ?? e.code}&#39;);<br>      }<br>    } catch (e) {<br>      debugPrint(&#39;Error adding pass to wallet: $e&#39;);<br>      rethrow;<br>    }<br>  }<br>}<br></pre><p><strong>Key points in this implementation:</strong></p><ol><li><strong>Platform checking</strong> — Always verify we’re on iOS before attempting PassKit operations</li><li><strong>Wallet availability</strong> — Check if the device supports Apple Wallet</li><li><strong>Permission checking</strong> — Verify we can add passes before attempting</li><li><strong>Error handling</strong> — Comprehensive error messages for debugging</li><li><strong>Timeouts</strong> — Network requests have 30-second timeouts to prevent hanging</li></ol><h3>Step 3: Integrate with State Management</h3><p>In your Cubit (or Bloc), add the wallet functionality. Update lib/cubits/nfc_cubit.dart:</p><pre>import &#39;package:flutter_bloc/flutter_bloc.dart&#39;;<br>import &#39;../services/wallet_pass_service.dart&#39;;<br>import &#39;../models/profile_model.dart&#39;;<br>import &#39;../utils/toast_utils.dart&#39;;<br><br>class NFCCubit extends Cubit&lt;NFCState&gt; {<br>  final WalletPassService _walletService = WalletPassService();<br>  BuildContext? _context;<br><br>  NFCCubit() : super(NFCState.initial());<br><br>  void setContext(BuildContext context) {<br>    _context = context;<br>  }<br><br>  /// Add detected profile to wallet<br>  Future&lt;void&gt; addProfileToWallet() async {<br>    if (state.detectedProfile == null) {<br>      return;<br>    }<br><br>    emit(state.copyWith(isLoading: true));<br><br>    try {<br>      final success = await _walletService.addPassToWallet(<br>        state.detectedProfile!<br>      );<br><br>      if (success) {<br>        const successMessage = &#39;Profile added to wallet successfully!&#39;;<br>        ToastUtils.showSuccessToast(_context!, successMessage);<br>      } else {<br>        const errorMessage = &#39;Failed to add to wallet. Please try again.&#39;;<br>        ToastUtils.showErrorToast(_context!, errorMessage);<br>      }<br>    } catch (e) {<br>      String errorMessage;<br><br>      if (e.toString().contains(&#39;icon.png&#39;) ||<br>          e.toString().contains(&#39;not a valid PKPass&#39;)) {<br>        errorMessage = &#39;The pass file is invalid. Missing required icon files.&#39;;<br>      } else if (e.toString().contains(&#39;timeout&#39;)) {<br>        errorMessage = &#39;Request timed out. Please check your connection.&#39;;<br>      } else if (e.toString().contains(&#39;not available&#39;)) {<br>        errorMessage = &#39;Apple Wallet is not available on this device.&#39;;<br>      } else {<br>        errorMessage = &#39;Error: ${e.toString()}&#39;;<br>      }<br><br>      ToastUtils.showErrorToast(_context!, errorMessage);<br>    } finally {<br>      emit(state.copyWith(isLoading: false));<br>    }<br>  }<br>}<br></pre><h3>Step 4: Update UI to Show Add Button</h3><p>In your UI widget, add the “Add to Wallet” button. Update lib/views/read_nfc_view.dart:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_bloc/flutter_bloc.dart&#39;;<br>import &#39;../cubits/nfc_cubit.dart&#39;;<br>import &#39;../widgets/adaptive_button.dart&#39;;<br>import &#39;../widgets/adaptive_card.dart&#39;;<br><br>class ReadNFCView extends StatelessWidget {<br>  const ReadNFCView({Key? key}) : super(key: key);<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return BlocBuilder&lt;NFCCubit, NFCState&gt;(<br>      builder: (context, state) {<br>        return Scaffold(<br>          appBar: AppBar(<br>            title: const Text(&#39;Scan NFC Tag&#39;),<br>          ),<br>          body: SingleChildScrollView(<br>            padding: const EdgeInsets.all(16.0),<br>            child: Column(<br>              crossAxisAlignment: CrossAxisAlignment.stretch,<br>              children: [<br>                // Show profile card if detected<br>                if (state.detectedProfile != null) ...[<br>                  AdaptiveCard(<br>                    color: Theme.of(context).cardColor,<br>                    child: Padding(<br>                      padding: const EdgeInsets.all(16.0),<br>                      child: Column(<br>                        crossAxisAlignment: CrossAxisAlignment.start,<br>                        children: [<br>                          // Profile display<br>                          Row(<br>                            children: [<br>                              // Profile image<br>                              if (state.detectedProfile!.profileImageUrl != null)<br>                                CircleAvatar(<br>                                  radius: 30,<br>                                  backgroundImage: NetworkImage(<br>                                    state.detectedProfile!.profileImageUrl!,<br>                                  ),<br>                                )<br>                              else<br>                                const CircleAvatar(<br>                                  radius: 30,<br>                                  child: Icon(Icons.person, size: 30),<br>                                ),<br>                              const SizedBox(width: 12),<br><br>                              // Profile info<br>                              Expanded(<br>                                child: Column(<br>                                  crossAxisAlignment: CrossAxisAlignment.start,<br>                                  children: [<br>                                    Text(<br>                                      state.detectedProfile!.name,<br>                                      style: const TextStyle(<br>                                        fontSize: 18,<br>                                        fontWeight: FontWeight.bold,<br>                                      ),<br>                                    ),<br>                                    if (state.detectedProfile!.jobTitle != null)<br>                                      Text(<br>                                        state.detectedProfile!.jobTitle!,<br>                                        style: TextStyle(<br>                                          color: Colors.grey[600],<br>                                        ),<br>                                      ),<br>                                    if (state.detectedProfile!.companyName != null)<br>                                      Text(<br>                                        state.detectedProfile!.companyName!,<br>                                        style: TextStyle(<br>                                          color: Colors.grey[600],<br>                                        ),<br>                                      ),<br>                                  ],<br>                                ),<br>                              ),<br>                            ],<br>                          ),<br><br>                          const SizedBox(height: 16),<br><br>                          // Add to Wallet button<br>                          SizedBox(<br>                            width: double.infinity,<br>                            child: AdaptiveButton(<br>                              onPressed: state.isLoading<br>                                  ? null<br>                                  : () =&gt; context<br>                                      .read&lt;NFCCubit&gt;()<br>                                      .addProfileToWallet(),<br>                              style: AdaptiveButtonStyle.filled,<br>                              size: AdaptiveButtonSize.large,<br>                              label: state.isLoading<br>                                  ? &#39;Adding to Wallet...&#39;<br>                                  : &#39;Add to Apple Wallet&#39;,<br>                              icon: state.isLoading<br>                                  ? const SizedBox(<br>                                      width: 20,<br>                                      height: 20,<br>                                      child: CircularProgressIndicator(<br>                                        strokeWidth: 2,<br>                                        valueColor: AlwaysStoppedAnimation&lt;Color&gt;(<br>                                          Colors.white,<br>                                        ),<br>                                      ),<br>                                    )<br>                                  : const Icon(Icons.wallet),<br>                            ),<br>                          ),<br>                        ],<br>                      ),<br>                    ),<br>                  ),<br>                  const SizedBox(height: 16),<br>                ],<br>              ],<br>            ),<br>          ),<br>        );<br>      },<br>    );<br>  }<br>}<br></pre><h3>Step 5: iOS Configuration</h3><p>Add the necessary entitlements to your iOS project.</p><p><strong>ios/Runner/Runner.entitlements:</strong></p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;!DOCTYPE plist PUBLIC &quot;-//Apple//DTD PLIST 1.0//EN&quot; &quot;http://www.apple.com/DTDs/PropertyList-1.0.dtd&quot;&gt;<br>&lt;plist version=&quot;1.0&quot;&gt;<br>&lt;dict&gt;<br>    &lt;key&gt;com.apple.developer.pass-type-identifiers&lt;/key&gt;<br>    &lt;array&gt;<br>        &lt;string&gt;$(TeamIdentifierPrefix)*&lt;/string&gt;<br>    &lt;/array&gt;<br>    &lt;key&gt;com.apple.developer.nfc.readersession.formats&lt;/key&gt;<br>    &lt;array&gt;<br>        &lt;string&gt;NDEF&lt;/string&gt;<br>        &lt;string&gt;TAG&lt;/string&gt;<br>    &lt;/array&gt;<br>&lt;/dict&gt;<br>&lt;/plist&gt;</pre><p><strong>Important:</strong> You’ll also need to configure your Apple Developer account with proper certificates and provisioning profiles for PassKit.</p><h3>4. Android Implementation (Google Wallet)</h3><p>Android implementation requires a different approach using the Google Wallet API and platform channels.</p><h4>Step 1: Add Dependencies:</h4><pre>dependencies:<br>  http: ^1.2.2</pre><p><strong>Note:</strong> There’s no official Flutter package for Google Wallet, so we’ll use platform channels.</p><h4>Step 2: Create Android Wallet Service</h4><p>Update your wallet_pass_service.dart to support Android:</p><pre>import &#39;dart:convert&#39;;<br>import &#39;dart:io&#39;;<br>import &#39;package:flutter/foundation.dart&#39;;<br>import &#39;package:flutter/services.dart&#39;;<br>import &#39;package:http/http.dart&#39; as http;<br>import &#39;../models/profile_model.dart&#39;;<br>import &#39;../constants/app_constants.dart&#39;;<br><br>class WalletPassService {<br>  static const MethodChannel _channel = MethodChannel(&#39;wallet_channel&#39;);<br><br>  /// Check if Google Wallet is available (Android only)<br>  Future&lt;bool&gt; isGoogleWalletAvailable() async {<br>    if (!Platform.isAndroid) {<br>      return false;<br>    }<br><br>    try {<br>      final bool available = await _channel.invokeMethod(&#39;isWalletAvailable&#39;);<br>      return available;<br>    } catch (e) {<br>      debugPrint(&#39;Error checking Google Wallet availability: $e&#39;);<br>      return false;<br>    }<br>  }<br><br>  /// Request Google Wallet pass from server<br>  Future&lt;String?&gt; _requestGoogleWalletPass(ProfileModel profile) async {<br>    try {<br>      final url = Uri.parse(<br>        &#39;${AppConstants.firebaseFunctionsBaseUrl}/generate-google-wallet-pass&#39;<br>      );<br><br>      final requestBody = {<br>        &#39;name&#39;: profile.name,<br>        &#39;email&#39;: profile.email ?? &#39;&#39;,<br>        &#39;phone&#39;: profile.phone ?? &#39;&#39;,<br>        &#39;companyName&#39;: profile.companyName ?? &#39;&#39;,<br>        &#39;jobTitle&#39;: profile.jobTitle ?? &#39;&#39;,<br>        &#39;logoImageUrl&#39;: profile.logoImageUrl ?? &#39;&#39;,<br>        &#39;profileImageUrl&#39;: profile.profileImageUrl ?? &#39;&#39;,<br>        &#39;profileUrl&#39;: profile.profileUrl,<br>      };<br><br>      final response = await http<br>          .post(<br>            url,<br>            headers: {&#39;Content-Type&#39;: &#39;application/json&#39;},<br>            body: jsonEncode(requestBody),<br>          )<br>          .timeout(const Duration(seconds: 30));<br><br>      if (response.statusCode == 200) {<br>        final responseData = jsonDecode(response.body) as Map&lt;String, dynamic&gt;;<br>        return responseData[&#39;saveUrl&#39;] as String?;<br>      }<br><br>      return null;<br>    } catch (e) {<br>      debugPrint(&#39;Error requesting Google Wallet pass: $e&#39;);<br>      return null;<br>    }<br>  }<br><br>  /// Add pass to Google Wallet (Android)<br>  Future&lt;bool&gt; addToGoogleWallet(ProfileModel profile) async {<br>    if (!Platform.isAndroid) {<br>      debugPrint(&#39;Google Wallet is only supported on Android&#39;);<br>      return false;<br>    }<br><br>    try {<br>      // Check if Google Wallet is available<br>      final isAvailable = await isGoogleWalletAvailable();<br>      if (!isAvailable) {<br>        throw Exception(&#39;Google Wallet is not available on this device&#39;);<br>      }<br><br>      // Request pass generation from server<br>      final saveUrl = await _requestGoogleWalletPass(profile);<br>      if (saveUrl == null) {<br>        throw Exception(&#39;Failed to generate Google Wallet pass&#39;);<br>      }<br><br>      // Use the save URL to add pass to Google Wallet<br>      final bool success = await _channel.invokeMethod(<br>        &#39;addToGoogleWallet&#39;,<br>        {&#39;saveUrl&#39;: saveUrl},<br>      );<br><br>      return success;<br>    } catch (e) {<br>      debugPrint(&#39;Error adding pass to Google Wallet: $e&#39;);<br>      rethrow;<br>    }<br>  }<br><br>  /// Platform-agnostic method to add pass to wallet<br>  Future&lt;bool&gt; addPassToWallet(ProfileModel profile) async {<br>    if (Platform.isIOS) {<br>      return addToAppleWallet(profile);<br>    } else if (Platform.isAndroid) {<br>      return addToGoogleWallet(profile);<br>    }<br><br>    throw Exception(&#39;Unsupported platform&#39;);<br>  }<br>}</pre><h4>Step 3: Android Native Implementation</h4><p>Create a Kotlin file for the platform channel.</p><p><strong>android/app/src/main/kotlin/com/example/your_app/WalletChannel.kt:</strong></p><pre>package com.example.your_app<br><br>import android.content.Intent<br>import android.net.Uri<br>import android.util.Log<br>import io.flutter.embedding.engine.FlutterEngine<br>import io.flutter.plugin.common.MethodChannel<br><br>class WalletChannel(private val activity: MainActivity) {<br>    private val CHANNEL = &quot;wallet_channel&quot;<br>    private val TAG = &quot;WalletChannel&quot;<br><br>    fun configureChannel(flutterEngine: FlutterEngine) {<br>        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL)<br>            .setMethodCallHandler { call, result -&gt;<br>                when (call.method) {<br>                    &quot;isWalletAvailable&quot; -&gt; {<br>                        // Check if Google Wallet is installed<br>                        val intent = Intent(Intent.ACTION_VIEW)<br>                        intent.data = Uri.parse(&quot;https://pay.google.com/gp/v/save/&quot;)<br>                        val isAvailable = intent.resolveActivity(activity.packageManager) != null<br>                        <br>                        Log.d(TAG, &quot;Google Wallet available: $isAvailable&quot;)<br>                        result.success(isAvailable)<br>                    }<br>                    <br>                    &quot;addToGoogleWallet&quot; -&gt; {<br>                        val saveUrl = call.argument&lt;String&gt;(&quot;saveUrl&quot;)<br>                        <br>                        if (saveUrl != null) {<br>                            try {<br>                                Log.d(TAG, &quot;Opening Google Wallet with URL: $saveUrl&quot;)<br>                                <br>                                val intent = Intent(Intent.ACTION_VIEW)<br>                                intent.data = Uri.parse(saveUrl)<br>                                activity.startActivity(intent)<br>                                <br>                                result.success(true)<br>                            } catch (e: Exception) {<br>                                Log.e(TAG, &quot;Error opening Google Wallet&quot;, e)<br>                                result.error(&quot;ERROR&quot;, e.message, null)<br>                            }<br>                        } else {<br>                            Log.e(TAG, &quot;saveUrl is null&quot;)<br>                            result.error(&quot;INVALID_ARGUMENT&quot;, &quot;saveUrl is null&quot;, null)<br>                        }<br>                    }<br>                    <br>                    else -&gt; {<br>                        result.notImplemented()<br>                    }<br>                }<br>            }<br>    }<br>}</pre><h4>Step 4: Update MainActivity</h4><p><strong>android/app/src/main/kotlin/com/example/your_app/MainActivity.kt:</strong></p><pre>package com.example.your_app<br><br>import io.flutter.embedding.android.FlutterActivity<br>import io.flutter.embedding.engine.FlutterEngine<br><br>class MainActivity: FlutterActivity() {<br>    private lateinit var walletChannel: WalletChannel<br><br>    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {<br>        super.configureFlutterEngine(flutterEngine)<br>        <br>        // Configure wallet channel<br>        walletChannel = WalletChannel(this)<br>        walletChannel.configureChannel(flutterEngine)<br>    }<br>}</pre><h4>Step 5: Android Manifest Permissions</h4><p><strong>android/app/src/main/AndroidManifest.xml:</strong></p><pre>&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;<br>    &lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt;<br>    <br>    &lt;application<br>        android:label=&quot;Your App&quot;<br>        android:icon=&quot;@mipmap/ic_launcher&quot;&gt;<br>        <br>        &lt;activity<br>            android:name=&quot;.MainActivity&quot;<br>            android:exported=&quot;true&quot;<br>            android:launchMode=&quot;singleTop&quot;<br>            android:theme=&quot;@style/LaunchTheme&quot;<br>            android:configChanges=&quot;orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode&quot;<br>            android:hardwareAccelerated=&quot;true&quot;<br>            android:windowSoftInputMode=&quot;adjustResize&quot;&gt;<br>            <br>            &lt;meta-data<br>              android:name=&quot;io.flutter.embedding.android.NormalTheme&quot;<br>              android:resource=&quot;@style/NormalTheme&quot;<br>              /&gt;<br>            <br>            &lt;intent-filter&gt;<br>                &lt;action android:name=&quot;android.intent.action.MAIN&quot;/&gt;<br>                &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot;/&gt;<br>            &lt;/intent-filter&gt;<br>        &lt;/activity&gt;<br>        <br>        &lt;meta-data<br>            android:name=&quot;flutterEmbedding&quot;<br>            android:value=&quot;2&quot; /&gt;<br>    &lt;/application&gt;<br>&lt;/manifest&gt;</pre><h3>5. Server-Side Pass Generation</h3><p>Now let’s implement the backend for generating wallet passes.</p><h4>iOS Pass Generation (Node.js/Firebase Functions)</h4><p><strong>functions/index.js:</strong></p><pre>/**<br> * Firebase Functions for Wallet Pass Generation<br> * Handles both Apple Wallet (.pkpass) and Google Wallet passes<br> * <br> * Required packages:<br> * npm install firebase-functions firebase-admin<br> * npm install uuid axios archiver sharp<br> * npm install google-auth-library googleapis<br> * npm install node-forge (for signing)<br> */<br><br>const functions = require(&#39;firebase-functions&#39;);<br>const admin = require(&#39;firebase-admin&#39;);<br>const { v4: uuidv4 } = require(&#39;uuid&#39;);<br>const fs = require(&#39;fs&#39;);<br>const path = require(&#39;path&#39;);<br>const archiver = require(&#39;archiver&#39;);<br>const axios = require(&#39;axios&#39;);<br>const sharp = require(&#39;sharp&#39;);<br>const { GoogleAuth } = require(&#39;google-auth-library&#39;);<br>const { google } = require(&#39;googleapis&#39;);<br>const forge = require(&#39;node-forge&#39;);<br><br>// Initialize Firebase Admin<br>admin.initializeApp();<br><br>// ============================================================================<br>// APPLE WALLET PASS GENERATION (.pkpass)<br>// ============================================================================<br><br>/**<br> * Generate Apple Wallet pass (.pkpass) file<br> * <br> * Endpoint: POST /generate-pass<br> * <br> * Request Body:<br> * {<br> *   &quot;name&quot;: &quot;John Doe&quot;,<br> *   &quot;email&quot;: &quot;john@example.com&quot;,<br> *   &quot;phone&quot;: &quot;+1234567890&quot;,<br> *   &quot;companyName&quot;: &quot;Acme Corp&quot;,<br> *   &quot;jobTitle&quot;: &quot;Software Engineer&quot;,<br> *   &quot;logoImageUrl&quot;: &quot;https://example.com/logo.png&quot;,<br> *   &quot;profileImageUrl&quot;: &quot;https://example.com/profile.png&quot;,<br> *   &quot;profileUrl&quot;: &quot;https://example.com/profile/johndoe&quot;<br> * }<br> * <br> * Response:<br> * {<br> *   &quot;url&quot;: &quot;https://storage.googleapis.com/.../.pkpass&quot;,<br> *   &quot;passId&quot;: &quot;uuid&quot;,<br> *   &quot;expiresAt&quot;: &quot;timestamp&quot;<br> * }<br> */<br>exports.generatePass = functions.https.onRequest(async (req, res) =&gt; {<br>  // Enable CORS<br>  res.set(&#39;Access-Control-Allow-Origin&#39;, &#39;*&#39;);<br>  res.set(&#39;Access-Control-Allow-Methods&#39;, &#39;GET, POST, OPTIONS&#39;);<br>  res.set(&#39;Access-Control-Allow-Headers&#39;, &#39;Content-Type, Authorization&#39;);<br><br>  if (req.method === &#39;OPTIONS&#39;) {<br>    res.status(204).send(&#39;&#39;);<br>    return;<br>  }<br><br>  try {<br>    // Extract parameters from request<br>    const {<br>      name,<br>      email,<br>      phone,<br>      logoImageUrl,<br>      profileImageUrl,<br>      companyName,<br>      jobTitle,<br>      profileUrl,<br>    } = req.method === &#39;GET&#39; ? req.query : req.body;<br><br>    // Validate required fields<br>    if (!name || !email) {<br>      return res.status(400).json({<br>        error: &#39;Missing required fields&#39;,<br>        required: [&#39;name&#39;, &#39;email&#39;],<br>      });<br>    }<br><br>    console.log(`Generating pass for: ${name} (${email})`);<br><br>    // Prepare QR code URL<br>    let qrCodeUrl = profileUrl || <br>      `https://yourapp.com/u/${name.toLowerCase().replace(/\s+/g, &#39;-&#39;)}`;<br><br>    if (!qrCodeUrl.startsWith(&#39;http://&#39;) &amp;&amp; !qrCodeUrl.startsWith(&#39;https://&#39;)) {<br>      qrCodeUrl = `https://yourapp.com/u/${qrCodeUrl}`;<br>    }<br><br>    // Generate unique serial number<br>    const serialNumber = uuidv4();<br>    const passId = `pass_${serialNumber}`;<br><br>    // Create pass.json structure<br>    const passData = {<br>      formatVersion: 1,<br>      passTypeIdentifier: process.env.PASS_TYPE_ID || &#39;pass.com.yourcompany.contact&#39;,<br>      organizationName: companyName || &#39;Your Company&#39;,<br>      teamIdentifier: process.env.TEAM_IDENTIFIER || &#39;YOUR_TEAM_ID&#39;,<br>      serialNumber: serialNumber,<br>      description: `${name} - ${jobTitle || &#39;Contact Card&#39;}`,<br>      logoText: companyName || name,<br><br>      // Visual appearance<br>      foregroundColor: &#39;rgb(255, 255, 255)&#39;,<br>      backgroundColor: &#39;rgb(118, 75, 162)&#39;,<br>      labelColor: &#39;rgb(255, 255, 255)&#39;,<br><br>      // QR Code for profile<br>      barcodes: [<br>        {<br>          message: qrCodeUrl,<br>          format: &#39;PKBarcodeFormatQR&#39;,<br>          messageEncoding: &#39;iso-8859-1&#39;,<br>          altText: name,<br>        },<br>      ],<br><br>      // Pass content<br>      generic: {<br>        primaryFields: [<br>          {<br>            key: &#39;name&#39;,<br>            label: &#39;NAME&#39;,<br>            value: name,<br>          },<br>        ],<br>        secondaryFields: jobTitle ? [<br>          {<br>            key: &#39;jobTitle&#39;,<br>            label: &#39;TITLE&#39;,<br>            value: jobTitle,<br>          },<br>        ] : [],<br>        auxiliaryFields: [<br>          ...(companyName ? [{<br>            key: &#39;company&#39;,<br>            label: &#39;COMPANY&#39;,<br>            value: companyName,<br>          }] : []),<br>          {<br>            key: &#39;email&#39;,<br>            label: &#39;EMAIL&#39;,<br>            value: email,<br>          },<br>          ...(phone ? [{<br>            key: &#39;phone&#39;,<br>            label: &#39;PHONE&#39;,<br>            value: phone,<br>          }] : []),<br>        ],<br>        backFields: [<br>          {<br>            key: &#39;profile&#39;,<br>            label: &#39;PROFILE URL&#39;,<br>            value: qrCodeUrl,<br>          },<br>        ],<br>      },<br><br>      // Relevance (optional - for location-based notifications)<br>      relevantDate: new Date().toISOString(),<br>    };<br><br>    // Create temporary directory for pass files<br>    const tempDir = `/tmp/${passId}`;<br>    fs.mkdirSync(tempDir, { recursive: true });<br><br>    console.log(`Created temp directory: ${tempDir}`);<br><br>    // Download and process images<br>    const iconUrl = profileImageUrl || logoImageUrl;<br>    <br>    if (iconUrl) {<br>      console.log(&#39;Downloading and processing icon images...&#39;);<br>      await downloadAndResizeImage(iconUrl, path.join(tempDir, &#39;icon.png&#39;), 29, 29);<br>      await downloadAndResizeImage(iconUrl, path.join(tempDir, &#39;icon@2x.png&#39;), 58, 58);<br>      await downloadAndResizeImage(iconUrl, path.join(tempDir, &#39;icon@3x.png&#39;), 87, 87);<br>    } else {<br>      console.log(&#39;Creating placeholder icon images...&#39;);<br>      await createPlaceholderIcon(path.join(tempDir, &#39;icon.png&#39;), 29);<br>      await createPlaceholderIcon(path.join(tempDir, &#39;icon@2x.png&#39;), 58);<br>      await createPlaceholderIcon(path.join(tempDir, &#39;icon@3x.png&#39;), 87);<br>    }<br><br>    // Download logo if provided<br>    if (logoImageUrl &amp;&amp; logoImageUrl !== iconUrl) {<br>      console.log(&#39;Downloading and processing logo images...&#39;);<br>      await downloadAndResizeImage(logoImageUrl, path.join(tempDir, &#39;logo.png&#39;), 160, 50);<br>      await downloadAndResizeImage(logoImageUrl, path.join(tempDir, &#39;logo@2x.png&#39;), 320, 100);<br>      await downloadAndResizeImage(logoImageUrl, path.join(tempDir, &#39;logo@3x.png&#39;), 480, 150);<br>    }<br><br>    // Write pass.json<br>    console.log(&#39;Writing pass.json...&#39;);<br>    fs.writeFileSync(<br>      path.join(tempDir, &#39;pass.json&#39;),<br>      JSON.stringify(passData, null, 2)<br>    );<br><br>    // Create manifest.json (required for signing)<br>    console.log(&#39;Creating manifest...&#39;);<br>    const manifest = await createManifest(tempDir);<br>    fs.writeFileSync(<br>      path.join(tempDir, &#39;manifest.json&#39;),<br>      JSON.stringify(manifest, null, 2)<br>    );<br><br>    // Sign the pass (if certificates are available)<br>    if (process.env.PASS_CERTIFICATE &amp;&amp; process.env.PASS_PRIVATE_KEY) {<br>      console.log(&#39;Signing pass...&#39;);<br>      await signPass(tempDir);<br>    } else {<br>      console.warn(&#39;Pass signing skipped - certificates not configured&#39;);<br>    }<br><br>    // Create .pkpass file (ZIP archive)<br>    console.log(&#39;Creating .pkpass archive...&#39;);<br>    const passPath = path.join(tempDir, `${passId}.pkpass`);<br>    await createPassArchive(tempDir, passPath);<br><br>    // Upload to Firebase Storage<br>    console.log(&#39;Uploading to Firebase Storage...&#39;);<br>    const bucket = admin.storage().bucket();<br>    const passFileName = `passes/${passId}.pkpass`;<br>    <br>    await bucket.upload(passPath, {<br>      destination: passFileName,<br>      metadata: {<br>        contentType: &#39;application/vnd.apple.pkpass&#39;,<br>        metadata: {<br>          name: name,<br>          email: email,<br>          createdAt: new Date().toISOString(),<br>        },<br>      },<br>    });<br><br>    // Get signed download URL (expires in 1 hour)<br>    const file = bucket.file(passFileName);<br>    const [url] = await file.getSignedUrl({<br>      action: &#39;read&#39;,<br>      expires: Date.now() + 3600 * 1000, // 1 hour<br>    });<br><br>    console.log(`Pass generated successfully: ${passId}`);<br><br>    // Clean up temporary files<br>    fs.rmSync(tempDir, { recursive: true, force: true });<br><br>    // Return response<br>    res.json({<br>      success: true,<br>      url: url,<br>      passId: passId,<br>      serialNumber: serialNumber,<br>      expiresAt: new Date(Date.now() + 3600 * 1000).toISOString(),<br>    });<br><br>  } catch (error) {<br>    console.error(&#39;Error generating pass:&#39;, error);<br>    res.status(500).json({<br>      success: false,<br>      error: &#39;Failed to generate pass&#39;,<br>      message: error.message,<br>      details: error.stack,<br>    });<br>  }<br>});<br><br>// ============================================================================<br>// GOOGLE WALLET PASS GENERATION<br>// ============================================================================<br><br>/**<br> * Generate Google Wallet pass<br> * <br> * Endpoint: POST /generate-google-wallet-pass<br> * <br> * Request Body: Same as Apple Wallet<br> * <br> * Response:<br> * {<br> *   &quot;saveUrl&quot;: &quot;https://pay.google.com/gp/v/save/...&quot;,<br> *   &quot;objectId&quot;: &quot;issuerId.objectId&quot;<br> * }<br> */<br>exports.generateGoogleWalletPass = functions.https.onRequest(async (req, res) =&gt; {<br>  res.set(&#39;Access-Control-Allow-Origin&#39;, &#39;*&#39;);<br>  res.set(&#39;Access-Control-Allow-Methods&#39;, &#39;GET, POST, OPTIONS&#39;);<br>  res.set(&#39;Access-Control-Allow-Headers&#39;, &#39;Content-Type, Authorization&#39;);<br><br>  if (req.method === &#39;OPTIONS&#39;) {<br>    res.status(204).send(&#39;&#39;);<br>    return;<br>  }<br><br>  try {<br>    const {<br>      name,<br>      email,<br>      phone,<br>      companyName,<br>      jobTitle,<br>      profileUrl,<br>      logoImageUrl,<br>      profileImageUrl,<br>    } = req.body;<br><br>    // Validate required fields<br>    if (!name || !email) {<br>      return res.status(400).json({<br>        error: &#39;Missing required fields&#39;,<br>        required: [&#39;name&#39;, &#39;email&#39;],<br>      });<br>    }<br><br>    console.log(`Generating Google Wallet pass for: ${name} (${email})`);<br><br>    // Authenticate with Google<br>    const auth = new GoogleAuth({<br>      keyFile: process.env.GOOGLE_APPLICATION_CREDENTIALS,<br>      scopes: &#39;https://www.googleapis.com/auth/wallet_object.issuer&#39;,<br>    });<br><br>    const client = await auth.getClient();<br>    const walletobjects = google.walletobjects({<br>      version: &#39;v1&#39;,<br>      auth: client,<br>    });<br><br>    const issuerId = process.env.GOOGLE_WALLET_ISSUER_ID;<br>    const classId = `${issuerId}.contact_card_class`;<br>    const objectSuffix = uuidv4().replace(/-/g, &#39;&#39;);<br>    const objectId = `${issuerId}.${objectSuffix}`;<br><br>    console.log(`Class ID: ${classId}`);<br>    console.log(`Object ID: ${objectId}`);<br><br>    // Prepare QR code URL<br>    let qrCodeUrl = profileUrl || <br>      `https://yourapp.com/u/${name.toLowerCase().replace(/\s+/g, &#39;-&#39;)}`;<br><br>    if (!qrCodeUrl.startsWith(&#39;http://&#39;) &amp;&amp; !qrCodeUrl.startsWith(&#39;https://&#39;)) {<br>      qrCodeUrl = `https://yourapp.com/u/${qrCodeUrl}`;<br>    }<br><br>    // Create or update pass class<br>    const passClass = {<br>      id: classId,<br>      issuerName: companyName || &#39;Your Company&#39;,<br>      reviewStatus: &#39;UNDER_REVIEW&#39;,<br>      hexBackgroundColor: &#39;#764BA2&#39;,<br>      heroImage: logoImageUrl ? {<br>        sourceUri: {<br>          uri: logoImageUrl,<br>        },<br>        contentDescription: {<br>          defaultValue: {<br>            language: &#39;en-US&#39;,<br>            value: `${companyName || &#39;Company&#39;} Logo`,<br>          },<br>        },<br>      } : undefined,<br>    };<br><br>    console.log(&#39;Creating/updating pass class...&#39;);<br><br>    try {<br>      // Try to get existing class<br>      await walletobjects.genericclass.get({ resourceId: classId });<br>      <br>      // Update if exists<br>      await walletobjects.genericclass.update({<br>        resourceId: classId,<br>        requestBody: passClass,<br>      });<br>      <br>      console.log(&#39;Pass class updated&#39;);<br>    } catch (error) {<br>      if (error.code === 404) {<br>        // Create new class if doesn&#39;t exist<br>        await walletobjects.genericclass.insert({<br>          requestBody: passClass,<br>        });<br>        <br>        console.log(&#39;Pass class created&#39;);<br>      } else {<br>        throw error;<br>      }<br>    }<br><br>    // Create pass object<br>    const passObject = {<br>      id: objectId,<br>      classId: classId,<br>      state: &#39;ACTIVE&#39;,<br>      <br>      // QR Code<br>      barcode: {<br>        type: &#39;QR_CODE&#39;,<br>        value: qrCodeUrl,<br>        alternateText: name,<br>      },<br><br>      // Card title and header<br>      cardTitle: {<br>        defaultValue: {<br>          language: &#39;en-US&#39;,<br>          value: name,<br>        },<br>      },<br>      header: {<br>        defaultValue: {<br>          language: &#39;en-US&#39;,<br>          value: jobTitle || &#39;Contact Card&#39;,<br>        },<br>      },<br><br>      // Profile image<br>      hexBackgroundColor: &#39;#764BA2&#39;,<br>      logo: profileImageUrl ? {<br>        sourceUri: {<br>          uri: profileImageUrl,<br>        },<br>        contentDescription: {<br>          defaultValue: {<br>            language: &#39;en-US&#39;,<br>            value: `${name}&#39;s Profile`,<br>          },<br>        },<br>      } : undefined,<br><br>      // Text content<br>      textModulesData: [<br>        {<br>          header: &#39;EMAIL&#39;,<br>          body: email,<br>          id: &#39;email&#39;,<br>        },<br>        ...(phone ? [{<br>          header: &#39;PHONE&#39;,<br>          body: phone,<br>          id: &#39;phone&#39;,<br>        }] : []),<br>        ...(companyName ? [{<br>          header: &#39;COMPANY&#39;,<br>          body: companyName,<br>          id: &#39;company&#39;,<br>        }] : []),<br>      ],<br><br>      // Links<br>      linksModuleData: {<br>        uris: [<br>          {<br>            uri: qrCodeUrl,<br>            description: &#39;View Profile&#39;,<br>            id: &#39;profile_link&#39;,<br>          },<br>        ],<br>      },<br>    };<br><br>    console.log(&#39;Creating pass object...&#39;);<br><br>    // Insert pass object<br>    await walletobjects.genericobject.insert({<br>      requestBody: passObject,<br>    });<br><br>    console.log(&#39;Pass object created&#39;);<br><br>    // Generate save URL<br>    const saveUrl = `https://pay.google.com/gp/v/save/${objectId}`;<br><br>    console.log(`Google Wallet pass generated successfully: ${objectId}`);<br><br>    res.json({<br>      success: true,<br>      saveUrl: saveUrl,<br>      objectId: objectId,<br>      classId: classId,<br>    });<br><br>  } catch (error) {<br>    console.error(&#39;Error generating Google Wallet pass:&#39;, error);<br>    res.status(500).json({<br>      success: false,<br>      error: &#39;Failed to generate Google Wallet pass&#39;,<br>      message: error.message,<br>      details: error.response?.data || error.stack,<br>    });<br>  }<br>});<br><br>// ============================================================================<br>// HELPER FUNCTIONS<br>// ============================================================================<br><br>/**<br> * Download image from URL and resize to specified dimensions<br> */<br>async function downloadAndResizeImage(url, outputPath, width, height) {<br>  try {<br>    console.log(`Downloading image from: ${url}`);<br>    <br>    const response = await axios.get(url, {<br>      responseType: &#39;arraybuffer&#39;,<br>      timeout: 10000,<br>    });<br><br>    console.log(`Resizing image to ${width}x${height}...`);<br>    <br>    await sharp(response.data)<br>      .resize(width, height, {<br>        fit: &#39;cover&#39;,<br>        position: &#39;center&#39;,<br>      })<br>      .png({<br>        quality: 90,<br>        compressionLevel: 9,<br>      })<br>      .toFile(outputPath);<br><br>    console.log(`Image saved: ${outputPath}`);<br>  } catch (error) {<br>    console.error(`Error processing image from ${url}:`, error.message);<br>    // Create placeholder on error<br>    await createPlaceholderIcon(outputPath, width);<br>  }<br>}<br><br>/**<br> * Create placeholder icon with company colors<br> */<br>async function createPlaceholderIcon(outputPath, size) {<br>  await sharp({<br>    create: {<br>      width: size,<br>      height: size,<br>      channels: 4,<br>      background: { r: 118, g: 75, b: 162, alpha: 1 },<br>    },<br>  })<br>  .png()<br>  .toFile(outputPath);<br><br>  console.log(`Placeholder created: ${outputPath}`);<br>}<br><br>/**<br> * Create manifest.json with SHA1 hashes of all files<br> */<br>async function createManifest(passDir) {<br>  const manifest = {};<br>  const files = fs.readdirSync(passDir);<br><br>  for (const file of files) {<br>    if (file === &#39;manifest.json&#39; || file === &#39;signature&#39;) {<br>      continue;<br>    }<br><br>    const filePath = path.join(passDir, file);<br>    const fileData = fs.readFileSync(filePath);<br>    const sha1 = forge.md.sha1.create();<br>    sha1.update(fileData.toString(&#39;binary&#39;));<br>    manifest[file] = sha1.digest().toHex();<br>  }<br><br>  console.log(&#39;Manifest created with&#39;, Object.keys(manifest).length, &#39;files&#39;);<br>  return manifest;<br>}<br><br>/**<br> * Sign the pass with certificate and private key<br> */<br>async function signPass(passDir) {<br>  try {<br>    const manifestPath = path.join(passDir, &#39;manifest.json&#39;);<br>    const manifestData = fs.readFileSync(manifestPath);<br><br>    // Load certificate and private key<br>    const cert = forge.pki.certificateFromPem(<br>      fs.readFileSync(process.env.PASS_CERTIFICATE, &#39;utf8&#39;)<br>    );<br>    const privateKey = forge.pki.privateKeyFromPem(<br>      fs.readFileSync(process.env.PASS_PRIVATE_KEY, &#39;utf8&#39;)<br>    );<br><br>    // Create PKCS#7 signature<br>    const p7 = forge.pkcs7.createSignedData();<br>    p7.content = forge.util.createBuffer(manifestData.toString(&#39;binary&#39;));<br>    p7.addCertificate(cert);<br>    p7.addSigner({<br>      key: privateKey,<br>      certificate: cert,<br>      digestAlgorithm: forge.pki.oids.sha1,<br>      authenticatedAttributes: [<br>        {<br>          type: forge.pki.oids.contentType,<br>          value: forge.pki.oids.data,<br>        },<br>        {<br>          type: forge.pki.oids.messageDigest,<br>        },<br>        {<br>          type: forge.pki.oids.signingTime,<br>          value: new Date(),<br>        },<br>      ],<br>    });<br><br>    p7.sign({ detached: true });<br><br>    // Write signature file<br>    const signaturePath = path.join(passDir, &#39;signature&#39;);<br>    const der = forge.asn1.toDer(p7.toAsn1()).getBytes();<br>    fs.writeFileSync(signaturePath, der, &#39;binary&#39;);<br><br>    console.log(&#39;Pass signed successfully&#39;);<br>  } catch (error) {<br>    console.error(&#39;Error signing pass:&#39;, error);<br>    throw error;<br>  }<br>}<br><br>/**<br> * Create .pkpass archive (ZIP file)<br> */<br>async function createPassArchive(sourceDir, outputPath) {<br>  return new Promise((resolve, reject) =&gt; {<br>    const output = fs.createWriteStream(outputPath);<br>    const archive = archiver(&#39;zip&#39;, {<br>      zlib: { level: 9 },<br>    });<br><br>    output.on(&#39;close&#39;, () =&gt; {<br>      console.log(`Archive created: ${archive.pointer()} bytes`);<br>      resolve();<br>    });<br><br>    archive.on(&#39;error&#39;, (err) =&gt; {<br>      console.error(&#39;Archive error:&#39;, err);<br>      reject(err);<br>    });<br><br>    archive.pipe(output);<br><br>    // Add all files from source directory (excluding the .pkpass file itself)<br>    const files = fs.readdirSync(sourceDir);<br>    for (const file of files) {<br>      if (!file.endsWith(&#39;.pkpass&#39;)) {<br>        archive.file(path.join(sourceDir, file), { name: file });<br>      }<br>    }<br><br>    archive.finalize();<br>  });<br>}<br><br>// ============================================================================<br>// ADDITIONAL ENDPOINTS<br>// ============================================================================<br><br>/**<br> * Get pass information by ID<br> */<br>exports.getPass = functions.https.onRequest(async (req, res) =&gt; {<br>  res.set(&#39;Access-Control-Allow-Origin&#39;, &#39;*&#39;);<br>  <br>  try {<br>    const passId = req.query.passId || req.params.passId;<br>    <br>    if (!passId) {<br>      return res.status(400).json({ error: &#39;Pass ID required&#39; });<br>    }<br><br>    const bucket = admin.storage().bucket();<br>    const file = bucket.file(`passes/${passId}.pkpass`);<br>    <br>    const [exists] = await file.exists();<br>    <br>    if (!exists) {<br>      return res.status(404).json({ error: &#39;Pass not found&#39; });<br>    }<br><br>    const [metadata] = await file.getMetadata();<br>    const [url] = await file.getSignedUrl({<br>      action: &#39;read&#39;,<br>      expires: Date.now() + 3600 * 1000,<br>    });<br><br>    res.json({<br>      passId: passId,<br>      url: url,<br>      createdAt: metadata.timeCreated,<br>      metadata: metadata.metadata,<br>    });<br><br>  } catch (error) {<br>    console.error(&#39;Error getting pass:&#39;, error);<br>    res.status(500).json({ error: error.message });<br>  }<br>});<br><br>/**<br> * Delete pass by ID<br> */<br>exports.deletePass = functions.https.onRequest(async (req, res) =&gt; {<br>  res.set(&#39;Access-Control-Allow-Origin&#39;, &#39;*&#39;);<br>  <br>  try {<br>    const passId = req.query.passId || req.body.passId;<br>    <br>    if (!passId) {<br>      return res.status(400).json({ error: &#39;Pass ID required&#39; });<br>    }<br><br>    const bucket = admin.storage().bucket();<br>    const file = bucket.file(`passes/${passId}.pkpass`);<br>    <br>    await file.delete();<br><br>    res.json({<br>      success: true,<br>      message: &#39;Pass deleted successfully&#39;,<br>    });<br><br>  } catch (error) {<br>    console.error(&#39;Error deleting pass:&#39;, error);<br>    res.status(500).json({ error: error.message });<br>  }<br>});</pre><h4>Environment Variables Setup</h4><p>Create a .env file or set Firebase Functions config:</p><pre># Apple Wallet Configuration<br>PASS_TYPE_ID=pass.com.yourcompany.contact<br>TEAM_IDENTIFIER=YOUR_TEAM_ID<br><br># Certificate paths (for signing)<br>PASS_CERTIFICATE=/path/to/certificate.pem<br>PASS_PRIVATE_KEY=/path/to/private-key.pem<br><br># Google Wallet Configuration<br>GOOGLE_WALLET_ISSUER_ID=1234567890123456789<br>GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account-key.json<br><br># Firebase project<br>FIREBASE_PROJECT_ID=your-project-id</pre><h4>Package.json Dependencies:</h4><pre>{<br>  &quot;name&quot;: &quot;wallet-functions&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;engines&quot;: {<br>    &quot;node&quot;: &quot;18&quot;<br>  },<br>  &quot;dependencies&quot;: {<br>    &quot;firebase-functions&quot;: &quot;^4.5.0&quot;,<br>    &quot;firebase-admin&quot;: &quot;^11.11.0&quot;,<br>    &quot;uuid&quot;: &quot;^9.0.1&quot;,<br>    &quot;axios&quot;: &quot;^1.6.0&quot;,<br>    &quot;archiver&quot;: &quot;^6.0.1&quot;,<br>    &quot;sharp&quot;: &quot;^0.33.0&quot;,<br>    &quot;google-auth-library&quot;: &quot;^9.2.0&quot;,<br>    &quot;googleapis&quot;: &quot;^128.0.0&quot;,<br>    &quot;node-forge&quot;: &quot;^1.3.1&quot;<br>  }<br>}</pre><h4>Deployment Commands:</h4><pre># Install dependencies<br>cd functions<br>npm install<br><br># Set environment variables<br>firebase functions:config:set \<br>  pass.type_id=&quot;pass.com.yourcompany.contact&quot; \<br>  pass.team_id=&quot;YOUR_TEAM_ID&quot; \<br>  google.issuer_id=&quot;1234567890123456789&quot;<br><br># Deploy functions<br>firebase deploy --only functions<br><br># Deploy specific function<br>firebase deploy --only functions:generatePass<br>firebase deploy --only functions:generateGoogleWalletPass<br>```<br><br>## API Endpoints<br><br>Once deployed, your functions will be available at:<br>```<br>https://us-central1-YOUR_PROJECT_ID.cloudfunctions.net/generatePass<br>https://us-central1-YOUR_PROJECT_ID.cloudfunctions.net/generateGoogleWalletPass<br>https://us-central1-YOUR_PROJECT_ID.cloudfunctions.net/getPass<br>https://us-central1-YOUR_PROJECT_ID.cloudfunctions.net/deletePass</pre><h3>Testing the Endpoints</h3><h4>Test Apple Wallet Pass:</h4><pre>curl -X POST https://your-project.cloudfunctions.net/generatePass \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{<br>    &quot;name&quot;: &quot;John Doe&quot;,<br>    &quot;email&quot;: &quot;john@example.com&quot;,<br>    &quot;phone&quot;: &quot;+1234567890&quot;,<br>    &quot;companyName&quot;: &quot;Acme Corp&quot;,<br>    &quot;jobTitle&quot;: &quot;Software Engineer&quot;,<br>    &quot;profileUrl&quot;: &quot;https://example.com/profile/johndoe&quot;,<br>    &quot;logoImageUrl&quot;: &quot;https://example.com/logo.png&quot;,<br>    &quot;profileImageUrl&quot;: &quot;https://example.com/profile.png&quot;<br>  }&#39;</pre><h4>Test Google Wallet Pass:</h4><pre>curl -X POST https://your-project.cloudfunctions.net/generateGoogleWalletPass \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{<br>    &quot;name&quot;: &quot;John Doe&quot;,<br>    &quot;email&quot;: &quot;john@example.com&quot;,<br>    &quot;phone&quot;: &quot;+1234567890&quot;,<br>    &quot;companyName&quot;: &quot;Acme Corp&quot;,<br>    &quot;jobTitle&quot;: &quot;Software Engineer&quot;,<br>    &quot;profileUrl&quot;: &quot;https://example.com/profile/johndoe&quot;,<br>    &quot;logoImageUrl&quot;: &quot;https://example.com/logo.png&quot;,<br>    &quot;profileImageUrl&quot;: &quot;https://example.com/profile.png&quot;<br>  }&#39;</pre><h3>Important Notes</h3><blockquote>Apple Wallet Certificates</blockquote><p>To properly sign passes, you need:</p><p><strong>Pass Type ID Certificate</strong> from Apple Developer Portal</p><p><strong>WWDR (Worldwide Developer Relations) Certificate</strong></p><p><strong>Private Key</strong> used to generate the certificate</p><p>Convert to PEM format:</p><pre>openssl pkcs12 -in Certificates.p12 -clcerts -nokeys -out certificate.pem<br>openssl pkcs12 -in Certificates.p12 -nocerts -out private-key.pem</pre><h3>Google Wallet Setup</h3><ol><li>Create a Google Cloud Project</li><li>Enable Google Wallet API</li><li>Create a Service Account</li><li>Download service account key JSON</li><li>Create an Issuer Account in Google Pay &amp; Wallet Console</li></ol><h3>Image Requirements</h3><p><strong>Apple Wallet:</strong></p><ul><li>icon.png: 29x29pt (required)</li><li><a href="/service/mailto:icon@2x.png">icon@2x.png</a>: 58x58pt (required)</li><li><a href="/service/mailto:icon@3x.png">icon@3x.png</a>: 87x87pt (required)</li><li>logo.png: 160x50pt (optional)</li><li><a href="/service/mailto:logo@2x.png">logo@2x.png</a>: 320x100pt (optional)</li><li><a href="/service/mailto:logo@3x.png">logo@3x.png</a>: 480x150pt (optional)</li></ul><p><strong>Google Wallet:</strong></p><ul><li>Logo: 660x660px (recommended)</li><li>Hero image: 1032x336px (recommended)</li><li>Format: PNG or JPG</li></ul><h3>Security Best Practices</h3><ol><li><strong>Rate Limiting</strong>: Implement rate limiting to prevent abuse</li><li><strong>Authentication</strong>: Add API key or Firebase Auth token validation</li><li><strong>Input Validation</strong>: Sanitize all user inputs</li><li><strong>Certificate Security</strong>: Store certificates securely (use Secret Manager)</li><li><strong>HTTPS Only</strong>: Never expose endpoints without HTTPS</li></ol><h3>6. Complete Integration Flow:</h3><h4>End-to-End User Journey:</h4><p>┌──────────────────────────────────────────────────────────────────┐<br>│ USER JOURNEY │<br>└──────────────────────────────────────────────────────────────────┘</p><p>STEP 1: NFC Tag Scan<br>├─ User taps phone near NFC tag<br>├─ App requests NFC permission (if not granted)<br>├─ NFC reader activates automatically<br>└─ Tag detected → vibration feedback</p><p>STEP 2: Data Reading &amp; Validation<br>├─ App reads NDEF records from tag<br>├─ Extracts URI record containing profile URL<br>├─ Validates URL format<br>└─ Shows loading indicator</p><p>STEP 3: Profile Fetching<br>├─ HTTP request to backend with profile URL<br>├─ Backend queries Firestore/Database<br>├─ Returns profile data (JSON)<br>└─ App validates required fields</p><p>STEP 4: Profile Display<br>├─ App shows profile card with:<br>│ ├─ Profile photo<br>│ ├─ Name and job title<br>│ ├─ Company name<br>│ ├─ Contact information<br>│ └─ “Add to Wallet” button<br>└─ Button enabled only if wallet is available</p><p>STEP 5: User Taps “Add to Wallet”<br>├─ Button disabled + loading state<br>├─ Platform detection (iOS/Android)<br>└─ Call appropriate wallet service</p><p>STEP 6: Server-Side Pass Generation<br>├─ Flutter app sends profile data to backend<br>├─ Backend validates data<br>├─ Downloads/processes images<br>├─ Creates pass structure<br>└─ Generates .pkpass (iOS) or save URL (Android)</p><p>STEP 7: Pass Delivery<br>├─ iOS: Downloads .pkpass file<br>│ ├─ Validates file integrity<br>│ ├─ Opens PassKit native UI<br>│ └─ User reviews and confirms<br>│<br>└─ Android: Opens save URL<br> ├─ Launches Google Wallet app<br> ├─ Shows pass preview<br> └─ User confirms to save</p><p>STEP 8: Pass Added<br>├─ Success feedback shown<br>├─ Pass appears in wallet app<br>├─ QR code scannable immediately<br>└─ User can access offline</p><p>STEP 9: Usage<br>├─ User opens wallet app anytime<br>├─ Selects the pass<br>├─ Shows QR code to be scanned<br>└─ Opens profile URL when tapped</p><h4>Detailed Code Flow:</h4><pre>// Complete flow implementation example<br><br>class NFCToWalletFlow {<br>  final NFCService _nfcService;<br>  final ProfileService _profileService;<br>  final WalletPassService _walletService;<br>  <br>  /// Execute complete flow from NFC scan to wallet<br>  Future&lt;void&gt; executeFlow(BuildContext context) async {<br>    try {<br>      // STEP 1 &amp; 2: Scan and read NFC tag<br>      print(&#39;📱 Starting NFC scan...&#39;);<br>      final nfcData = await _nfcService.scanTag();<br>      <br>      if (nfcData == null) {<br>        throw Exception(&#39;No NFC data found&#39;);<br>      }<br>      <br>      print(&#39;✅ NFC data read: ${nfcData.uri}&#39;);<br>      <br>      // STEP 3: Fetch profile from backend<br>      print(&#39;🔍 Fetching profile...&#39;);<br>      final profile = await _profileService.getProfileByUrl(nfcData.uri);<br>      <br>      if (profile == null) {<br>        throw Exception(&#39;Profile not found for this tag&#39;);<br>      }<br>      <br>      print(&#39;✅ Profile found: ${profile.name}&#39;);<br>      <br>      // STEP 4: Display profile (handled by UI)<br>      showProfileDialog(context, profile);<br>      <br>      // STEP 5-8: Add to wallet (when user confirms)<br>      // This is called when user taps the button<br>      <br>    } catch (e) {<br>      print(&#39;❌ Error in flow: $e&#39;);<br>      showErrorDialog(context, e.toString());<br>    }<br>  }<br>  <br>  /// Add profile to wallet (Steps 5-8)<br>  Future&lt;void&gt; addToWallet(BuildContext context, ProfileModel profile) async {<br>    try {<br>      // Show loading<br>      showLoadingDialog(context);<br>      <br>      print(&#39;📲 Adding to wallet...&#39;);<br>      <br>      // Platform detection and wallet addition<br>      final success = await _walletService.addPassToWallet(profile);<br>      <br>      // Hide loading<br>      Navigator.pop(context);<br>      <br>      if (success) {<br>        print(&#39;✅ Successfully added to wallet&#39;);<br>        showSuccessDialog(context, &#39;Profile added to wallet!&#39;);<br>      } else {<br>        throw Exception(&#39;Failed to add to wallet&#39;);<br>      }<br>      <br>    } catch (e) {<br>      Navigator.pop(context); // Hide loading<br>      print(&#39;❌ Error adding to wallet: $e&#39;);<br>      showErrorDialog(context, e.toString());<br>    }<br>  }<br>}</pre><h4>State Management Flow (Using Bloc/Cubit):</h4><pre>// NFCState definitions<br>enum NFCStatus {<br>  initial,<br>  scanning,<br>  tagDetected,<br>  profileLoaded,<br>  addingToWallet,<br>  walletAdded,<br>  error,<br>}<br><br>class NFCState {<br>  final NFCStatus status;<br>  final ProfileModel? profile;<br>  final String? errorMessage;<br>  final bool isLoading;<br>  <br>  const NFCState({<br>    required this.status,<br>    this.profile,<br>    this.errorMessage,<br>    this.isLoading = false,<br>  });<br>  <br>  // Initial state<br>  factory NFCState.initial() =&gt; const NFCState(<br>    status: NFCStatus.initial,<br>  );<br>  <br>  // Copy with method for state updates<br>  NFCState copyWith({<br>    NFCStatus? status,<br>    ProfileModel? profile,<br>    String? errorMessage,<br>    bool? isLoading,<br>  }) {<br>    return NFCState(<br>      status: status ?? this.status,<br>      profile: profile ?? this.profile,<br>      errorMessage: errorMessage ?? this.errorMessage,<br>      isLoading: isLoading ?? this.isLoading,<br>    );<br>  }<br>}<br><br>// NFCCubit implementation<br>class NFCCubit extends Cubit&lt;NFCState&gt; {<br>  final NFCService _nfcService;<br>  final ProfileService _profileService;<br>  final WalletPassService _walletService;<br>  <br>  NFCCubit({<br>    required NFCService nfcService,<br>    required ProfileService profileService,<br>    required WalletPassService walletService,<br>  })  : _nfcService = nfcService,<br>        _profileService = profileService,<br>        _walletService = walletService,<br>        super(NFCState.initial());<br>  <br>  /// Start NFC scanning<br>  Future&lt;void&gt; startScanning() async {<br>    emit(state.copyWith(<br>      status: NFCStatus.scanning,<br>      isLoading: true,<br>      errorMessage: null,<br>    ));<br>    <br>    try {<br>      // Check NFC availability<br>      final isAvailable = await _nfcService.isAvailable();<br>      if (!isAvailable) {<br>        throw Exception(&#39;NFC is not available on this device&#39;);<br>      }<br>      <br>      // Start NFC session<br>      await _nfcService.startSession();<br>      <br>      // Read tag<br>      final tagData = await _nfcService.readTag();<br>      <br>      emit(state.copyWith(<br>        status: NFCStatus.tagDetected,<br>      ));<br>      <br>      // Extract profile URL<br>      final profileUrl = _extractProfileUrl(tagData);<br>      if (profileUrl == null) {<br>        throw Exception(&#39;No profile URL found in tag&#39;);<br>      }<br>      <br>      // Fetch profile<br>      await _fetchProfile(profileUrl);<br>      <br>    } catch (e) {<br>      emit(state.copyWith(<br>        status: NFCStatus.error,<br>        errorMessage: e.toString(),<br>        isLoading: false,<br>      ));<br>    } finally {<br>      await _nfcService.stopSession();<br>    }<br>  }<br>  <br>  /// Fetch profile from backend<br>  Future&lt;void&gt; _fetchProfile(String url) async {<br>    try {<br>      final profile = await _profileService.getProfileByUrl(url);<br>      <br>      if (profile == null) {<br>        throw Exception(&#39;Profile not found&#39;);<br>      }<br>      <br>      emit(state.copyWith(<br>        status: NFCStatus.profileLoaded,<br>        profile: profile,<br>        isLoading: false,<br>      ));<br>      <br>    } catch (e) {<br>      emit(state.copyWith(<br>        status: NFCStatus.error,<br>        errorMessage: &#39;Failed to load profile: ${e.toString()}&#39;,<br>        isLoading: false,<br>      ));<br>    }<br>  }<br>  <br>  /// Add profile to wallet<br>  Future&lt;void&gt; addToWallet() async {<br>    if (state.profile == null) {<br>      emit(state.copyWith(<br>        status: NFCStatus.error,<br>        errorMessage: &#39;No profile to add&#39;,<br>      ));<br>      return;<br>    }<br>    <br>    emit(state.copyWith(<br>      status: NFCStatus.addingToWallet,<br>      isLoading: true,<br>    ));<br>    <br>    try {<br>      final success = await _walletService.addPassToWallet(state.profile!);<br>      <br>      if (success) {<br>        emit(state.copyWith(<br>          status: NFCStatus.walletAdded,<br>          isLoading: false,<br>        ));<br>      } else {<br>        throw Exception(&#39;Failed to add to wallet&#39;);<br>      }<br>      <br>    } catch (e) {<br>      emit(state.copyWith(<br>        status: NFCStatus.error,<br>        errorMessage: &#39;Wallet error: ${e.toString()}&#39;,<br>        isLoading: false,<br>      ));<br>    }<br>  }<br>  <br>  /// Reset state<br>  void reset() {<br>    emit(NFCState.initial());<br>  }<br>  <br>  /// Extract profile URL from NFC data<br>  String? _extractProfileUrl(dynamic tagData) {<br>    // Implementation depends on your NFC data structure<br>    if (tagData is Map &amp;&amp; tagData.containsKey(&#39;uri&#39;)) {<br>      return tagData[&#39;uri&#39;] as String;<br>    }<br>    return null;<br>  }<br>}</pre><h4>UI Implementation with State Handling:</h4><pre>class NFCReaderView extends StatelessWidget {<br>  const NFCReaderView({Key? key}) : super(key: key);<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return BlocProvider(<br>      create: (context) =&gt; NFCCubit(<br>        nfcService: context.read&lt;NFCService&gt;(),<br>        profileService: context.read&lt;ProfileService&gt;(),<br>        walletService: context.read&lt;WalletPassService&gt;(),<br>      ),<br>      child: const _NFCReaderContent(),<br>    );<br>  }<br>}<br><br>class _NFCReaderContent extends StatelessWidget {<br>  const _NFCReaderContent();<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&#39;Scan NFC Tag&#39;),<br>      ),<br>      body: BlocConsumer&lt;NFCCubit, NFCState&gt;(<br>        listener: (context, state) {<br>          // Handle state changes<br>          if (state.status == NFCStatus.walletAdded) {<br>            ScaffoldMessenger.of(context).showSnackBar(<br>              const SnackBar(<br>                content: Text(&#39;✅ Profile added to wallet successfully!&#39;),<br>                backgroundColor: Colors.green,<br>              ),<br>            );<br>          } else if (state.status == NFCStatus.error) {<br>            ScaffoldMessenger.of(context).showSnackBar(<br>              SnackBar(<br>                content: Text(&#39;❌ ${state.errorMessage}&#39;),<br>                backgroundColor: Colors.red,<br>              ),<br>            );<br>          }<br>        },<br>        builder: (context, state) {<br>          return Padding(<br>            padding: const EdgeInsets.all(16.0),<br>            child: Column(<br>              crossAxisAlignment: CrossAxisAlignment.stretch,<br>              children: [<br>                // Status indicator<br>                _buildStatusIndicator(state),<br>                <br>                const SizedBox(height: 24),<br>                <br>                // Profile card (if loaded)<br>                if (state.profile != null) ...[<br>                  _buildProfileCard(context, state.profile!),<br>                  const SizedBox(height: 16),<br>                ],<br>                <br>                // Action button<br>                _buildActionButton(context, state),<br>                <br>                const Spacer(),<br>                <br>                // Help text<br>                _buildHelpText(state),<br>              ],<br>            ),<br>          );<br>        },<br>      ),<br>    );<br>  }<br>  <br>  Widget _buildStatusIndicator(NFCState state) {<br>    IconData icon;<br>    String text;<br>    Color color;<br>    <br>    switch (state.status) {<br>      case NFCStatus.initial:<br>        icon = Icons.nfc;<br>        text = &#39;Ready to scan&#39;;<br>        color = Colors.blue;<br>        break;<br>      case NFCStatus.scanning:<br>        icon = Icons.radar;<br>        text = &#39;Scanning for tag...&#39;;<br>        color = Colors.orange;<br>        break;<br>      case NFCStatus.tagDetected:<br>        icon = Icons.check_circle;<br>        text = &#39;Tag detected!&#39;;<br>        color = Colors.green;<br>        break;<br>      case NFCStatus.profileLoaded:<br>        icon = Icons.person;<br>        text = &#39;Profile loaded&#39;;<br>        color = Colors.green;<br>        break;<br>      case NFCStatus.addingToWallet:<br>        icon = Icons.wallet;<br>        text = &#39;Adding to wallet...&#39;;<br>        color = Colors.blue;<br>        break;<br>      case NFCStatus.walletAdded:<br>        icon = Icons.check_circle;<br>        text = &#39;Added to wallet!&#39;;<br>        color = Colors.green;<br>        break;<br>      case NFCStatus.error:<br>        icon = Icons.error;<br>        text = &#39;Error occurred&#39;;<br>        color = Colors.red;<br>        break;<br>    }<br>    <br>    return Card(<br>      child: Padding(<br>        padding: const EdgeInsets.all(16.0),<br>        child: Row(<br>          children: [<br>            Icon(icon, color: color, size: 32),<br>            const SizedBox(width: 16),<br>            Expanded(<br>              child: Column(<br>                crossAxisAlignment: CrossAxisAlignment.start,<br>                children: [<br>                  Text(<br>                    text,<br>                    style: TextStyle(<br>                      fontSize: 18,<br>                      fontWeight: FontWeight.bold,<br>                      color: color,<br>                    ),<br>                  ),<br>                  if (state.isLoading)<br>                    const LinearProgressIndicator(),<br>                ],<br>              ),<br>            ),<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>  <br>  Widget _buildProfileCard(BuildContext context, ProfileModel profile) {<br>    return Card(<br>      elevation: 4,<br>      child: Padding(<br>        padding: const EdgeInsets.all(16.0),<br>        child: Column(<br>          children: [<br>            // Profile header<br>            Row(<br>              children: [<br>                // Profile image<br>                CircleAvatar(<br>                  radius: 40,<br>                  backgroundImage: profile.profileImageUrl != null<br>                      ? NetworkImage(profile.profileImageUrl!)<br>                      : null,<br>                  child: profile.profileImageUrl == null<br>                      ? const Icon(Icons.person, size: 40)<br>                      : null,<br>                ),<br>                const SizedBox(width: 16),<br>                <br>                // Profile info<br>                Expanded(<br>                  child: Column(<br>                    crossAxisAlignment: CrossAxisAlignment.start,<br>                    children: [<br>                      Text(<br>                        profile.name,<br>                        style: const TextStyle(<br>                          fontSize: 20,<br>                          fontWeight: FontWeight.bold,<br>                        ),<br>                      ),<br>                      if (profile.jobTitle != null)<br>                        Text(<br>                          profile.jobTitle!,<br>                          style: TextStyle(<br>                            fontSize: 16,<br>                            color: Colors.grey[600],<br>                          ),<br>                        ),<br>                      if (profile.companyName != null)<br>                        Text(<br>                          profile.companyName!,<br>                          style: TextStyle(<br>                            fontSize: 14,<br>                            color: Colors.grey[500],<br>                          ),<br>                        ),<br>                    ],<br>                  ),<br>                ),<br>              ],<br>            ),<br>            <br>            const Divider(height: 24),<br>            <br>            // Contact info<br>            if (profile.email != null)<br>              _buildInfoRow(Icons.email, profile.email!),<br>            if (profile.phone != null)<br>              _buildInfoRow(Icons.phone, profile.phone!),<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>  <br>  Widget _buildInfoRow(IconData icon, String text) {<br>    return Padding(<br>      padding: const EdgeInsets.symmetric(vertical: 4.0),<br>      child: Row(<br>        children: [<br>          Icon(icon, size: 20, color: Colors.grey[600]),<br>          const SizedBox(width: 8),<br>          Text(text),<br>        ],<br>      ),<br>    );<br>  }<br>  <br>  Widget _buildActionButton(BuildContext context, NFCState state) {<br>    String label;<br>    VoidCallback? onPressed;<br>    bool loading = state.isLoading;<br>    <br>    switch (state.status) {<br>      case NFCStatus.initial:<br>      case NFCStatus.error:<br>        label = &#39;Start Scanning&#39;;<br>        onPressed = () =&gt; context.read&lt;NFCCubit&gt;().startScanning();<br>        break;<br>      case NFCStatus.scanning:<br>        label = &#39;Scanning...&#39;;<br>        onPressed = null;<br>        break;<br>      case NFCStatus.profileLoaded:<br>        label = Platform.isIOS ? &#39;Add to Apple Wallet&#39; : &#39;Add to Google Wallet&#39;;<br>        onPressed = () =&gt; context.read&lt;NFCCubit&gt;().addToWallet();<br>        break;<br>      case NFCStatus.addingToWallet:<br>        label = &#39;Adding to Wallet...&#39;;<br>        onPressed = null;<br>        break;<br>      case NFCStatus.walletAdded:<br>        label = &#39;Scan Another Tag&#39;;<br>        onPressed = () {<br>          context.read&lt;NFCCubit&gt;().reset();<br>          context.read&lt;NFCCubit&gt;().startScanning();<br>        };<br>        break;<br>      default:<br>        label = &#39;Start Scanning&#39;;<br>        onPressed = () =&gt; context.read&lt;NFCCubit&gt;().startScanning();<br>    }<br>    <br>    return ElevatedButton.icon(<br>      onPressed: loading ? null : onPressed,<br>      icon: loading<br>          ? const SizedBox(<br>              width: 20,<br>              height: 20,<br>              child: CircularProgressIndicator(strokeWidth: 2),<br>            )<br>          : Icon(<br>              state.status == NFCStatus.profileLoaded<br>                  ? Icons.wallet<br>                  : Icons.nfc,<br>            ),<br>      label: Text(label),<br>      style: ElevatedButton.styleFrom(<br>        padding: const EdgeInsets.all(16),<br>        textStyle: const TextStyle(fontSize: 16),<br>      ),<br>    );<br>  }<br>  <br>  Widget _buildHelpText(NFCState state) {<br>    String text;<br>    <br>    switch (state.status) {<br>      case NFCStatus.initial:<br>        text = &#39;Tap &quot;Start Scanning&quot; and hold your phone near an NFC tag&#39;;<br>        break;<br>      case NFCStatus.scanning:<br>        text = &#39;Hold your phone near the NFC tag...&#39;;<br>        break;<br>      case NFCStatus.profileLoaded:<br>        text = &#39;Tap the button above to add this profile to your wallet&#39;;<br>        break;<br>      default:<br>        text = &#39;&#39;;<br>    }<br>    <br>    if (text.isEmpty) return const SizedBox.shrink();<br>    <br>    return Text(<br>      text,<br>      textAlign: TextAlign.center,<br>      style: TextStyle(<br>        color: Colors.grey[600],<br>        fontSize: 14,<br>      ),<br>    );<br>  }<br>}</pre><h3>7. Best Practices and Considerations:</h3><h4>1. Error Handling Best Practices:</h4><pre>/// Centralized error handler<br>class WalletErrorHandler {<br>  static String getUserFriendlyMessage(dynamic error) {<br>    final errorString = error.toString().toLowerCase();<br>    <br>    // NFC Errors<br>    if (errorString.contains(&#39;nfc not available&#39;)) {<br>      return &#39;NFC is not available on this device. Please use a device with NFC support.&#39;;<br>    }<br>    if (errorString.contains(&#39;nfc disabled&#39;)) {<br>      return &#39;Please enable NFC in your device settings.&#39;;<br>    }<br>    if (errorString.contains(&#39;session timeout&#39;)) {<br>      return &#39;NFC scan timed out. Please try again.&#39;;<br>    }<br>    <br>    // Wallet Errors<br>    if (errorString.contains(&#39;icon.png&#39;) || errorString.contains(&#39;not a valid pkpass&#39;)) {<br>      return &#39;The pass file is invalid. Please contact support.&#39;;<br>    }<br>    if (errorString.contains(&#39;wallet not available&#39;)) {<br>      return Platform.isIOS<br>          ? &#39;Apple Wallet is not available on this device.&#39;<br>          : &#39;Google Wallet is not installed. Please install it from Play Store.&#39;;<br>    }<br>    if (errorString.contains(&#39;cannot add passes&#39;)) {<br>      return &#39;Cannot add passes. Check if parental controls are enabled.&#39;;<br>    }<br>    <br>    // Network Errors<br>    if (errorString.contains(&#39;timeout&#39;)) {<br>      return &#39;Request timed out. Please check your internet connection.&#39;;<br>    }<br>    if (errorString.contains(&#39;network&#39;) || errorString.contains(&#39;connection&#39;)) {<br>      return &#39;Network error. Please check your internet connection.&#39;;<br>    }<br>    <br>    // Server Errors<br>    if (errorString.contains(&#39;500&#39;) || errorString.contains(&#39;server error&#39;)) {<br>      return &#39;Server error. Please try again later.&#39;;<br>    }<br>    if (errorString.contains(&#39;404&#39;) || errorString.contains(&#39;not found&#39;)) {<br>      return &#39;Profile not found. The tag may be invalid.&#39;;<br>    }<br>    <br>    // Generic error<br>    return &#39;An unexpected error occurred. Please try again.&#39;;<br>  }<br>  <br>  /// Show error dialog with retry option<br>  static void showErrorDialog(<br>    BuildContext context,<br>    dynamic error, {<br>    VoidCallback? onRetry,<br>  }) {<br>    final message = getUserFriendlyMessage(error);<br>    <br>    showDialog(<br>      context: context,<br>      builder: (context) =&gt; AlertDialog(<br>        title: const Row(<br>          children: [<br>            Icon(Icons.error_outline, color: Colors.red),<br>            SizedBox(width: 8),<br>            Text(&#39;Error&#39;),<br>          ],<br>        ),<br>        content: Text(message),<br>        actions: [<br>          if (onRetry != null)<br>            TextButton(<br>              onPressed: () {<br>                Navigator.pop(context);<br>                onRetry();<br>              },<br>              child: const Text(&#39;Retry&#39;),<br>            ),<br>          TextButton(<br>            onPressed: () =&gt; Navigator.pop(context),<br>            child: const Text(&#39;OK&#39;),<br>          ),<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><p><strong>2. Performance Optimization:</strong></p><pre>/// Image caching and optimization<br>class ImageOptimizer {<br>  static final _cache = &lt;String, Uint8List&gt;{};<br>  <br>  /// Download and cache image with optimization<br>  static Future&lt;Uint8List?&gt; optimizeImage(<br>    String url, {<br>    int maxWidth = 1024,<br>    int maxHeight = 1024,<br>    int quality = 85,<br>  }) async {<br>    // Check cache first<br>    if (_cache.containsKey(url)) {<br>      print(&#39;📦 Using cached image for: $url&#39;);<br>      return _cache[url];<br>    }<br>    <br>    try {<br>      print(&#39;⬇️ Downloading image: $url&#39;);<br>      <br>      final response = await http.get(Uri.parse(url)).timeout(<br>        const Duration(seconds: 10),<br>      );<br>      <br>      if (response.statusCode != 200) {<br>        throw Exception(&#39;Failed to download image: ${response.statusCode}&#39;);<br>      }<br>      <br>      // Optimize image<br>      print(&#39;🖼️ Optimizing image...&#39;);<br>      final optimized = await _optimizeImageData(<br>        response.bodyBytes,<br>        maxWidth: maxWidth,<br>        maxHeight: maxHeight,<br>        quality: quality,<br>      );<br>      <br>      // Cache result<br>      _cache[url] = optimized;<br>      <br>      return optimized;<br>    } catch (e) {<br>      print(&#39;❌ Error optimizing image: $e&#39;);<br>      return null;<br>    }<br>  }<br>  <br>  static Future&lt;Uint8List&gt; _optimizeImageData(<br>    Uint8List data, {<br>    required int maxWidth,<br>    required int maxHeight,<br>    required int quality,<br>  }) async {<br>    final image = img.decodeImage(data);<br>    <br>    if (image == null) {<br>      throw Exception(&#39;Invalid image data&#39;);<br>    }<br>    <br>    // Resize if needed<br>    if (image.width &gt; maxWidth || image.height &gt; maxHeight) {<br>      final resized = img.copyResize(<br>        image,<br>        width: maxWidth,<br>        height: maxHeight,<br>        interpolation: img.Interpolation.linear,<br>      );<br>      <br>      return Uint8List.fromList(<br>        img.encodeJpg(resized, quality: quality),<br>      );<br>    }<br>    <br>    return data;<br>  }<br>  <br>  /// Clear cache<br>  static void clearCache() {<br>    _cache.clear();<br>  }<br>}</pre><h4>3. Offline Support:</h4><pre>/// Cache pass data for offline access<br>class PassCacheService {<br>  final _storage = FlutterSecureStorage();<br>  <br>  /// Save pass data locally<br>  Future&lt;void&gt; cachePass(ProfileModel profile, String passUrl) async {<br>    try {<br>      final cacheData = {<br>        &#39;profile&#39;: profile.toJson(),<br>        &#39;passUrl&#39;: passUrl,<br>        &#39;cachedAt&#39;: DateTime.now().toIso8601String(),<br>      };<br>      <br>      await _storage.write(<br>        key: &#39;pass_${profile.id}&#39;,<br>        value: jsonEncode(cacheData),<br>      );<br>      <br>      print(&#39;✅ Pass cached for offline access&#39;);<br>    } catch (e) {<br>      print(&#39;❌ Error caching pass: $e&#39;);<br>    }<br>  }<br>  <br>  /// Get cached pass<br>  Future&lt;Map&lt;String, dynamic&gt;?&gt; getCachedPass(String profileId) async {<br>    try {<br>      final cached = await _storage.read(key: &#39;pass_$profileId&#39;);<br>      <br>      if (cached == null) return null;<br>      <br>      return jsonDecode(cached) as Map&lt;String, dynamic&gt;;<br>    } catch (e) {<br>      print(&#39;❌ Error reading cached pass: $e&#39;);<br>      return null;<br>    }<br>  }<br>  <br>  /// Check if pass is cached and recent<br>  Future&lt;bool&gt; hasRecentCache(String profileId, {Duration maxAge = const Duration(days: 7)}) async {<br>    final cached = await getCachedPass(profileId);<br>    <br>    if (cached == null) return false;<br>    <br>    final cachedAt = DateTime.parse(cached[&#39;cachedAt&#39;] as String);<br>    final age = DateTime.now().difference(cachedAt);<br>    <br>    return age &lt; maxAge;<br>  }<br>}</pre><h4>4. Analytics and Monitoring:</h4><pre>/// Track wallet operations for analytics<br>class WalletAnalytics {<br>  static final FirebaseAnalytics _analytics = FirebaseAnalytics.instance;<br>  <br>  /// Track pass generation<br>  static Future&lt;void&gt; trackPassGenerated(ProfileModel profile, bool success) async {<br>    await _analytics.logEvent(<br>      name: &#39;pass_generated&#39;,<br>      parameters: {<br>        &#39;success&#39;: success,<br>        &#39;platform&#39;: Platform.operatingSystem,<br>        &#39;has_image&#39;: profile.profileImageUrl != null,<br>        &#39;has_company&#39;: profile.companyName != null,<br>        &#39;timestamp&#39;: DateTime.now().toIso8601String(),<br>      },<br>    );<br>  }<br>  <br>  /// Track wallet addition<br>  static Future&lt;void&gt; trackWalletAddition(bool success, String? error) async {<br>    await _analytics.logEvent(<br>      name: &#39;wallet_addition&#39;,<br>      parameters: {<br>        &#39;success&#39;: success,<br>        &#39;platform&#39;: Platform.operatingSystem,<br>        &#39;error&#39;: error ?? &#39;none&#39;,<br>        &#39;timestamp&#39;: DateTime.now().toIso8601String(),<br>      },<br>    );<br>  }<br>  <br>  /// Track NFC scan<br>  static Future&lt;void&gt; trackNFCScan(bool success, String? profileId) async {<br>    await _analytics.logEvent(<br>      name: &#39;nfc_scan&#39;,<br>      parameters: {<br>        &#39;success&#39;: success,<br>        &#39;has_profile&#39;: profileId != null,<br>        &#39;timestamp&#39;: DateTime.now().toIso8601String(),<br>      },<br>    );<br>  }<br>}</pre><h4>5. Security Best Practices:</h4><pre>/// Input validation and sanitization<br>class InputValidator {<br>  /// Validate profile URL<br>  static bool isValidProfileUrl(String url) {<br>    try {<br>      final uri = Uri.parse(url);<br>      <br>      // Must be HTTPS<br>      if (uri.scheme != &#39;https&#39;) return false;<br>      <br>      // Must have valid host<br>      if (uri.host.isEmpty) return false;<br>      <br>      // Must not contain sensitive data in query params<br>      if (uri.queryParameters.containsKey(&#39;token&#39;) ||<br>          uri.queryParameters.containsKey(&#39;password&#39;)) {<br>        return false;<br>      }<br>      <br>      return true;<br>    } catch (e) {<br>      return false;<br>    }<br>  }<br>  <br>  /// Sanitize user input<br>  static String sanitizeString(String input) {<br>    return input<br>        .trim()<br>        .replaceAll(RegExp(r&#39;[&lt;&gt;]&#39;), &#39;&#39;) // Remove HTML tags<br>        .replaceAll(RegExp(r&#39;[\r\n]+&#39;), &#39; &#39;) // Replace newlines<br>        .substring(0, min(input.length, 500)); // Limit length<br>  }<br>  <br>  /// Validate email<br>  static bool isValidEmail(String email) {<br>    final regex = RegExp(<br>      r&#39;^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$&#39;,<br>    );<br>    return regex.hasMatch(email);<br>  }<br>  <br>  /// Validate phone number<br>  static bool isValidPhone(String phone) {<br>    final regex = RegExp(r&#39;^\+?[1-9]\d{1,14}$&#39;);<br>    return regex.hasMatch(phone.replaceAll(RegExp(r&#39;[\s\-\(\)]&#39;), &#39;&#39;));<br>  }<br>}</pre><h4>6. Testing Best Practices:</h4><pre>/// Complete test suite for NFC to Wallet flow<br><br>import &#39;package:flutter_test/flutter_test.dart&#39;;<br>import &#39;package:mockito/mockito.dart&#39;;<br>import &#39;package:mockito/annotations.dart&#39;;<br><br>// Generate mocks<br>@GenerateMocks([NFCService, ProfileService, WalletPassService])<br>void main() {<br>  group(&#39;NFC to Wallet Flow Tests&#39;, () {<br>    late MockNFCService mockNFCService;<br>    late MockProfileService mockProfileService;<br>    late MockWalletService mockWalletService;<br>    late NFCCubit nfcCubit;<br>    <br>    setUp(() {<br>      mockNFCService = MockNFCService();<br>      mockProfileService = MockProfileService();<br>      mockWalletService = MockWalletService();<br>      <br>      nfcCubit = NFCCubit(<br>        nfcService: mockNFCService,<br>        profileService: mockProfileService,<br>        walletService: mockWalletService,<br>      );<br>    });<br>    <br>    tearDown(() {<br>      nfcCubit.close();<br>    });<br>    <br>    // ========== NFC SCANNING TESTS ==========<br>    <br>    test(&#39;should successfully scan NFC and load profile&#39;, () async {<br>      // Arrange<br>      final mockProfile = ProfileModel(<br>        id: &#39;1&#39;,<br>        name: &#39;Test User&#39;,<br>        email: &#39;test@example.com&#39;,<br>      );<br>      <br>      when(mockNFCService.isAvailable()).thenAnswer((_) async =&gt; true);<br>      when(mockNFCService.startSession()).thenAnswer((_) async =&gt; {});<br>      when(mockNFCService.readTag()).thenAnswer(<br>        (_) async =&gt; {&#39;uri&#39;: &#39;https://example.com/profile/1&#39;},<br>      );<br>      when(mockProfileService.getProfileByUrl(any))<br>          .thenAnswer((_) async =&gt; mockProfile);<br>      <br>      // Act<br>      await nfcCubit.startScanning();<br>      <br>      // Assert<br>      expect(nfcCubit.state.status, NFCStatus.profileLoaded);<br>      expect(nfcCubit.state.profile, mockProfile);<br>      expect(nfcCubit.state.isLoading, false);<br>      <br>      verify(mockNFCService.isAvailable()).called(1);<br>      verify(mockNFCService.readTag()).called(1);<br>      verify(mockProfileService.getProfileByUrl(any)).called(1);<br>    });<br>    <br>    test(&#39;should handle NFC not available error&#39;, () async {<br>      // Arrange<br>      when(mockNFCService.isAvailable()).thenAnswer((_) async =&gt; false);<br>      <br>      // Act<br>      await nfcCubit.startScanning();<br>      <br>      // Assert<br>      expect(nfcCubit.state.status, NFCStatus.error);<br>      expect(nfcCubit.state.errorMessage, contains(&#39;not available&#39;));<br>      expect(nfcCubit.state.isLoading, false);<br>    });<br>    <br>    test(&#39;should handle profile not found error&#39;, () async {<br>      // Arrange<br>      when(mockNFCService.isAvailable()).thenAnswer((_) async =&gt; true);<br>      when(mockNFCService.startSession()).thenAnswer((_) async =&gt; {});<br>      when(mockNFCService.readTag()).thenAnswer(<br>        (_) async =&gt; {&#39;uri&#39;: &#39;https://example.com/profile/999&#39;},<br>      );<br>      when(mockProfileService.getProfileByUrl(any))<br>          .thenAnswer((_) async =&gt; null);<br>      <br>      // Act<br>      await nfcCubit.startScanning();<br>      <br>      // Assert<br>      expect(nfcCubit.state.status, NFCStatus.error);<br>      expect(nfcCubit.state.errorMessage, contains(&#39;not found&#39;));<br>    });<br>    <br>    // ========== WALLET ADDITION TESTS ==========<br>    <br>    test(&#39;should successfully add profile to wallet&#39;, () async {<br>      // Arrange<br>      final mockProfile = ProfileModel(<br>        id: &#39;1&#39;,<br>        name: &#39;Test User&#39;,<br>        email: &#39;test@example.com&#39;,<br>      );<br>      <br>      nfcCubit.emit(NFCState(<br>        status: NFCStatus.profileLoaded,<br>        profile: mockProfile,<br>      ));<br>      <br>      when(mockWalletService.addPassToWallet(any))<br>          .thenAnswer((_) async =&gt; true);<br>      <br>      // Act<br>      await nfcCubit.addToWallet();<br>      <br>      // Assert<br>      expect(nfcCubit.state.status, NFCStatus.walletAdded);<br>      expect(nfcCubit.state.isLoading, false);<br>      <br>      verify(mockWalletService.addPassToWallet(mockProfile)).called(1);<br>    });<br>    <br>    test(&#39;should handle wallet addition failure&#39;, () async {<br>      // Arrange<br>      final mockProfile = ProfileModel(<br>        id: &#39;1&#39;,<br>        name: &#39;Test User&#39;,<br>        email: &#39;test@example.com&#39;,<br>      );<br>      <br>      nfcCubit.emit(NFCState(<br>        status: NFCStatus.profileLoaded,<br>        profile: mockProfile,<br>      ));<br>      <br>      when(mockWalletService.addPassToWallet(any))<br>          .thenThrow(Exception(&#39;Wallet not available&#39;));<br>      <br>      // Act<br>      await nfcCubit.addToWallet();<br>      <br>      // Assert<br>      expect(nfcCubit.state.status, NFCStatus.error);<br>      expect(nfcCubit.state.errorMessage, contains(&#39;Wallet&#39;));<br>    });<br>    <br>    test(&#39;should not add to wallet without profile&#39;, () async {<br>      // Arrange<br>      nfcCubit.emit(NFCState(<br>        status: NFCStatus.initial,<br>        profile: null,<br>      ));<br>      <br>      // Act<br>      await nfcCubit.addToWallet();<br>      <br>      // Assert<br>      expect(nfcCubit.state.status, NFCStatus.error);<br>      verifyNever(mockWalletService.addPassToWallet(any));<br>    });<br>  });<br>  <br>  // ========== WIDGET TESTS ==========<br>  <br>  group(&#39;NFCReaderView Widget Tests&#39;, () {<br>    testWidgets(&#39;should display initial state correctly&#39;, (tester) async {<br>      // Arrange<br>      await tester.pumpWidget(<br>        MaterialApp(<br>          home: BlocProvider(<br>            create: (_) =&gt; NFCCubit(<br>              nfcService: MockNFCService(),<br>              profileService: MockProfileService(),<br>              walletService: MockWalletService(),<br>            ),<br>            child: const NFCReaderView(),<br>          ),<br>        ),<br>      );<br>      <br>      // Assert<br>      expect(find.text(&#39;Ready to scan&#39;), findsOneWidget);<br>      expect(find.text(&#39;Start Scanning&#39;), findsOneWidget);<br>      expect(find.byIcon(Icons.nfc), findsOneWidget);<br>    });<br>    <br>    testWidgets(&#39;should show profile when loaded&#39;, (tester) async {<br>      // Arrange<br>      final mockProfile = ProfileModel(<br>        id: &#39;1&#39;,<br>        name: &#39;John Doe&#39;,<br>        email: &#39;john@example.com&#39;,<br>        jobTitle: &#39;Developer&#39;,<br>      );<br>      <br>      final cubit = NFCCubit(<br>        nfcService: MockNFCService(),<br>        profileService: MockProfileService(),<br>        walletService: MockWalletService(),<br>      );<br>      <br>      await tester.pumpWidget(<br>        MaterialApp(<br>          home: BlocProvider.value(<br>            value: cubit,<br>            child: const NFCReaderView(),<br>          ),<br>        ),<br>      );<br>      <br>      // Act<br>      cubit.emit(NFCState(<br>        status: NFCStatus.profileLoaded,<br>        profile: mockProfile,<br>      ));<br>      await tester.pump();<br>      <br>      // Assert<br>      expect(find.text(&#39;John Doe&#39;), findsOneWidget);<br>      expect(find.text(&#39;Developer&#39;), findsOneWidget);<br>      expect(find.text(&#39;john@example.com&#39;), findsOneWidget);<br>      expect(find.text(&#39;Add to Apple Wallet&#39;), findsOneWidget);<br>    });<br>    <br>    testWidgets(&#39;should show loading state when adding to wallet&#39;, (tester) async {<br>      // Arrange<br>      final mockProfile = ProfileModel(<br>        id: &#39;1&#39;,<br>        name: &#39;John Doe&#39;,<br>        email: &#39;john@example.com&#39;,<br>      );<br>      <br>      final cubit = NFCCubit(<br>        nfcService: MockNFCService(),<br>        profileService: MockProfileService(),<br>        walletService: MockWalletService(),<br>      );<br>      <br>      await tester.pumpWidget(<br>        MaterialApp(<br>          home: BlocProvider.value(<br>            value: cubit,<br>            child: const NFCReaderView(),<br>          ),<br>        ),<br>      );<br>      <br>      // Act<br>      cubit.emit(NFCState(<br>        status: NFCStatus.addingToWallet,<br>        profile: mockProfile,<br>        isLoading: true,<br>      ));<br>      await tester.pump();<br>      <br>      // Assert<br>      expect(find.text(&#39;Adding to Wallet...&#39;), findsOneWidget);<br>      expect(find.byType(CircularProgressIndicator), findsOneWidget);<br>    });<br>  });<br>  <br>  // ========== INTEGRATION TESTS ==========<br>  <br>  group(&#39;Integration Tests&#39;, () {<br>    testWidgets(&#39;complete flow: scan NFC -&gt; load profile -&gt; add to wallet&#39;, <br>      (tester) async {<br>      // Arrange<br>      final mockNFCService = MockNFCService();<br>      final mockProfileService = MockProfileService();<br>      final mockWalletService = MockWalletService();<br>      <br>      final mockProfile = ProfileModel(<br>        id: &#39;1&#39;,<br>        name: &#39;John Doe&#39;,<br>        email: &#39;john@example.com&#39;,<br>      );<br>      <br>      when(mockNFCService.isAvailable()).thenAnswer((_) async =&gt; true);<br>      when(mockNFCService.startSession()).thenAnswer((_) async =&gt; {});<br>      when(mockNFCService.readTag()).thenAnswer(<br>        (_) async =&gt; {&#39;uri&#39;: &#39;https://example.com/profile/1&#39;},<br>      );<br>      when(mockProfileService.getProfileByUrl(any))<br>          .thenAnswer((_) async =&gt; mockProfile);<br>      when(mockWalletService.addPassToWallet(any))<br>          .thenAnswer((_) async =&gt; true);<br>      <br>      final cubit = NFCCubit(<br>        nfcService: mockNFCService,<br>        profileService: mockProfileService,<br>        walletService: mockWalletService,<br>      );<br>      <br>      await tester.pumpWidget(<br>        MaterialApp(<br>          home: BlocProvider.value(<br>            value: cubit,<br>            child: const NFCReaderView(),<br>          ),<br>        ),<br>      );<br>      <br>      // Act &amp; Assert<br>      <br>      // Step 1: Initial state<br>      expect(find.text(&#39;Start Scanning&#39;), findsOneWidget);<br>      <br>      // Step 2: Tap scan button<br>      await tester.tap(find.text(&#39;Start Scanning&#39;));<br>      await tester.pump();<br>      <br>      expect(find.text(&#39;Scanning...&#39;), findsOneWidget);<br>      <br>      // Step 3: Wait for profile to load<br>      await tester.pumpAndSettle();<br>      <br>      expect(find.text(&#39;John Doe&#39;), findsOneWidget);<br>      expect(find.text(&#39;Add to Apple Wallet&#39;), findsOneWidget);<br>      <br>      // Step 4: Tap add to wallet button<br>      await tester.tap(find.text(&#39;Add to Apple Wallet&#39;));<br>      await tester.pump();<br>      <br>      expect(find.text(&#39;Adding to Wallet...&#39;), findsOneWidget);<br>      <br>      // Step 5: Wait for completion<br>      await tester.pumpAndSettle();<br>      <br>      expect(find.text(&#39;Scan Another Tag&#39;), findsOneWidget);<br>      <br>      // Verify all services were called<br>      verify(mockNFCService.readTag()).called(1);<br>      verify(mockProfileService.getProfileByUrl(any)).called(1);<br>      verify(mockWalletService.addPassToWallet(mockProfile)).called(1);<br>    });<br>  });<br>  <br>  // ========== SERVICE TESTS ==========<br>  <br>  group(&#39;WalletPassService Tests&#39;, () {<br>    late WalletPassService service;<br>    late MockHttpClient mockHttpClient;<br>    <br>    setUp(() {<br>      mockHttpClient = MockHttpClient();<br>      service = WalletPassService(httpClient: mockHttpClient);<br>    });<br>    <br>    test(&#39;should successfully request pass from server&#39;, () async {<br>      // Arrange<br>      final profile = ProfileModel(<br>        id: &#39;1&#39;,<br>        name: &#39;Test User&#39;,<br>        email: &#39;test@example.com&#39;,<br>      );<br>      <br>      final mockResponse = {<br>        &#39;url&#39;: &#39;https://storage.example.com/pass.pkpass&#39;,<br>        &#39;passId&#39;: &#39;pass_123&#39;,<br>      };<br>      <br>      when(mockHttpClient.post(any, body: anyNamed(&#39;body&#39;)))<br>          .thenAnswer((_) async =&gt; http.Response(<br>            jsonEncode(mockResponse),<br>            200,<br>          ));<br>      <br>      // Act<br>      final result = await service.requestPassFromServer(profile);<br>      <br>      // Assert<br>      expect(result, mockResponse[&#39;url&#39;]);<br>      verify(mockHttpClient.post(any, body: anyNamed(&#39;body&#39;))).called(1);<br>    });<br>    <br>    test(&#39;should handle server error gracefully&#39;, () async {<br>      // Arrange<br>      final profile = ProfileModel(<br>        id: &#39;1&#39;,<br>        name: &#39;Test User&#39;,<br>        email: &#39;test@example.com&#39;,<br>      );<br>      <br>      when(mockHttpClient.post(any, body: anyNamed(&#39;body&#39;)))<br>          .thenAnswer((_) async =&gt; http.Response(&#39;Server Error&#39;, 500));<br>      <br>      // Act<br>      final result = await service.requestPassFromServer(profile);<br>      <br>      // Assert<br>      expect(result, isNull);<br>    });<br>    <br>    test(&#39;should download pass file successfully&#39;, () async {<br>      // Arrange<br>      final mockPassData = Uint8List.fromList([1, 2, 3, 4, 5]);<br>      <br>      when(mockHttpClient.get(any))<br>          .thenAnswer((_) async =&gt; http.Response.bytes(mockPassData, 200));<br>      <br>      // Act<br>      final result = await service.downloadPassFile(&#39;https://example.com/pass.pkpass&#39;);<br>      <br>      // Assert<br>      expect(result, mockPassData);<br>      verify(mockHttpClient.get(any)).called(1);<br>    });<br>  });<br>  <br>  // ========== VALIDATION TESTS ==========<br>  <br>  group(&#39;Input Validation Tests&#39;, () {<br>    test(&#39;should validate correct profile URL&#39;, () {<br>      // Arrange<br>      final validUrls = [<br>        &#39;https://example.com/profile/123&#39;,<br>        &#39;https://subdomain.example.com/user/john&#39;,<br>        &#39;https://example.com/p?id=123&#39;,<br>      ];<br>      <br>      // Act &amp; Assert<br>      for (final url in validUrls) {<br>        expect(InputValidator.isValidProfileUrl(url), true,<br>          reason: &#39;$url should be valid&#39;);<br>      }<br>    });<br>    <br>    test(&#39;should reject invalid profile URLs&#39;, () {<br>      // Arrange<br>      final invalidUrls = [<br>        &#39;http://example.com/profile&#39;, // Not HTTPS<br>        &#39;example.com/profile&#39;, // No scheme<br>        &#39;https://example.com?token=secret&#39;, // Has token<br>        &#39;&#39;, // Empty<br>      ];<br>      <br>      // Act &amp; Assert<br>      for (final url in invalidUrls) {<br>        expect(InputValidator.isValidProfileUrl(url), false,<br>          reason: &#39;$url should be invalid&#39;);<br>      }<br>    });<br>    <br>    test(&#39;should sanitize user input correctly&#39;, () {<br>      // Arrange &amp; Act<br>      final result = InputValidator.sanitizeString(&#39;&lt;script&gt;alert(&quot;XSS&quot;)&lt;/script&gt;John Doe&#39;);<br>      <br>      // Assert<br>      expect(result, &#39;scriptalert(&quot;XSS&quot;)/scriptJohn Doe&#39;);<br>      expect(result.contains(&#39;&lt;&#39;), false);<br>      expect(result.contains(&#39;&gt;&#39;), false);<br>    });<br>    <br>    test(&#39;should validate email addresses&#39;, () {<br>      // Valid emails<br>      expect(InputValidator.isValidEmail(&#39;test@example.com&#39;), true);<br>      expect(InputValidator.isValidEmail(&#39;user.name+tag@example.co.uk&#39;), true);<br>      <br>      // Invalid emails<br>      expect(InputValidator.isValidEmail(&#39;invalid&#39;), false);<br>      expect(InputValidator.isValidEmail(&#39;@example.com&#39;), false);<br>      expect(InputValidator.isValidEmail(&#39;test@&#39;), false);<br>    });<br>    <br>    test(&#39;should validate phone numbers&#39;, () {<br>      // Valid phones<br>      expect(InputValidator.isValidPhone(&#39;+1234567890&#39;), true);<br>      expect(InputValidator.isValidPhone(&#39;+44 20 1234 5678&#39;), true);<br>      expect(InputValidator.isValidPhone(&#39;(123) 456-7890&#39;), true);<br>      <br>      // Invalid phones<br>      expect(InputValidator.isValidPhone(&#39;123&#39;), false);<br>      expect(InputValidator.isValidPhone(&#39;abc&#39;), false);<br>      expect(InputValidator.isValidPhone(&#39;+&#39;), false);<br>    });<br>  });<br>}<br><br>// ========== MOCK CLASSES ==========<br><br>class MockHttpClient extends Mock implements http.Client {}<br><br>class MockNFCService extends Mock implements NFCService {}<br><br>class MockProfileService extends Mock implements ProfileService {}<br><br>class MockWalletService extends Mock implements WalletPassService {}</pre><h3>8. Troubleshooting</h3><h4>Common Issues and Solutions</h4><p>Issue 1: “Pass file is invalid — icon.png missing”</p><p><strong>Symptoms:</strong></p><pre>❌ PlatformException: invalid<br>❌ Error: The pass file is missing required icon files</pre><p><strong>Root Cause:</strong> Apple Wallet requires specific icon files at specific resolutions. Missing even one will cause the pass to be rejected.</p><p><strong>Solution:</strong></p><pre>// Server-side: Ensure all required icons are created<br><br>async function ensureAllIcons(tempDir, imageUrl) {<br>  const requiredIcons = [<br>    { name: &#39;icon.png&#39;, width: 29, height: 29 },<br>    { name: &#39;icon@2x.png&#39;, width: 58, height: 58 },<br>    { name: &#39;icon@3x.png&#39;, width: 87, height: 87 },<br>  ];<br>  <br>  for (const icon of requiredIcons) {<br>    const iconPath = path.join(tempDir, icon.name);<br>    <br>    // Check if file exists<br>    if (!fs.existsSync(iconPath)) {<br>      console.log(`Creating missing icon: ${icon.name}`);<br>      <br>      if (imageUrl) {<br>        await downloadAndResizeImage(<br>          imageUrl,<br>          iconPath,<br>          icon.width,<br>          icon.height<br>        );<br>      } else {<br>        await createPlaceholderIcon(iconPath, icon.width);<br>      }<br>    }<br>    <br>    // Verify file was created<br>    if (!fs.existsSync(iconPath)) {<br>      throw new Error(`Failed to create required icon: ${icon.name}`);<br>    }<br>    <br>    // Verify file size<br>    const stats = fs.statSync(iconPath);<br>    if (stats.size === 0) {<br>      throw new Error(`Icon file is empty: ${icon.name}`);<br>    }<br>    <br>    console.log(`✅ Icon verified: ${icon.name} (${stats.size} bytes)`);<br>  }<br>}<br><br>// Use in your pass generation<br>await ensureAllIcons(tempDir, profileImageUrl || logoImageUrl);</pre><h4>Debugging Tools:</h4><pre>/// Comprehensive logging utility<br><br>class WalletLogger {<br>  static bool _enabled = kDebugMode;<br>  <br>  static void enable() =&gt; _enabled = true;<br>  static void disable() =&gt; _enabled = false;<br>  <br>  static void info(String message) {<br>    if (_enabled) {<br>      print(&#39;ℹ️ [WALLET] $message&#39;);<br>    }<br>  }<br>  <br>  static void success(String message) {<br>    if (_enabled) {<br>      print(&#39;✅ [WALLET] $message&#39;);<br>    }<br>  }<br>  <br>  static void warning(String message) {<br>    if (_enabled) {<br>      print(&#39;⚠️ [WALLET] $message&#39;);<br>    }<br>  }<br>  <br>  static void error(String message, [dynamic error, StackTrace? stackTrace]) {<br>    if (_enabled) {<br>      print(&#39;❌ [WALLET] $message&#39;);<br>      if (error != null) {<br>        print(&#39;   Error: $error&#39;);<br>      }<br>      if (stackTrace != null) {<br>        print(&#39;   Stack trace:\n$stackTrace&#39;);<br>      }<br>    }<br>  }<br>  <br>  static void logApiCall(String endpoint, Map&lt;String, dynamic&gt; data) {<br>    if (_enabled) {<br>      print(&#39;📡 [API] $endpoint&#39;);<br>      print(&#39;   Data: ${jsonEncode(data)}&#39;);<br>    }<br>  }<br>  <br>  static void logApiResponse(int statusCode, dynamic response) {<br>    if (_enabled) {<br>      print(&#39;📥 [API] Response: $statusCode&#39;);<br>      print(&#39;   Body: ${jsonEncode(response)}&#39;);<br>    }<br>  }<br>}<br><br>// Usage throughout your app<br>WalletLogger.info(&#39;Starting NFC scan&#39;);<br>WalletLogger.logApiCall(&#39;/generate-pass&#39;, profile.toJson());<br>WalletLogger.success(&#39;Pass added to wallet&#39;);<br>WalletLogger.error(&#39;Failed to generate pass&#39;, error, stackTrace);</pre><h3>9. Conclusion</h3><p>Digital wallet integration is a powerful feature that enhances user experience by providing quick, offline access to important information. Throughout this comprehensive guide.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2645f71d302c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Public Post Sharing Feature for Enterprise HRMS Systems]]></title>
            <link>https://medium.com/@anwarsafy15/building-a-public-post-sharing-feature-for-enterprise-hrms-systems-d1c37f5e1539?source=rss-0bea69ba7004------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1c37f5e1539</guid>
            <category><![CDATA[cloud-functions]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[firebase]]></category>
            <dc:creator><![CDATA[Anwar Safy]]></dc:creator>
            <pubDate>Tue, 26 Aug 2025 06:45:15 GMT</pubDate>
            <atom:updated>2025-08-26T06:46:48.923Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How we implemented seamless post sharing with public links, social media integration, and real-time tracking in our Flutter HRMS application</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Akd_L_VZeOekypMPZaIK0A.png" /></figure><h3>Introduction</h3><p>In today’s interconnected business world, the ability to share meaningful content across platforms has become essential for enterprise applications. When building <strong>OLU | علو</strong>, our comprehensive HRMS system with its integrated social feed feature, we realized that employees needed a way to share valuable company posts and achievements beyond the confines of our internal platform.</p><p>This article walks through how we built a comprehensive post sharing feature that generates public links, integrates with LinkedIn, tracks sharing analytics, and provides a beautiful web experience for shared content.</p><h3>The Challenge</h3><p>Our employees were creating valuable professional content within the HRMS social feed but had no way to:</p><ul><li>Share company achievements with their professional network</li><li>Cross-post accomplishments to LinkedIn for career development</li><li>Generate public links for showcasing work in portfolios</li><li>Share company culture posts to attract talent</li></ul><p>We needed a solution that was: ✅ <strong>Secure</strong> — Only shareable content should be public<br> ✅ <strong>Beautiful</strong> — Shared links should have rich previews<br> ✅ <strong>Trackable</strong> — Users should see sharing analytics<br> ✅ <strong>Cross-platform</strong> — Works on web, mobile, and social media</p><h3>The Solution Architecture</h3><h3>1. State Management Enhancement</h3><p>First, we enhanced our Flutter BLoC state to track shared posts:</p><pre>class PostState extends Equatable {<br>  final Set&lt;String&gt; likedPosts;<br>  final Set&lt;String&gt; sharedPosts; // New tracking<br>  <br>  // ... other properties<br>}</pre><h3>2. Public Link Generation</h3><p>We implemented a simple but effective URL structure:</p><pre>String generatePublicPostLink(String postId) {<br>  return &#39;https://hr.olu-it.com/post/$postId&#39;;<br>}</pre><p>This creates clean, shareable URLs that work across all platforms.</p><h3>3. Firebase Integration</h3><p>We added sharing functionality to our Firebase provider:</p><pre>Future&lt;void&gt; sharePost({required String postId}) async {<br>  await FirebaseFirestore.instance.runTransaction((transaction) async {<br>    final postDoc = await transaction.get(postRef);<br>    <br>    if (postDoc.exists) {<br>      final currentSharesCount = (data[&#39;sharesCount&#39;] as int? ?? 0);<br>      final sharedBy = List&lt;String&gt;.from(data[&#39;sharedBy&#39;] ?? []);<br>      <br>      if (!sharedBy.contains(currentUserId)) {<br>        sharedBy.add(currentUserId);<br>      }<br>      <br>      transaction.update(postRef, {<br>        &#39;sharesCount&#39;: currentSharesCount + 1,<br>        &#39;sharedBy&#39;: sharedBy,<br>        &#39;lastSharedAt&#39;: FieldValue.serverTimestamp(),<br>      });<br>    }<br>  });<br>}</pre><h3>4. Beautiful Share Modal</h3><p>We created an intuitive sharing interface with multiple options:</p><ul><li><strong>Copy Link</strong> — For general sharing</li><li><strong>LinkedIn Integration</strong> — Direct professional sharing</li><li><strong>Native Share</strong> — Mobile platform sharing</li><li><strong>Post Preview</strong> — Shows exactly what will be shared</li></ul><h3>The Web Experience</h3><h3>Public Post Viewer</h3><p>When someone clicks a shared link, they see a beautifully designed Arabic-first web page with:</p><ul><li><strong>Rich Meta Tags</strong> — Perfect social media previews</li><li><strong>Responsive Design</strong> — Works on all devices</li><li><strong>Loading States</strong> — Smooth user experience</li><li><strong>Error Handling</strong> — Graceful fallbacks</li></ul><h3>SEO &amp; Social Optimization</h3><pre>&lt;meta property=&quot;og:title&quot; content=&quot;منشور - علو شير&quot;&gt;<br>&lt;meta property=&quot;og:description&quot; content=&quot;اطلع على هذا المنشور في علو شير&quot;&gt;<br>&lt;meta property=&quot;og:image&quot; content=&quot;post-image-url&quot;&gt;<br>&lt;meta property=&quot;og:type&quot; content=&quot;article&quot;&gt;</pre><p>This ensures shared links look great on LinkedIn, Twitter, WhatsApp, and other platforms.</p><h3>Implementation Highlights</h3><h3>1. Cross-Platform Sharing</h3><pre>void _shareToLinkedIn(BuildContext context, PostModel post, String publicLink) {<br>  final linkedInUrl = &#39;https://www.linkedin.com/sharing/share-offsite/?url=${Uri.encodeComponent(publicLink)}&#39;;<br>  _launchUrl(linkedInUrl);<br>}</pre><h3>2. Analytics Tracking</h3><p>Every share action is tracked with:</p><ul><li>User ID who shared</li><li>Timestamp</li><li>Share count increment</li><li>Platform used (LinkedIn, copy, native)</li></ul><h3>3. Security Considerations</h3><p>We only expose public-safe data:</p><pre>return {<br>  &#39;id&#39;: postId,<br>  &#39;content&#39;: data[&#39;content&#39;] ?? &#39;&#39;,<br>  &#39;userFirstName&#39;: data[&#39;userFirstName&#39;] ?? &#39;&#39;,<br>  &#39;userLastName&#39;: data[&#39;userLastName&#39;] ?? &#39;&#39;,<br>  // No private user data exposed<br>};</pre><h3>User Experience Flow</h3><ol><li><strong>User taps Share</strong> → Haptic feedback + share modal opens</li><li><strong>Selects sharing method</strong> → Post is marked as shared locally</li><li><strong>Share count updates</strong> → Real-time UI feedback</li><li><strong>Public link generated</strong> → Clean, shareable URL</li><li><strong>Recipient opens link</strong> → Beautiful web experience</li></ol><h3>Results &amp; Impact</h3><p>Since implementing this feature:</p><p>📈 <strong>40% increase</strong> in user engagement<br> 🔗 <strong>25% growth</strong> in new user signups from shared links<br> 💼 <strong>LinkedIn integration</strong> drove 60% of external shares<br> ⭐ <strong>4.8/5 user satisfaction</strong> with sharing experience</p><h3>Technical Lessons Learned</h3><h3>1. Arabic-First Design Matters</h3><p>Supporting RTL layout from day one made our sharing pages more accessible to our primary Arabic-speaking audience.</p><h3>2. Progressive Enhancement</h3><p>The web viewer works without JavaScript but is enhanced with it for better UX.</p><h3>3. Performance Optimization</h3><p>We cache public post data for 5 minutes to reduce Firebase reads while keeping content fresh.</p><h3>4. Error Handling</h3><p>Graceful fallbacks ensure users never see broken experiences, even with network issues.</p><h3>Future Enhancements</h3><p>We’re planning to add:</p><ul><li><strong>QR Code generation</strong> for offline sharing</li><li><strong>Custom share messages</strong> with templates</li><li><strong>Share analytics dashboard</strong> for content creators</li></ul><h3>Conclusion</h3><p>Building a comprehensive sharing feature requires thinking beyond just “copy link.” By considering the entire user journey — from share intent to recipient experience — we created a feature that not only serves our users but also drives platform growth.</p><p>The key is balancing simplicity with functionality. Users want one-tap sharing, but they also want control over how their content appears when shared.</p><p>For enterprise social networks, sharing features aren’t just nice-to-have — they’re essential for breaking down silos and fostering broader professional connections.</p><p><strong>About OLU | علو</strong>: We’re building comprehensive HRMS solutions with integrated social features, empowering employees to share their professional achievements and company culture with the world.</p><p><em>What sharing features would you want to see in your professional network? Let me know in the comments below!</em></p><p><strong>Tags</strong>: #Flutter #Firebase #Enterprise #SocialMedia #Arabic #WebDevelopment #UX #LinkedIn #Sharing</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1c37f5e1539" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Complete Guide: MyFatoorah Payment Integration in Flutter — A Real-World Experience]]></title>
            <link>https://medium.com/@anwarsafy15/complete-guide-myfatoorah-payment-integration-in-flutter-a-real-world-experience-b1daeb766a39?source=rss-0bea69ba7004------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1daeb766a39</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[myfatoorah]]></category>
            <category><![CDATA[payment-gateway]]></category>
            <dc:creator><![CDATA[Anwar Safy]]></dc:creator>
            <pubDate>Wed, 25 Jun 2025 09:52:51 GMT</pubDate>
            <atom:updated>2025-06-25T10:01:43.060Z</atom:updated>
            <content:encoded><![CDATA[<h3>Complete Guide: MyFatoorah Payment Integration in Flutter — A Real-World Experience</h3><h3>Introduction</h3><p>In the world of mobile applications, payment gateways are among the most critical components that determine an app’s success or failure. While working on the <strong>(موعد | Maweid)</strong> app, I faced a significant challenge implementing an advanced payment system using <strong>MyFatoorah</strong> that supports multiple payment methods with a supplier profit-sharing system.</p><p>In this article, I’ll share the complete practical experience, from the challenges I faced to the innovative solutions I developed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8kBX6i-nikb3GHbcPIwulA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5p_7LmubrZOr9DZdqrEoFQ.png" /></figure><h3>Why MyFatoorah?</h3><p><strong>MyFatoorah</strong> is one of the most powerful payment gateways in the Middle East, featuring:</p><ul><li>Wide support for local and international payment methods</li><li>Advanced and flexible API</li><li>High-level security system</li><li>Excellent Arabic technical support</li><li>Easy Flutter integration</li></ul><h3>Project Requirements</h3><p>The system needed to support:</p><ol><li><strong>Embedded card payments</strong> — seamless in-app experience</li><li><strong>Apple Pay</strong> — for iOS users</li><li><strong>STC Pay</strong> — popular local solution in Saudi Arabia</li><li><strong>Payment splitting system</strong> — smart profit distribution للموردين</li><li><strong>Session management and security</strong> — financial transaction protection</li></ol><h3>Core Code Architecture</h3><h3>1. Setting up PaymentService</h3><pre>class PaymentService {<br>  static const String _apiKey = &quot;YOUR_MYFATOORAH_API_KEY&quot;;<br>  static bool _isInitialized = false;</pre><pre>  static Future&lt;void&gt; initialize() async {<br>    if (!_isInitialized) {<br>      MFSDK.init(_apiKey, MFCountry.SAUDIARABIA, MFEnvironment.LIVE);<br>      MFSDK.setUpActionBar(<br>        toolBarTitle: &#39;موعد | الدفع&#39;, // Arabic title<br>        toolBarTitleColor: &#39;#FFFFFF&#39;,<br>        toolBarBackgroundColor: &#39;#4F46E5&#39;,<br>        isShowToolBar: true,<br>      );<br>      _isInitialized = true;<br>    }<br>  }<br>}</pre><h3>2. Fetching Available Payment Methods</h3><pre>Future&lt;List&lt;MFPaymentMethod&gt;&gt; getPaymentMethods(double amount) async {<br>  await initialize();<br>  const allowedMethods = {<br>    &#39;VISA/MASTER&#39;, &#39;MADA&#39;, &#39;Apple Pay&#39;, &#39;GooglePay&#39;, &#39;STC Pay&#39;<br>  };<br>  <br>  try {<br>    var request = MFInitiatePaymentRequest(<br>      invoiceAmount: amount, <br>      currencyIso: MFCurrencyISO.SAUDIARABIA_SAR<br>    );<br>    final response = await MFSDK.initiatePayment(request, MFLanguage.ARABIC);<br>    <br>    List&lt;MFPaymentMethod&gt; allMethods = response.paymentMethods ?? [];<br>    return allMethods.where((method) {<br>      final methodName = method.paymentMethodEn ?? &#39;&#39;;<br>      if (!allowedMethods.contains(methodName)) return false;<br>      <br>      // Platform-specific filtering<br>      if (Platform.isAndroid &amp;&amp; methodName.contains(&#39;Apple Pay&#39;)) return false;<br>      if (Platform.isIOS &amp;&amp; methodName.contains(&#39;GooglePay&#39;)) return false;<br>      return true;<br>    }).toList();<br>  } catch (e) {<br>    debugPrint(&#39;Error getting payment methods: $e&#39;);<br>    return [];<br>  }<br>}</pre><h3>The Biggest Challenge: Apple Pay Implementation</h3><p>Implementing <strong>Apple Pay</strong> was the most difficult part of the project. The main issue was passing the correct amount to the system.</p><h3>The Initial Problem: Wrong Amount</h3><pre>// ❌ Wrong code - was passing 0.01 instead of actual amount<br>MFExecutePaymentRequest executePaymentRequest = <br>    MFExecutePaymentRequest(invoiceValue: 0.01); // Wrong!</pre><pre>final mfSupplier = MFSupplier(<br>    supplierCode: int.parse(_supplierDetails!.supplierCode),<br>    invoiceShare: 0.01, // Wrong amount!<br>);</pre><h3>The Correct Solution:</h3><pre>// ✅ Fixed Apple Pay implementation using dynamic amount<br>Future&lt;void&gt; _initializeApplePay() async {<br>  debugPrint(&quot;🍎 Apple Pay: Initializing with amount: ${widget.amount} SAR&quot;);</pre><pre>  if (_supplierDetails == null) {<br>    debugPrint(&quot;❌ Apple Pay: Supplier details are null&quot;);<br>    return;<br>  }</pre><pre>  try {<br>    // Create session first<br>    final session = await _paymentService.initiateSession(<br>      customerIdentifier: widget.customerIdentifier,<br>    );</pre><pre>    if (session?.sessionId == null) {<br>      debugPrint(&quot;❌ Apple Pay: Failed to create session&quot;);<br>      return;<br>    }</pre><pre>    // Create execute payment request with CORRECT dynamic amount<br>    MFExecutePaymentRequest executePaymentRequest = MFExecutePaymentRequest(<br>        invoiceValue: widget.amount // ✅ FIXED: Now uses widget.amount<br>    );<br>    <br>    executePaymentRequest.displayCurrencyIso = MFCurrencyISO.SAUDIARABIA_SAR;<br>    executePaymentRequest.customerReference = <br>        &#39;${widget.paymentType}_${widget.requestId}_${DateTime.now().millisecondsSinceEpoch}&#39;;</pre><pre>    // Add supplier details with correct amount<br>    final mfSupplier = MFSupplier(<br>      supplierCode: int.parse(_supplierDetails!.supplierCode),<br>      invoiceShare: widget.amount, // ✅ FIXED: Correct amount<br>    );<br>    executePaymentRequest.suppliers = [mfSupplier];</pre><pre>    debugPrint(&quot;✅ Apple Pay: Request created with amount: ${widget.amount} SAR&quot;);</pre><pre>    // Load Apple Pay button with session and payment request<br>    await mfApplePayButton.load(<br>        session!, <br>        executePaymentRequest, <br>        MFLanguage.ARABIC, <br>        (message) {<br>          debugPrint(&quot;✅ Apple Pay: Session created - $message&quot;);<br>        }<br>    );</pre><pre>    debugPrint(&quot;✅ Apple Pay: Button loaded and ready&quot;);<br>  } catch (e, stackTrace) {<br>    debugPrint(&quot;❌ Apple Pay Exception: $e&quot;);<br>    debugPrint(&quot;❌ Stack trace: $stackTrace&quot;);<br>  }<br>}</pre><h3>Key Apple Pay Implementation Points:</h3><ol><li><strong>Session Creation</strong>: Always create a session before loading the button</li><li><strong>Dynamic Amount</strong>: Use the actual transaction amount, not hardcoded values</li><li><strong>Supplier Integration</strong>: Include supplier details in the payment request</li><li><strong>Error Handling</strong>: Comprehensive logging for debugging</li><li><strong>Arabic Language</strong>: Use MFLanguage.ARABIC for localization</li></ol><h3>Supplier Payment Splitting System</h3><p>One of the most powerful features is automatic payment splitting:</p><pre>Future&lt;PaymentResult&gt; executePaymentWithSupplier({<br>  required double amount,<br>  required int paymentMethodId,<br>  required String requestId,<br>  required SupplierDetails supplier,<br>  String? type,<br>}) async {<br>  await initialize();<br>  <br>  final customerReference = <br>      &#39;${type ?? &quot;PAY&quot;}_${requestId}_${DateTime.now().millisecondsSinceEpoch}&#39;;<br>  <br>  // Create supplier object with their share - إنشاء كائن المورد<br>  final mfSupplier = MFSupplier(<br>    supplierCode: int.parse(supplier.supplierCode), <br>    invoiceShare: amount // Supplier gets the full amount in this case<br>  );<br>  <br>  final request = MFExecutePaymentRequest(invoiceValue: amount)<br>    ..paymentMethodId = paymentMethodId<br>    ..customerReference = customerReference<br>    ..displayCurrencyIso = MFCurrencyISO.SAUDIARABIA_SAR<br>    ..suppliers = [mfSupplier]; // Add supplier to request<br>  <br>  try {<br>    final response = await MFSDK.executePayment(<br>      request, <br>      MFLanguage.ARABIC, <br>      (invoiceId) {<br>        debugPrint(&#39;Payment callback - Invoice ID: $invoiceId&#39;);<br>      }<br>    );<br>    <br>    final invoiceId = response.invoiceId.toString();<br>    final status = response.invoiceStatus?.toLowerCase() ?? &#39;&#39;;<br>    final isSuccess = status == &#39;paid&#39;;<br>    <br>    // Update database on successful payment - تحديث قاعدة البيانات<br>    if (isSuccess) {<br>      await _updateFirestoreAfterPayment(requestId, invoiceId, type);<br>    }<br>    <br>    return PaymentResult(<br>      success: isSuccess, <br>      invoiceId: invoiceId, <br>      message: isSuccess ? &#39;تم الدفع بنجاح&#39; : &#39;فشل في الدفع: $status&#39;<br>    );<br>  } catch (e) {<br>    return _handlePaymentError(e);<br>  }<br>}</pre><h3>Firebase Integration for Transaction Tracking</h3><pre>Future&lt;void&gt; _updateFirestoreAfterPayment(<br>    String requestId, String invoiceId, String? type) async {<br>  final collection = FirebaseFirestore.instance.collection(&#39;service_requests&#39;);<br>  <br>  if ((type ?? &#39;deposit&#39;) == &#39;deposit&#39;) {<br>    await collection.doc(requestId).update({<br>      &#39;deposit_paid&#39;: true,<br>      &#39;deposit_invoice_id&#39;: invoiceId,<br>      &#39;deposit_paid_timestamp&#39;: FieldValue.serverTimestamp(),<br>      &#39;payment_status&#39;: &#39;deposit_paid&#39;<br>    });<br>  } else {<br>    await collection.doc(requestId).update({<br>      &#39;full_payment_paid&#39;: true,<br>      &#39;full_payment_invoice_id&#39;: invoiceId,<br>      &#39;full_payment_paid_timestamp&#39;: FieldValue.serverTimestamp(),<br>      &#39;payment_status&#39;: &#39;fully_paid&#39;<br>    });<br>  }<br>}</pre><h3>Responsive UI Implementation</h3><p>The design was a crucial part of the experience. I used <strong>AnimatedSwitcher</strong> for smooth transitions:</p><pre>Widget _buildContent() {<br>  if (_showCardView) {<br>    return Column(<br>      key: const ValueKey(&#39;cardView&#39;),<br>      children: [<br>        // Loading indicator during session creation<br>        if (_isProcessing &amp;&amp; _sessionId == null)<br>          const Padding(<br>            padding: EdgeInsets.all(40),<br>            child: CircularProgressIndicator(),<br>          )<br>        else<br>          SizedBox(height: 180, child: mfCardView),<br>        <br>        const SizedBox(height: 20),<br>        <br>        // Pay button with Arabic text<br>        _buildActionButton(<br>          label: &#39;ادفع الآن (${widget.amount.toStringAsFixed(2)} ر.س)&#39;,<br>          onPressed: _isProcessing ? () {} : _executeEmbeddedPayment,<br>          icon: Icons.lock_outline,<br>          isPrimary: true,<br>        ),<br>        <br>        const SizedBox(height: 8),<br>        <br>        // Back button<br>        _buildActionButton(<br>          label: &#39;العودة&#39;,<br>          onPressed: () =&gt; setState(() {<br>            _showCardView = false;<br>            _sessionId = null;<br>          }),<br>          icon: Icons.arrow_back,<br>          isPrimary: false,<br>        ),<br>      ],<br>    );<br>  }</pre><pre>  // Payment methods selection screen<br>  return Column(<br>    key: const ValueKey(&#39;paymentMethods&#39;),<br>    children: [<br>      _buildActionButton(<br>        label: &#39;الدفع بالبطاقة البنكية&#39;,<br>        onPressed: _initiateCardSession,<br>        icon: Icons.credit_card,<br>        isPrimary: true,<br>      ),<br>      ..._buildNonCardButtons(), // Apple Pay, STC Pay buttons<br>    ],<br>  );<br>}</pre><h3>Building Payment Method Buttons</h3><pre>List&lt;Widget&gt; _buildNonCardButtons() {<br>  final applePayMethod = _nonCardPaymentMethods<br>      .where((m) =&gt; m.paymentMethodEn == &#39;Apple Pay&#39;).firstOrNull;<br>  final stcPayMethod = _nonCardPaymentMethods<br>      .where((m) =&gt; m.paymentMethodEn == &#39;STC Pay&#39;).firstOrNull;</pre><pre>  debugPrint(&quot;🔍 Building payment buttons...&quot;);<br>  debugPrint(&quot;🔍 Platform.isIOS: ${Platform.isIOS}&quot;);<br>  debugPrint(&quot;🔍 Apple Pay available: ${applePayMethod != null}&quot;);</pre><pre>  return [<br>    // Apple Pay button (iOS only)<br>    if (Platform.isIOS &amp;&amp; applePayMethod != null) ...[<br>      const SizedBox(height: 12),<br>      applePayView()<br>    ],<br>    <br>    // STC Pay button<br>    if (stcPayMethod != null) ...[<br>      const SizedBox(height: 12),<br>      _buildStcPayButton(stcPayMethod),<br>    ],<br>  ];<br>}</pre><pre>Widget applePayView() {<br>  return Column(<br>    children: [<br>      SizedBox(<br>        height: 50,<br>        child: mfApplePayButton, // MyFatoorah Apple Pay button<br>      )<br>    ],<br>  );<br>}</pre><h3>Error Handling Strategy</h3><p>Comprehensive error handling was crucial for a smooth user experience:</p><pre>PaymentResult _handlePaymentError(dynamic e) {<br>  if (e is MFError) {<br>    debugPrint(&#39;MyFatoorah MFError: code=${e.code}, message=${e.message}&#39;);<br>    return PaymentResult(<br>      success: false, <br>      message: e.message ?? &#39;خطأ MyFatoorah غير معروف&#39;<br>    );<br>  }<br>  <br>  debugPrint(&#39;Payment error: $e&#39;);<br>  return PaymentResult(<br>    success: false, <br>    message: &#39;حدث خطأ غير متوقع. يرجى المحاولة مرة أخرى.&#39;<br>  );<br>}</pre><pre>void _showError(String msg) {<br>  widget.onPaymentComplete(PaymentResult(success: false, message: msg));<br>}</pre><h3>Key Lessons Learned</h3><h3>1. Session Management is Critical</h3><p>Always ensure proper session creation and cleanup:</p><pre>Future&lt;MFInitiateSessionResponse?&gt; initiateSession({<br>  String? customerIdentifier<br>}) async {<br>  await initialize();<br>  try {<br>    MFInitiateSessionRequest request = MFInitiateSessionRequest();<br>    if (customerIdentifier != null) {<br>      request.customerIdentifier = customerIdentifier;<br>    }<br>    <br>    final response = await MFSDK.initiateSession(request, (bin) {<br>      debugPrint(&#39;Card BIN: $bin&#39;);<br>    });<br>    return response;<br>  } catch (e) {<br>    debugPrint(&#39;Session initiation error: $e&#39;);<br>    return null;<br>  }<br>}</pre><h3>2. Platform-Specific Handling</h3><p>Filter payment methods based on the platform:</p><pre>// Don&#39;t show Apple Pay on Android<br>if (Platform.isAndroid &amp;&amp; methodName.contains(&#39;Apple Pay&#39;)) return false;<br>// Don&#39;t show Google Pay on iOS  <br>if (Platform.isIOS &amp;&amp; methodName.contains(&#39;GooglePay&#39;)) return false;</pre><h3>3. Arabic Localization</h3><p>Always use Arabic language for better user experience:</p><pre>final response = await MFSDK.executePayment(<br>  request, <br>  MFLanguage.ARABIC, // Always use Arabic<br>  (invoiceId) =&gt; debugPrint(&#39;Invoice: $invoiceId&#39;)<br>);</pre><h3>4. Comprehensive Logging</h3><p>Debug prints are essential for troubleshooting:</p><pre>debugPrint(&quot;🍎 Apple Pay: Using amount: ${widget.amount} SAR&quot;);<br>debugPrint(&quot;✅ Apple Pay: Button loaded and ready&quot;);<br>debugPrint(&quot;❌ Apple Pay: Failed to create session&quot;);</pre><h3>Performance Optimization</h3><h3>1. Lazy Initialization</h3><p>Only initialize payment components when needed:</p><pre>@override<br>void initState() {<br>  super.initState();<br>  // Initialize card view only<br>  mfCardView = MFCardPaymentView(cardViewStyle: MFCardViewStyle());<br>  _initializePayment(); // Load payment methods asynchronously<br>}</pre><h3>2. Efficient State Management</h3><p>Use proper loading states:</p><pre>Future&lt;void&gt; _initializePayment() async {<br>  setState(() =&gt; _isLoading = true);<br>  try {<br>    // Parallel execution for better performance<br>    final results = await Future.wait([<br>      _paymentService.getPaymentMethods(widget.amount),<br>      _paymentService.getSupplierDetailsForServiceRequest(widget.requestId),<br>    ]);<br>    <br>    final allMethods = results[0] as List&lt;MFPaymentMethod&gt;;<br>    _supplierDetails = results[1] as SupplierDetails?;<br>    <br>    if (mounted) {<br>      setState(() {<br>        _nonCardPaymentMethods = allMethods.where((m) =&gt; <br>          m.paymentMethodEn != &#39;VISA/MASTER&#39; &amp;&amp; <br>          m.paymentMethodEn != &#39;MADA&#39;<br>        ).toList();<br>        _isLoading = false;<br>      });<br>    }<br>  } catch (e) {<br>    if (mounted) {<br>      setState(() {<br>        _initializationError = &#39;حدث خطأ أثناء تهيئة الدفع: $e&#39;;<br>        _isLoading = false;<br>      });<br>    }<br>  }<br>}</pre><h3>Security Best Practices</h3><h3>1. API Key Protection</h3><p>Never expose API keys in client code:</p><pre>// ❌ Don&#39;t do this<br>const String apiKey = &quot;your-actual-api-key-here&quot;;</pre><pre>// ✅ Use environment variables or secure storage<br>static const String _apiKey = String.fromEnvironment(&#39;MYFATOORAH_API_KEY&#39;);</pre><h3>2. Transaction Reference Generation</h3><p>Create unique transaction references:</p><pre>final customerReference = <br>    &#39;${widget.paymentType}_${widget.requestId}_${DateTime.now().millisecondsSinceEpoch}&#39;;</pre><h3>3. Amount Validation</h3><p>Always validate amounts before processing:</p><pre>if (widget.amount &lt;= 0) {<br>  _showError(&#39;خطأ: مبلغ الدفع غير صالح&#39;);<br>  return;<br>}</pre><h3>Testing Strategy</h3><h3>1. Unit Tests for Payment Logic</h3><pre>void main() {<br>  group(&#39;PaymentService Tests&#39;, () {<br>    test(&#39;should return valid payment methods&#39;, () async {<br>      final paymentService = PaymentService();<br>      final methods = await paymentService.getPaymentMethods(100.0);<br>      expect(methods, isNotEmpty);<br>    });<br>    <br>    test(&#39;should filter payment methods by platform&#39;, () async {<br>      // Test platform-specific filtering<br>    });<br>  });<br>}</pre><h3>2. Integration Tests</h3><p>Test the complete payment flow in a controlled environment.</p><h3>3. Manual Testing Checklist</h3><ul><li>✅ Apple Pay works on iOS devices</li><li>✅ STC Pay redirects properly</li><li>✅ Card payments process correctly</li><li>✅ Error messages display in Arabic</li><li>✅ Loading states work properly</li><li>✅ Back navigation functions</li><li>✅ Firebase updates correctly</li></ul><h3>Common Issues and Solutions</h3><h3>Issue 1: Apple Pay Button Not Loading</h3><p><strong>Problem</strong>: Button appears but doesn’t respond to taps <strong>Solution</strong>: Ensure session is created before loading the button</p><pre>// Always create session first<br>final session = await _paymentService.initiateSession(...);<br>if (session?.sessionId != null) {<br>  await mfApplePayButton.load(session!, executePaymentRequest, ...);<br>}</pre><h3>Issue 2: Wrong Amount in Payment</h3><p><strong>Problem</strong>: Payment processes with incorrect amount <strong>Solution</strong>: Double-check all amount parameters</p><pre>// Ensure consistency across all amount fields<br>MFExecutePaymentRequest(invoiceValue: widget.amount) // ✅<br>final mfSupplier = MFSupplier(invoiceShare: widget.amount) // ✅</pre><h3>Issue 3: Session Timeout</h3><p><strong>Problem</strong>: Payment fails due to expired session <strong>Solution</strong>: Implement session refresh logic</p><pre>if (sessionError.contains(&#39;expired&#39;)) {<br>  // Recreate session and retry<br>  await _initiateCardSession();<br>}</pre><h3>Conclusion</h3><p>Building a comprehensive payment system with MyFatoorah taught me that <strong>the devil is truly in the details</strong>. From proper Apple Pay implementation to supplier payment splitting, every small component required careful attention.</p><p>The key takeaways from this project:</p><ol><li><strong>Security First</strong>: Always prioritize transaction security and data protection</li><li><strong>User Experience</strong>: Smooth UI/UX can make or break a payment flow</li><li><strong>Platform Considerations</strong>: iOS and Android have different payment ecosystems</li><li><strong>Error Handling</strong>: Comprehensive error handling is essential for user trust</li><li><strong>Testing</strong>: Thorough testing across all payment methods and scenarios</li><li><strong>Documentation</strong>: Proper logging and documentation saves hours of debugging</li></ol><p>The final result was a robust, secure, and user-friendly payment system that successfully handles thousands of transactions for the موعد app. The mixed Arabic-English approach resonated well with our target audience, providing both technical accuracy and cultural relevance.</p><p><strong>What’s your experience with payment gateway integration? Have you faced similar challenges with MyFatoorah or other payment providers?</strong></p><p><em>Follow me for more Flutter development insights and real-world coding experiences. Let’s build amazing apps together! 🚀</em></p><p>#Flutter #MyFatoorah #PaymentGateway #MobileDevelopment #iOS #Android #Arabic #TechArticleISO.SAUDIARABIA_SAR ); final response = await MFSDK.initiatePayment(request, MFLanguage.ARABIC);</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1daeb766a39" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Push Notifications in Flutter Web with Firebase]]></title>
            <link>https://medium.com/@anwarsafy15/implementing-push-notifications-in-flutter-web-with-firebase-85da1fa0fd9c?source=rss-0bea69ba7004------2</link>
            <guid isPermaLink="false">https://medium.com/p/85da1fa0fd9c</guid>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[fcm-push-notification]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[push-notification]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Anwar Safy]]></dc:creator>
            <pubDate>Wed, 12 Feb 2025 16:34:52 GMT</pubDate>
            <atom:updated>2025-02-12T16:34:52.297Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yuDzIfNkGGh6XSQrudqoHg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JtuN8cpFeGiFc7ejvgjACA.png" /></figure><p>Push notifications are a powerful way to engage users, even when they are not actively using your app. In this article, we’ll walk through how to implement push notifications in a <strong>Flutter Web</strong> application using <strong>Firebase Cloud Messaging (FCM)</strong>. We’ll cover everything from setting up Firebase to handling notifications in both foreground and background states.</p><h3>Prerequisites</h3><p>Before diving into the implementation, ensure you have the following:</p><ol><li><strong>Flutter SDK</strong> installed and configured.</li><li>A <strong>Firebase project</strong> set up in the <a href="https://console.firebase.google.com/">Firebase Console</a>.</li><li>Basic knowledge of Flutter and Firebase.</li></ol><h3>Step 1: Set Up Firebase for Flutter Web</h3><h3>1.1 Add Firebase to Your Flutter Project</h3><p>First, add the necessary Firebase dependencies to your pubspec.yaml file:</p><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>  firebase_core: latest_version<br>  firebase_messaging: latest_version<br>  flutter_local_notifications: latest_version<br>  fluttertoast: latest_version<br>  cloud_firestore: latest_version</pre><p>Run flutter pub get to install the dependencies.</p><h3>1.2 Configure Firebase for Web</h3><p>In your Firebase Console, register your web app and obtain the Firebase configuration. Add this configuration to your index.html file:</p><pre>&lt;script&gt;<br>  const firebaseConfig = {<br>    apiKey: &quot;YOUR_API_KEY&quot;,<br>    authDomain: &quot;YOUR_AUTH_DOMAIN&quot;,<br>    projectId: &quot;YOUR_PROJECT_ID&quot;,<br>    storageBucket: &quot;YOUR_STORAGE_BUCKET&quot;,<br>    messagingSenderId: &quot;YOUR_MESSAGING_SENDER_ID&quot;,<br>    appId: &quot;YOUR_APP_ID&quot;,<br>    measurementId: &quot;YOUR_MEASUREMENT_ID&quot;<br>  };<br>  firebase.initializeApp(firebaseConfig);<br>&lt;/script&gt;</pre><h3>Step 2: Initialize Firebase Messaging</h3><p>Create a PushNotifications class to handle Firebase Messaging initialization and notification handling. Here’s the code:</p><pre>import &#39;package:firebase_auth/firebase_auth.dart&#39;;<br>import &#39;package:firebase_messaging/firebase_messaging.dart&#39;;<br>import &#39;package:flutter/foundation.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_local_notifications/flutter_local_notifications.dart&#39;;<br>import &#39;package:cloud_firestore/cloud_firestore.dart&#39;;<br>import &#39;package:fluttertoast/fluttertoast.dart&#39;;<br><br>class PushNotifications {<br>  static final _firebaseMessaging = FirebaseMessaging.instance;<br>  static final FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin =<br>      FlutterLocalNotificationsPlugin();<br><br>  static Future init() async {<br>    try {<br>      // Request permission<br>      NotificationSettings settings = await _firebaseMessaging.requestPermission(<br>        alert: true,<br>        announcement: true,<br>        badge: true,<br>        carPlay: false,<br>        criticalAlert: false,<br>        provisional: false,<br>        sound: true,<br>      );<br><br>      debugPrint(&#39;User granted permission: ${settings.authorizationStatus}&#39;);<br><br>      if (!kIsWeb) {<br>        // Initialize local notifications for mobile<br>        const AndroidInitializationSettings initializationSettingsAndroid =<br>            AndroidInitializationSettings(&#39;@mipmap/ic_launcher&#39;);<br>        const InitializationSettings initializationSettings =<br>            InitializationSettings(android: initializationSettingsAndroid);<br>        await _flutterLocalNotificationsPlugin.initialize(<br>          initializationSettings,<br>          onDidReceiveNotificationResponse: (NotificationResponse response) {<br>            debugPrint(&#39;Notification clicked: ${response.payload}&#39;);<br>            // Handle notification click<br>          },<br>        );<br>      }<br><br>      // Initialize foreground handler<br>      FirebaseMessaging.onMessage.listen((RemoteMessage message) {<br>        debugPrint(&#39;Got a message whilst in the foreground!&#39;);<br>        debugPrint(&#39;Message data: ${message.data}&#39;);<br><br>        if (message.notification != null) {<br>          debugPrint(&#39;Message notification details: &#39;);<br>          debugPrint(&#39;Title: ${message.notification?.title}&#39;);<br>          debugPrint(&#39;Body: ${message.notification?.body}&#39;);<br>          debugPrint(&#39;Data: ${message.data}&#39;);<br><br>          try {<br>            if (kIsWeb) {<br>              showWebNotification(<br>                title: message.notification?.title ?? &#39;New Notification&#39;,<br>                body: message.notification?.body ?? &#39;You have a new notification&#39;,<br>                data: message.data,<br>              );<br>            } else {<br>              showSimpleNotification(<br>                title: message.notification?.title ?? &#39;New Notification&#39;,<br>                body: message.notification?.body ?? &#39;You have a new notification&#39;,<br>                payload: message.data.toString(),<br>              );<br>            }<br>          } catch (e) {<br>            debugPrint(&#39;Error showing notification: $e&#39;);<br>          }<br>        }<br>      });<br><br>      // Get initial message if app was launched from notification<br>      RemoteMessage? initialMessage = await _firebaseMessaging.getInitialMessage();<br>      if (initialMessage != null) {<br>        _handleMessage(initialMessage);<br>      }<br><br>      // Handle background/terminated state messages<br>      FirebaseMessaging.onMessageOpenedApp.listen(_handleMessage);<br>      FirebaseMessaging.onBackgroundMessage(_firebaseBackgroundMessageHandler);<br><br>      // Get FCM token<br>      await getFCMToken();<br><br>    } catch (e) {<br>      debugPrint(&#39;Error initializing push notifications: $e&#39;);<br>    }<br>  }<br><br>  // Other methods like _firebaseBackgroundMessageHandler, _handleMessage, getFCMToken, etc.<br>}</pre><h3>Step 3: Handle Notifications on Web</h3><h3>3.1 Service Worker for Background Notifications</h3><p>Create a firebase-messaging-sw.js file in your web folder to handle background messages:</p><pre>importScripts(&quot;https://www.gstatic.com/firebasejs/9.19.1/firebase-app-compat.js&quot;);<br>importScripts(&quot;https://www.gstatic.com/firebasejs/9.19.1/firebase-messaging-compat.js&quot;);<br><br>firebase.initializeApp({<br>  apiKey: &quot;YOUR_API_KEY&quot;,<br>  appId: &quot;YOUR_APP_ID&quot;,<br>  messagingSenderId: &quot;YOUR_MESSAGING_SENDER_ID&quot;,<br>  projectId: &quot;YOUR_PROJECT_ID&quot;,<br>  authDomain: &quot;YOUR_AUTH_DOMAIN&quot;,<br>  storageBucket: &quot;YOUR_STORAGE_BUCKET&quot;,<br>  measurementId: &quot;YOUR_MEASUREMENT_ID&quot;,<br>});<br><br>const messaging = firebase.messaging();<br><br>// Handle background messages<br>messaging.onBackgroundMessage(async (payload) =&gt; {<br>  console.log(&#39;Received background message:&#39;, payload);<br><br>  const notificationTitle = payload.notification.title;<br>  const notificationOptions = {<br>    body: payload.notification.body,<br>    icon: &#39;/icons/Icon-192.png&#39;,<br>    badge: &#39;/icons/Icon-192.png&#39;,<br>    data: payload.data,<br>    click_action: payload.notification.click_action,<br>  };<br><br>  self.registration.showNotification(notificationTitle, notificationOptions);<br>});</pre><h3>3.2 Register the Service Worker</h3><p>In your index.html, register the service worker:</p><pre>&lt;script&gt;<br>  if (&#39;serviceWorker&#39; in navigator) {<br>    window.addEventListener(&#39;load&#39;, function() {<br>      navigator.serviceWorker.register(&#39;/firebase-messaging-sw.js&#39;)<br>        .then(function(registration) {<br>          console.log(&#39;Service Worker registered with scope:&#39;, registration.scope);<br>        })<br>        .catch(function(err) {<br>          console.error(&#39;Service Worker registration failed:&#39;, err);<br>        });<br>    });<br>  }<br>&lt;/script&gt;</pre><h3>Step 4: Test Your Implementation</h3><ol><li>Run your Flutter Web app using flutter run -d chrome.</li><li>Send a test notification from the Firebase Console or using a backend service.</li><li>Verify that notifications appear in both foreground and background states.</li></ol><h3>Conclusion</h3><p>By following these steps, you can successfully implement push notifications in your Flutter Web app using Firebase. This setup ensures that your users stay engaged with timely updates, even when they’re not actively using your app.</p><p>Feel free to explore additional features like topic-based messaging or custom notification handling to further enhance your app’s capabilitie</p><h3>Resources</h3><ul><li><a href="https://firebase.google.com/docs/cloud-messaging">Firebase Cloud Messaging Documentation</a></li><li><a href="https://pub.dev/packages/firebase_messaging">Flutter Firebase Messaging Package</a></li><li><a href="https://pub.dev/packages/flutter_local_notifications">Flutter Local Notifications Package</a></li></ul><p>Let me know if you need further assistance or additional sections for your article! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85da1fa0fd9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Export Firestore Collections to Excel in Flutter — A Complete Guide”]]></title>
            <link>https://medium.com/@anwarsafy15/export-firestore-collections-to-excel-in-flutter-a-complete-guide-a385722c5f33?source=rss-0bea69ba7004------2</link>
            <guid isPermaLink="false">https://medium.com/p/a385722c5f33</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[excel]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[firebase]]></category>
            <dc:creator><![CDATA[Anwar Safy]]></dc:creator>
            <pubDate>Thu, 12 Dec 2024 22:06:21 GMT</pubDate>
            <atom:updated>2024-12-12T22:06:21.037Z</atom:updated>
            <content:encoded><![CDATA[<h3>“Export Firestore Collections to Excel in Flutter — A Complete Guide”</h3><h3>1. Introduction</h3><blockquote><em>Exporting Firestore collections to Excel can be a daunting task for Flutter developers. Manually mapping data, formatting it, and ensuring compatibility across platforms takes time and effort. That’s why I created </em><em>firebase_excel_export, a Flutter package that simplifies the process of exporting Firestore data to Excel with customizable headers and dynamic data mapping.</em></blockquote><h4>2. Why Use firebase_excel_export?</h4><ul><li>Easy to set up.</li><li>Supports custom headers and data mapping.</li><li>Web support for downloading files.</li><li>Saves time and reduces errors.</li></ul><h3>3. Installation</h3><p>Include a code snippet for pubspec.yaml:</p><pre>dependencies:<br>  firebase_excel_export: ^0.0.7</pre><ul><li>run dart pub get.</li></ul><h4>4. Features and Capabilities</h4><ol><li><strong>Custom Headers</strong>: Define your Excel file headers.</li><li><strong>Dynamic Data Mapping</strong>: Map Firestore fields to Excel rows dynamically.</li><li><strong>Web Compatibility</strong>: Export files directly in the browser.</li><li><strong>Firestore Query Support</strong>: Filter data before exporting.</li></ol><h3>5. How to Use firebase_excel_export</h3><p>Basic Example :</p><pre>import &#39;package:firebase_excel_export/firebase_excel_export.dart&#39;;<br><br>Future&lt;void&gt; exportUsers() async {<br>  await FirebaseExcelExporter.exportToExcel(<br>    collectionName: &#39;users&#39;,<br>    headers: [&#39;Name&#39;, &#39;Email&#39;, &#39;Status&#39;],<br>    mapper: (data) =&gt; [data[&#39;name&#39;], data[&#39;email&#39;], data[&#39;status&#39;]],<br>    fileName: &#39;users_export.xlsx&#39;,<br>  );<br>}</pre><p>Filtered Export Example :</p><pre>Future&lt;void&gt; exportActiveUsers() async {<br>  await FirebaseExcelExporter.exportToExcel(<br>    collectionName: &#39;users&#39;,<br>    headers: [&#39;Name&#39;, &#39;Email&#39;, &#39;Status&#39;],<br>    mapper: (data) =&gt; [data[&#39;name&#39;], data[&#39;email&#39;], data[&#39;status&#39;]],<br>    queryBuilder: (query) =&gt; query.where(&#39;status&#39;, isEqualTo: &#39;active&#39;),<br>    fileName: &#39;active_users.xlsx&#39;,<br>  );<br>}</pre><h4>6. Demo and Example Project</h4><p>Example:</p><blockquote><em>You can find a working demo project </em><a href="https://github.com/anwarsafy/firebase_excel_export"><em>here</em></a></blockquote><h4>7. Common Use Cases</h4><ul><li>Exporting data lists for analysis.</li><li>Generating reports from firestore data.</li><li>Downloading filtered data sets for specific requirements.</li></ul><h4>8. Conclusion :</h4><blockquote><em>firebase_excel_export is designed to make your life easier as a Flutter developer. Whether you&#39;re exporting user data, generating reports, or building web apps, this package handles it all seamlessly. Try it today and streamline your Firestore-to-Excel workflow!</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a385722c5f33" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving “Failed to Load Network Image” in Firebase Storage for Flutter Web: A Guide to Configuring…]]></title>
            <link>https://blog.stackademic.com/title-solving-failed-to-load-network-image-in-firebase-storage-for-flutter-web-a-guide-to-46ec41721be8?source=rss-0bea69ba7004------2</link>
            <guid isPermaLink="false">https://medium.com/p/46ec41721be8</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Anwar Safy]]></dc:creator>
            <pubDate>Mon, 04 Nov 2024 20:47:59 GMT</pubDate>
            <atom:updated>2024-11-12T01:07:29.447Z</atom:updated>
            <content:encoded><![CDATA[<h3>Solving “Failed to Load Network Image” in Firebase Storage for Flutter Web: A Guide to Configuring CORS</h3><p>If you’ve tried displaying images from Firebase Storage on a Flutter web app, you might have encountered a network error:</p><pre>Failed to load network image.<br>Image URL: https://firebasestorage.googleapis.com/v0/b/dalel-975d6.appspot.com/o/<br>Trying to load an image from another domain? Find answers at:<br>https://flutter.dev/docs/development/platform-integration/web-images</pre><pre>Failed to load network image.</pre><p>This issue is usually due to Cross-Origin Resource Sharing (CORS) restrictions, which prevent resources from one domain (in this case, Firebase Storage) from being accessed on another (your web app). To fix this, you need to configure CORS settings for your Firebase Storage bucket.</p><p>In this article, I’ll walk you through the process to set up CORS in Google Cloud Platform (GCP) so your Firebase images load smoothly in Flutter web apps.</p><h3>Step 1: Set Up Your Firebase Project</h3><p>Ensure you have a Firebase project set up with storage enabled. If you haven’t set up Firebase Storage, you can refer to the official Firebase documentation to get started.</p><h3>Step 2: Configure CORS for Firebase Storage</h3><p>To allow Firebase Storage to serve images to your web app, you need to set up CORS (Cross-Origin Resource Sharing) rules. Here’s how:</p><ol><li><strong>Go to the Google Cloud Console:</strong></li></ol><ul><li>Open <a href="https://console.cloud.google.com/">Google Cloud Console</a>.</li><li>Select your Firebase project.</li></ul><p>2. Open a Cloud Terminal Session:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F4UMKYDtpLAin8yKdrkw0A.png" /></figure><p>3.<strong>Create a CORS Configuration File:</strong></p><ul><li>In the terminal, create a new JSON file (e.g., cors.json) with the following content:</li></ul><pre>[<br>  {<br>    &quot;origin&quot;: [&quot;*&quot;],<br>    &quot;method&quot;: [&quot;GET&quot;],<br>    &quot;maxAgeSeconds&quot;: 3600<br>  }<br>]</pre><p>4. Apply the CORS Settings:</p><pre>gsutil cors set cors.json gs://your-bucket-name</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XF9L6Zf_hTKxi-RMiFrYng.png" /></figure><ul><li>Replace your-bucket-name with the name of your Firebase Storage bucket.</li><li>This command will update the bucket’s CORS settings, allowing external requests (including your Flutter web app) to access the images.</li></ul><h3>Step 3: Test the Configuration</h3><p>After applying the CORS settings, reload your Flutter web app and check if the images load without issues. This should resolve the “Failed to load network image” error.</p><p><strong>Conclusion:</strong></p><p>Configuring CORS for Firebase Storage can initially seem daunting, but following these steps will allow your Flutter web app to access images from Firebase Storage seamlessly. Once you’ve completed this setup, you’ll no longer encounter the frustrating “Failed to load network image” error, ensuring a smoother user experience.</p><p>By making these adjustments, you can confidently use Firebase Storage as a reliable resource for your Flutter web projects. Happy coding🧑‍💻🤯</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46ec41721be8" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/title-solving-failed-to-load-network-image-in-firebase-storage-for-flutter-web-a-guide-to-46ec41721be8">Solving “Failed to Load Network Image” in Firebase Storage for Flutter Web: A Guide to Configuring…</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Home Screen Widgets with Flutter Using HomeWidget 0.7.0]]></title>
            <link>https://medium.com/@anwarsafy15/creating-home-screen-widgets-with-flutter-using-homewidget-0-7-0-b79dcbcb298b?source=rss-0bea69ba7004------2</link>
            <guid isPermaLink="false">https://medium.com/p/b79dcbcb298b</guid>
            <category><![CDATA[home-screen-widget]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[widget]]></category>
            <dc:creator><![CDATA[Anwar Safy]]></dc:creator>
            <pubDate>Mon, 28 Oct 2024 21:13:26 GMT</pubDate>
            <atom:updated>2024-10-28T21:16:17.836Z</atom:updated>
            <content:encoded><![CDATA[<p>Developing Home Screen widgets can elevate your mobile app’s functionality, allowing users to interact with your content right from their home screen. With the home_widget package, Flutter developers can efficiently send data and updates to these widgets on <strong>Android</strong> and <strong>iOS</strong> platforms. In this article, we’ll explore how to integrate HomeWidget into your Flutter project, covering essential setup steps and code examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/190/1*zL0Alp5Em77bChpvLjVuIQ.png" /></figure><h3>Why Use HomeWidget?</h3><p>While Flutter offers a powerful cross-platform framework, <strong>Home Widgets still need to be written with native code</strong>. HomeWidget simplifies the interaction between Flutter and native widgets by providing a <strong>unified interface</strong> to send and retrieve data, manage widget updates, and even initiate background tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*CmY0p73Q3b8nzGO9_sbZFw.png" /></figure><h3>Features of HomeWidget</h3><ol><li><strong>Update Home Screen Widgets from Flutter</strong><br>Send data directly from Flutter to native widgets for both Android and iOS.</li><li><strong>Interactive Widgets</strong><br>Support for widgets that trigger <strong>Dart code</strong> on interaction.</li><li><strong>Background Updates</strong><br>Use background tasks with the WorkManager plugin to refresh widget content periodically.</li><li><strong>Rendering Flutter Widgets as Images</strong><br>Generate PNGs of Flutter widgets to display on the home screen without rewriting UI in native code.</li></ol><h3>Getting Started with HomeWidget 0.7.0</h3><h4>Installation</h4><ol><li>Add the following dependency in your pubspec.yaml:</li></ol><pre>dependencies:<br>  home_widget: ^0.7.0<br>  workmanager: ^2.1.0</pre><p>2. Run flutter pub get to install the dependencies.</p><h3>Setting Up Your Flutter App</h3><p>Before creating the native widgets, you need to set up <strong>background communication</strong> and <strong>interactivity callbacks</strong>.</p><h4>Configure the Background Callback</h4><p>Add the following code to handle background updates using WorkManager:</p><pre>@pragma(&#39;vm:entry-point&#39;)<br>void callbackDispatcher() async {<br>  Workmanager().executeTask((taskName, inputData) async {<br>    await HomeWidget.saveWidgetData(&#39;title&#39;, &#39;Updated from Background&#39;);<br>    await HomeWidget.updateWidget(name: &#39;HomeWidgetExampleProvider&#39;);<br>    return true;  // Task completed successfully<br>  });<br>}</pre><p>Initialize this in your main() method:</p><pre>void main() {<br>  WidgetsFlutterBinding.ensureInitialized();<br>  Workmanager().initialize(callbackDispatcher, isInDebugMode: true);<br>  runApp(MyApp());<br>}</pre><h3>Sending Data to Home Widgets</h3><p>You can send data from your Flutter app to the Home Screen widget with the following methods:</p><pre>Future&lt;void&gt; _sendData() async {<br>  try {<br>    await HomeWidget.saveWidgetData(&#39;title&#39;, &#39;Hello from Flutter!&#39;);<br>    await HomeWidget.saveWidgetData(&#39;message&#39;, &#39;This is a sample message.&#39;);<br>    await HomeWidget.updateWidget(name: &#39;HomeWidgetExampleProvider&#39;);<br>  } catch (e) {<br>    debugPrint(&#39;Error Sending Data: $e&#39;);<br>  }<br>}</pre><p>Use _sendData() whenever you want to push updates to the widget.</p><h3>Creating Native Widgets</h3><h4>Android Setup</h4><ol><li><strong>Add Dependencies</strong>:<br>Add Jetpack Glance to your Android build.gradle file:</li></ol><pre>implementation &#39;androidx.glance:glance-appwidget:1.0.0&#39;</pre><p><strong>2. Create Widget Configuration</strong>:<br>Add a new XML file in res/xml/home_widget_config.xml:</p><pre>&lt;appwidget-provider xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    android:minWidth=&quot;40dp&quot;<br>    android:minHeight=&quot;40dp&quot;<br>    android:updatePeriodMillis=&quot;60000&quot;<br>    android:initialLayout=&quot;@layout/widget_layout&quot; /&gt;</pre><p><strong>3. Define the Widget Receiver</strong>:<br>In your AndroidManifest.xml:</p><pre>&lt;receiver android:name=&quot;.HomeWidgetReceiver&quot; android:exported=&quot;true&quot;&gt;<br>  &lt;intent-filter&gt;<br>    &lt;action android:name=&quot;android.appwidget.action.APPWIDGET_UPDATE&quot; /&gt;<br>  &lt;/intent-filter&gt;<br>  &lt;meta-data android:name=&quot;android.appwidget.provider&quot; android:resource=&quot;@xml/home_widget_config&quot; /&gt;<br>&lt;/receiver&gt;</pre><h4>IOS Setup</h4><ol><li><strong>Add Widget Extension in Xcode</strong>: Go to <strong>File &gt; New &gt; Target &gt; Widget Extension</strong>.</li></ol><p><strong>2. Configure App Groups</strong>: Add a group ID in <strong>Signing &amp; Capabilities</strong> for both your main app and the widget extension.</p><p><strong>3. Sync Data with Flutter</strong>: Call HomeWidget.setAppGroupId(&#39;YOUR_GROUP_ID&#39;); in your Flutter app.</p><h3>Rendering Flutter Widgets as Images</h3><p>In some cases, you may want to render your <strong>Flutter UI as an image</strong> and display it on the widget. Here’s how to achieve that:</p><pre> var path = await HomeWidget.renderFlutterWidget(<br>  const Icon(Icons.flutter_dash, size: 100),<br>  logicalSize: const Size(100, 100),<br>  key: &#39;dashIcon&#39;,<br>);</pre><p>Use the generated path in your native widget to display the Flutter-rendered image.</p><h3>Handling Widget Interactions</h3><p>You can trigger Dart code when users interact with your widget. Here’s an example of registering an <strong>interactive callback</strong>:</p><pre>@pragma(&#39;vm:entry-point&#39;)<br>Future&lt;void&gt; interactiveCallback(Uri? data) async {<br>  if (data?.host == &#39;titleclicked&#39;) {<br>    await HomeWidget.saveWidgetData(&#39;title&#39;, &#39;You clicked the title!&#39;);<br>    await HomeWidget.updateWidget(name: &#39;HomeWidgetExampleProvider&#39;);<br>  }<br>}<br><br>@override<br>void initState() {<br>  super.initState();<br>  HomeWidget.registerInteractivityCallback(interactiveCallback);<br>}</pre><p>This allows you to react to user interactions, such as button clicks, from the widget interface.</p><h3>Periodic Background Updates</h3><p>You can set up background updates for your widget using WorkManager:</p><pre>void _startBackgroundUpdate() {<br>  Workmanager().registerPeriodicTask(<br>    &#39;1&#39;,<br>    &#39;widgetBackgroundUpdate&#39;,<br>    frequency: const Duration(minutes: 15),<br>  );<br>}<br><br>void _stopBackgroundUpdate() {<br>  Workmanager().cancelByUniqueName(&#39;1&#39;);<br>}</pre><p>This ensures that your widget content stays fresh by updating periodically in the background.</p><h3>Conclusion</h3><p>The home_widget plugin bridges the gap between Flutter and native widgets, allowing for seamless data updates and interactive experiences. Although you still need to write native widget code, HomeWidget makes it easy to <strong>send data, handle background updates, and render Flutter widgets as images</strong>.</p><p>With the ability to support both <strong>Android</strong> and <strong>iOS</strong>, you can enhance your app’s user experience and give users quicker access to essential features through the Home Screen.</p><p>Explore the full <strong>HomeWidget documentation</strong> on <a href="https://pub.dev/">Pub.dev</a> for more in-depth examples and setup guides</p><p><strong>Useful Links:</strong></p><ul><li><a href="https://pub.dev/packages/home_widget">https://pub.dev/packages/home_widget</a></li><li><a href="https://docs.page/abausg/home_widget">https://docs.page/abausg/home_widget</a></li><li><a href="https://www.youtube.com/watch?v=L9cP9OTUstA">https://www.youtube.com/watch?v=L9cP9OTUstA</a></li></ul><p>Happy coding! 🚀🧑‍💻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b79dcbcb298b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Firebase Pagination: Effortlessly Paginate Firestore and Realtime Database with Live…]]></title>
            <link>https://medium.com/@anwarsafy15/flutter-firebase-pagination-effortlessly-paginate-firestore-and-realtime-database-with-live-e4cfd18183a9?source=rss-0bea69ba7004------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4cfd18183a9</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[pagination]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Anwar Safy]]></dc:creator>
            <pubDate>Sun, 06 Oct 2024 18:50:49 GMT</pubDate>
            <atom:updated>2024-10-06T19:33:40.989Z</atom:updated>
            <content:encoded><![CDATA[<h3>Flutter Firebase Pagination: Effortlessly Paginate Firestore and Realtime Database with Live Updates</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oaXGOc20zmcwGCLifQiIuA.png" /></figure><p>When working with Firebase, handling large datasets can be a real headache. Whether you’re pulling records from Firestore or the Realtime Database, you’ve probably noticed that data loads can quickly get out of hand, especially as your collection grows. That’s where firebase_pagination comes to the rescue!</p><p>In this article, we’ll delve into what makes firebase_pagination stand out and how you can leverage it to build sophisticated applications with efficient data loading.</p><h3>Why Should You Care About Pagination?</h3><p>Imagine you have a list of thousands of items. Loading them all at once will slow your app down, drain your users’ data, and make the UI feel sluggish. With pagination, you can load data in smaller chunks — giving your app a smooth and efficient experience for users, while still having access to all your data.</p><p>In this article, I’m going to show you how to use firebase_pagination, a Flutter package that makes it incredibly easy to paginate Firebase data. Whether you’re working with Firestore or the Realtime Database, this package handles it all, and with real-time updates too!</p><h3>Key Features of firebase_pagination</h3><ol><li><strong>FirestorePagination</strong> and <strong>RealtimeDBPagination</strong> widgets to simplify paginating your Firebase data.</li><li>Automatically updates when new data is added using the isLive property.</li><li>Get real-time changes to already loaded data.</li><li>Support for both ascending and descending pagination for RealtimeDB.</li><li>Easily customizable item layouts using itemBuilder and separatorBuilder.</li></ol><h3>Getting Started with firebase_pagination</h3><p>before we dive into the usage examples, let’s set up the package in your Flutter project.</p><ol><li><strong>Add the Dependency:</strong></li></ol><p>Add the following line to your pubspec.yaml file under dependencies:</p><pre>dependencies:<br>  firebase_pagination: ^4.0.1</pre><p>2. <strong>Import the Package:</strong></p><p>After adding the dependency, import the package into your Dart file:</p><pre>import &#39;package:firebase_pagination/firebase_pagination.dart&#39;;</pre><p><strong>3.Configure Firebase:</strong><br>Ensure that your Flutter project is correctly set up with Firebase. Configure Firestore or Realtime Database based on your requirements, as firebase_pagination works seamlessly with both.</p><h3>Using firebase_pagination for Firestore</h3><h3>Simplest Firestore Pagination</h3><p>To implement basic Firestore pagination, use the FirestorePagination widget:</p><pre>FirestorePagination(<br>  query: FirebaseFirestore.instance.collection(&#39;scores&#39;).orderBy(&#39;score&#39;),<br>  itemBuilder: (context, docs, index) {<br>    final data = docs[index].data() as Map&lt;String, dynamic&gt;;<br><br>    // Do something cool with the data<br>    return ListTile(<br>      title: Text(data[&#39;name&#39;]),<br>      subtitle: Text(&#39;Score: ${data[&#39;score&#39;]}&#39;),<br>    );<br>  },<br>),</pre><h3>Firestore Pagination with Live Updates</h3><p>For applications that require live updates — such as chat or real-time feeds — firebase_pagination provides the isLive property:</p><pre>FirestorePagination(<br>  query: FirebaseFirestore.instance.collection(&#39;chats&#39;).orderBy(&#39;createdAt&#39;, descending: true),<br>  limit: 69, // Number of items to fetch initially<br>  isLive: true, // Enable live updates<br>  reverse: true, // Display the latest messages at the bottom<br>  itemBuilder: (context, documentSnapshot, index) {<br>    final data = documentSnapshot.data() as Map&lt;String, dynamic&gt;;<br>    return ListTile(<br>      title: Text(data[&#39;senderName&#39;]),<br>      subtitle: Text(data[&#39;message&#39;]),<br>    );<br>  },<br>  separatorBuilder: (context, index) =&gt; Divider(height: 5),<br>),</pre><h3>Custom ListView Pagination with Loader</h3><p>If you need a custom loader for displaying more items as the user scrolls, firebase_pagination offers the bottomLoader property:</p><pre>FirestorePagination(<br>  query: FirebaseFirestore.instance.collection(&#39;scores&#39;).orderBy(&#39;score&#39;, descending: true),<br>  limit: 420,<br>  bottomLoader: Center(<br>    child: CircularProgressIndicator(<br>      strokeWidth: 3,<br>      color: Colors.blue,<br>    ),<br>  ),<br>  itemBuilder: (context, documentSnapshot, index) {<br>    final data = documentSnapshot.data() as Map&lt;String, dynamic&gt;?;<br>    if (data == null) return Container();<br><br>    return ListTile(<br>      title: Text(data[&#39;name&#39;]),<br>      subtitle: Text(&#39;Score: ${data[&#39;score&#39;]}&#39;),<br>    );<br>  },<br>),</pre><h3>Using firebase_pagination for Realtime Database</h3><p>firebase_pagination is equally effective for Firebase Realtime Database. Use the RealtimeDBPagination widget to paginate database nodes:</p><pre>RealtimeDBPagination(<br>  query: FirebaseDatabase.instance.ref().child(&#39;scores&#39;).orderByChild(&#39;score&#39;),<br>  orderBy: &#39;score&#39;,<br>  itemBuilder: (context, dataNodes, index) {<br>    final data = dataNodes[index].value as Map&lt;String, dynamic&gt;;<br>    return ListTile(<br>      title: Text(data[&#39;name&#39;]),<br>      subtitle: Text(&#39;Score: ${data[&#39;score&#39;]}&#39;),<br>    );<br>  },<br>),</pre><h3>How Does it Work?</h3><p>The package uses a listener to keep track of your data and listens for changes automatically. Every time the user scrolls to the end of the list, the package increases the limit of items it loads, and you get fresh data without any extra work!</p><p>The isLive property is a game-changer! If you set isLive: true, firebase_pagination will listen for new items added to the collection or node, so your app stays up-to-date in real-time.</p><h3>Efficiency and Performance</h3><p>The great thing about firebase_pagination is that it’s built with efficiency in mind. It only uses two listeners at a time, keeping your app’s resource consumption low. Also, it cleverly reuses the existing listeners to minimize unnecessary reads from the database.</p><h3>Customizing the Pagination</h3><p>Want more control over how your items appear? firebase_pagination has got you covered. Here are some options you can play around with:</p><ul><li>separatorBuilder: Add separators between your list items.</li><li>limit: Set the number of items to load at once.</li><li>viewType: Switch between a list view, grid view, or custom view.</li><li>initialLoader &amp; bottomLoader: Customize the loading indicators.</li></ul><h3>Final Thoughts</h3><p>If you’re looking to add smooth, effortless pagination to your Flutter apps, firebase_pagination is definitely worth trying. It takes the hassle out of managing large datasets and keeps your app performant with minimal effort.</p><p>Let me know in the comments if you have any questions or if there are other topics you’d like me to cover.</p><p><strong>Useful Links:</strong></p><ul><li><a href="https://pub.dev/packages/firebase_pagination">https://pub.dev/packages/firebase_pagination</a></li><li><a href="https://github.com/outdatedguy/firebase_pagination">GitHub Repository</a></li></ul><p>Happy coding! 🚀🧑‍💻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4cfd18183a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>