Code Snippets

Deep Linking Code Snippets

Copy-paste ready code for Flutter and React Native. Implement email verification, referrals, push notifications, and attribution tracking in minutes.

Authentication

Email Verification Deep Link Handler

Handle email verification links with token parsing

import 'package:redirectly_sdk/redirectly_sdk.dart';
import 'package:uni_links/uni_links.dart';

class EmailVerificationHandler {
  Future<void> handleEmailVerification() async {
    try {
      // Listen to deep links
      deepLinkStream.listen((String? link) async {
        if (link != null && link.contains('/verify')) {
          final uri = Uri.parse(link);
          final token = uri.queryParameters['token'];

          if (token != null) {
            // Send verification request
            final response = await verifyEmail(token);

            if (response.success) {
              // Navigate to success screen
              navigateTo('/email-verified');
            }
          }
        }
      });
    } catch (e) {
      print('Email verification error: $e');
    }
  }

  Future<VerificationResponse> verifyEmail(String token) async {
    // Your verification logic
    return VerificationResponse(success: true);
  }
}

class VerificationResponse {
  final bool success;
  VerificationResponse({required this.success});
}

Marketing

Referral Link Generator & Handler

Create and handle referral links with reward tracking

import 'package:redirectly_sdk/redirectly_sdk.dart';
import 'package:share_plus/share_plus.dart';

class ReferralManager {
  final redirectly = RedirectlySDK();

  // Generate referral link
  Future<String> generateReferralLink(String userId) async {
    final link = await redirectly.createDeepLink(
      route: '/referral',
      data: {
        'referrer_id': userId,
        'timestamp': DateTime.now().toIso8601String(),
      },
    );
    return link;
  }

  // Share referral link
  Future<void> shareReferralLink(String userId) async {
    final link = await generateReferralLink(userId);
    await Share.share(
      'Join me on the app! $link',
      subject: 'Join my referral program',
    );
  }

  // Handle incoming referral
  Future<void> handleReferral(String? referrerId) async {
    if (referrerId != null) {
      // Save referrer info
      await saveReferrerInfo(referrerId);

      // Track referral event
      await redirectly.trackEvent(
        name: 'referral_accepted',
        data: {'referrer_id': referrerId},
      );

      // Award bonus
      await awardReferralBonus();
    }
  }

  Future<void> saveReferrerInfo(String referrerId) async {
    // Save to local storage or API
  }

  Future<void> awardReferralBonus() async {
    // Award points, credits, etc.
  }
}

Analytics

Campaign Attribution Reader

Read and track attribution data from deep links

import 'package:redirectly_sdk/redirectly_sdk.dart';

class AttributionReader {
  final redirectly = RedirectlySDK();

  Future<AttributionData> getAttributionData() async {
    try {
      // Get installation attribution
      final attribution = await redirectly.getAttribution();

      return AttributionData(
        source: attribution['utm_source'] ?? 'organic',
        medium: attribution['utm_medium'] ?? 'direct',
        campaign: attribution['utm_campaign'] ?? 'none',
        content: attribution['utm_content'],
        term: attribution['utm_term'],
        clickId: attribution['click_id'],
        customData: attribution['custom_data'] ?? {},
      );
    } catch (e) {
      print('Attribution error: $e');
      rethrow;
    }
  }

  Future<void> trackAttributionEvent(
    String eventName,
    AttributionData attribution,
  ) async {
    await redirectly.trackEvent(
      name: eventName,
      data: {
        'utm_source': attribution.source,
        'utm_medium': attribution.medium,
        'utm_campaign': attribution.campaign,
        'utm_content': attribution.content,
        'utm_term': attribution.term,
      },
    );
  }

  Future<void> analyzeUserJourney(AttributionData attribution) async {
    print('User came from: ${attribution.source}');
    print('Campaign: ${attribution.campaign}');

    // Store for analytics
    await _storeAttributionLocally(attribution);
  }

  Future<void> _storeAttributionLocally(AttributionData attribution) async {
    // Save to local database or preferences
  }
}

class AttributionData {
  final String source;
  final String medium;
  final String campaign;
  final String? content;
  final String? term;
  final String? clickId;
  final Map<String, dynamic> customData;

  AttributionData({
    required this.source,
    required this.medium,
    required this.campaign,
    this.content,
    this.term,
    this.clickId,
    required this.customData,
  });
}

Engagement

Push Notification Deep Link Handler

Handle deep links from push notifications

import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:redirectly_sdk/redirectly_sdk.dart';

class PushNotificationHandler {
  final messaging = FirebaseMessaging.instance;
  final redirectly = RedirectlySDK();

  Future<void> initializePushNotifications() async {
    // Request permissions
    await messaging.requestPermission();

    // Handle notification when app is terminated
    final initialMessage = await messaging.getInitialMessage();
    if (initialMessage != null) {
      _handleNotification(initialMessage);
    }

    // Handle notification when app is in foreground
    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      _handleNotification(message);
    });

    // Handle notification tap when app is in background
    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
      _handleNotification(message);
    });
  }

  void _handleNotification(RemoteMessage message) {
    final deepLink = message.data['deep_link'];
    final screenName = message.data['screen'];

    if (deepLink != null) {
      // Navigate via deep link
      navigateTo(deepLink);
    } else if (screenName != null) {
      // Navigate to specific screen
      navigateToScreen(screenName, message.data);
    }
  }

  void navigateTo(String deepLink) {
    // Your navigation logic
    print('Navigating to: $deepLink');
  }

  void navigateToScreen(String screen, Map<String, dynamic> data) {
    // Navigate with parameters
    print('Navigating to screen: $screen');
  }
}

Configuration

go_router Deep Link Configuration

Set up go_router with Redirectly deep links

import 'package:go_router/go_router.dart';
import 'package:redirectly_sdk/redirectly_sdk.dart';

final redirectly = RedirectlySDK();

final appRouter = GoRouter(
  // Handle initial deep link
  initialLocation: '/',

  // Route redirect logic
  redirect: (context, state) async {
    // Handle Redirectly deep links
    final deepLink = state.uri.toString();
    if (deepLink.contains('redirectly.app')) {
      // Let Redirectly SDK handle the routing
      return await redirectly.handleDeepLink(deepLink);
    }
    return null;
  },

  routes: [
    GoRoute(
      path: '/',
      builder: (context, state) => const HomeScreen(),
    ),
    GoRoute(
      path: '/product/:id',
      builder: (context, state) {
        final productId = state.pathParameters['id'];
        return ProductDetailScreen(productId: productId ?? '');
      },
    ),
    GoRoute(
      path: '/referral',
      builder: (context, state) {
        final referrerId = state.uri.queryParameters['referrer_id'];
        return ReferralScreen(referrerId: referrerId);
      },
    ),
    GoRoute(
      path: '/verify',
      builder: (context, state) {
        final token = state.uri.queryParameters['token'];
        return EmailVerificationScreen(token: token ?? '');
      },
    ),
    GoRoute(
      path: '/promo/:code',
      builder: (context, state) {
        final promoCode = state.pathParameters['code'];
        return PromoScreen(code: promoCode ?? '');
      },
    ),
  ],
);

// Handle incoming links
Future<void> setupDeepLinkHandling() async {
  redirectly.onDeepLinkReceived = (deepLink, data) {
    // Custom handling for specific routes
    if (deepLink.contains('/product/')) {
      // Analytics tracking
      redirectly.trackEvent(
        name: 'product_opened',
        data: data,
      );
    }
  };
}

Basic SDK Initialization

Initialize Redirectly SDK in your Flutter app

import 'package:flutter/material.dart';
import 'package:redirectly_sdk/redirectly_sdk.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // Initialize Redirectly SDK
  await RedirectlySDK.initialize(
    apiKey: 'your_api_key_here',
    subdomain: 'your_subdomain',
    // Optional: Enable debug logging
    enableDebugLogging: true,
  );

  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late RedirectlySDK _redirectly;

  @override
  void initState() {
    super.initState();
    _initializeRedirectly();
  }

  Future<void> _initializeRedirectly() async {
    _redirectly = RedirectlySDK.instance;

    // Listen for deep links
    _redirectly.deepLinkStream.listen((deepLink) {
      _handleDeepLink(deepLink);
    });

    // Get initial deep link (if app was opened via link)
    final initialLink = await _redirectly.getInitialDeepLink();
    if (initialLink != null) {
      _handleDeepLink(initialLink);
    }
  }

  void _handleDeepLink(String deepLink) {
    // Route based on deep link
    final uri = Uri.parse(deepLink);
    print('Deep link received: ${uri.path}');
    // Navigate to appropriate screen
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'My App',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const HomeScreen(),
    );
  }

  @override
  void dispose() {
    _redirectly.dispose();
    super.dispose();
  }
}

Code Snippets for Every Use Case

Our comprehensive library of code snippets covers the most common deep linking scenarios. Whether you're implementing email verification, tracking referrals, handling push notifications, or reading attribution data, we have production-ready code that you can copy and paste into your project.

Each snippet is fully commented and includes error handling. We provide examples for both Flutter (Dart) and React Native (TypeScript) so you can choose the framework that works best for your team. The snippets demonstrate best practices and integration with popular libraries like go_router, React Navigation, Firebase, and OneSignal.

All code is maintained and updated to work with the latest SDK versions. You can customize the snippets to match your specific needs, such as changing API endpoints, modifying navigation flows, or integrating with your own analytics platform. We recommend reviewing the code and testing thoroughly in your development environment before deploying to production.

Need Custom Implementation?

While our snippets cover common scenarios, every app is unique. Our team can help you customize the implementation for your specific use case, integrate with your backend, or set up advanced attribution tracking.

Get Started with Redirectly

Free API key, subdomain, and 10k monthly links. No credit card required.