Flutter SDK - Supporting Referrer Short Links

Creating Short Referrer Links

Generate short, shareable referrer links that enable user-to-user attribution and track app installs from organic referrals.

Version Requirement: This functionality requires SDK version 1.0.7 or higher. Short links remain active for 30 days after creation.

Overview

What Are Short Referrer Links

Short links transform long, parameter-filled Singular Links into compact, secure URLs convenient for sharing via SMS, social media, or in-app invitations.

Create short links dynamically so users can share them with friends to invite them to download and use your app. Each short link tracks the referring user, enabling you to measure viral growth and attribute new installs to specific advocates.


Implementation Requirements

Required Components

Gather these elements before creating a short referrer link:

  • Singular Link: A base tracking link that directs users to your app download. See Singular Links FAQ for setup instructions
  • Dynamic Parameters: Optional custom parameters to add context to the link. View available options in Tracking Link Parameters
  • Referrer Information: Name and ID of the user sharing the link to enable attribution of new installs back to the referrer

SDK Method

CreateReferrerShortLink

Generate a short referrer link with custom parameters and a callback handler for success and error states.

Method Signature:

static void createReferrerShortLink(
  String baseLink,
  String referrerName,
  String referrerId,
  Map<String, String> passthroughParams,
  void Function(String? shortLinkURL, String? error) completionHandler
)

Parameters:

  • baseLink: The original Singular tracking link URL
  • referrerName: Display name of the referring user
  • referrerId: Unique identifier for the referring user
  • passthroughParams: Map containing additional dynamic parameters (pass empty map if none)
  • completionHandler: Callback function with parameters (String? shortLinkURL, String? error)

For complete method documentation, see createReferrerShortLink reference.


Basic Usage Example

Create a short link with custom parameters and implement sharing logic in the success callback.

Dart
import 'package:flutter/material.dart';
import 'package:singular_flutter_sdk/singular.dart';
import 'package:share_plus/share_plus.dart';

class ReferralScreen extends StatelessWidget {
  void handleShareReferral() {
    // Create custom parameters for the link
    final parameters = {
      'channel': 'sms',
      'campaign_id': 'summer_promo_2025',
      'referral_type': 'friend_invite'
    };

    // Generate the short referrer link
    Singular.createReferrerShortLink(
      'https://sample.sng.link/D52wc/cuvk?pcn=test',  // Base Singular Link
      'John Doe',                                      // Referrer name
      'user_12345',                                    // Referrer ID
      parameters,                                      // Custom parameters
      (shortLink, error) {
        if (error != null) {
          // Error occurred during link creation
          print('Error creating short link: $error');
          _showErrorDialog('Failed to create share link. Please try again.');
        } else if (shortLink != null) {
          // Success - short link was created
          print('Generated short link: $shortLink');

          // Share the link using share_plus package
          shareLink(shortLink);
        }
      }
    );
  }

  void shareLink(String shortLink) {
    try {
      Share.share(
        'Join me on this awesome app! $shortLink',
        subject: 'App Invitation'
      );
      print('Link shared successfully');
    } catch (error) {
      print('Error sharing link: $error');
      _showErrorDialog('Failed to share link');
    }
  }

  void _showErrorDialog(String message) {
    // Your dialog implementation
    print('Error: $message');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Referral')),
      body: Center(
        child: ElevatedButton(
          onPressed: handleShareReferral,
          child: Text('Share Referral Link'),
        ),
      ),
    );
  }
}

Advanced Implementation

Implement a complete referral system with retry logic, loading states, and clipboard fallback.

Dart
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:singular_flutter_sdk/singular.dart';
import 'package:share_plus/share_plus.dart';

class ReferralManager extends StatefulWidget {
  final String userId;
  final String userName;
  final String baseLink;

  const ReferralManager({
    Key? key,
    required this.userId,
    required this.userName,
    required this.baseLink,
  }) : super(key: key);

  @override
  _ReferralManagerState createState() => _ReferralManagerState();
}

class _ReferralManagerState extends State<ReferralManager> {
  bool _isGenerating = false;
  String? _lastGeneratedLink;

  Future<String> _generateShortLink({int retryCount = 0}) async {
    final parameters = {
      'channel': 'in_app',
      'campaign_id': 'organic_referral',
      'user_tier': 'premium',
      'referral_timestamp': DateTime.now().millisecondsSinceEpoch.toString()
    };

    final completer = Completer<String>();

    Singular.createReferrerShortLink(
      widget.baseLink,
      widget.userName,
      widget.userId,
      parameters,
      (shortLink, error) async {
        if (error != null) {
          // Retry logic with exponential backoff
          if (retryCount < 3) {
            final delay = Duration(seconds: (1 << retryCount)); // 1s, 2s, 4s
            print('Retrying in ${delay.inSeconds}s... (Attempt ${retryCount + 1}/3)');

            await Future.delayed(delay);
            try {
              final result = await _generateShortLink(retryCount: retryCount + 1);
              completer.complete(result);
            } catch (e) {
              completer.completeError(e);
            }
          } else {
            completer.completeError(Exception(error));
          }
        } else if (shortLink != null) {
          setState(() {
            _lastGeneratedLink = shortLink;
          });
          completer.complete(shortLink);
        } else {
          completer.completeError(Exception('Unknown error occurred'));
        }
      }
    );

    return completer.future;
  }

  Future<void> _handleShare() async {
    setState(() {
      _isGenerating = true;
    });

    try {
      final shortLink = await _generateShortLink();
      print('Short link generated: $shortLink');

      // Attempt to share
      await Share.share(
        '${widget.userName} invited you to join! $shortLink',
        subject: 'App Invitation from ${widget.userName}'
      );

      // Track share event
      Singular.event('referral_link_shared');
      print('Link shared successfully');
    } catch (error) {
      print('Error in share flow: $error');

      // Fallback: Copy to clipboard if available
      if (_lastGeneratedLink != null) {
        await Clipboard.setData(ClipboardData(text: _lastGeneratedLink!));
        _showDialog(
          'Link Copied',
          'Failed to share, but the referral link has been copied to your clipboard!',
        );
      } else {
        _showDialog(
          'Error',
          'Failed to generate referral link. Please check your connection and try again.',
        );
      }
    } finally {
      setState(() {
        _isGenerating = false;
      });
    }
  }

  Future<void> _copyToClipboard() async {
    if (_lastGeneratedLink != null) {
      await Clipboard.setData(ClipboardData(text: _lastGeneratedLink!));
      _showDialog('Copied!', 'Referral link copied to clipboard');
    } else {
      _showDialog('No Link', 'Please generate a link first');
    }
  }

  void _showDialog(String title, String message) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(title),
        content: Text(message),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: Text('OK'),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        if (_isGenerating)
          CircularProgressIndicator()
        else ...[
          ElevatedButton(
            onPressed: _handleShare,
            child: Text('Share Referral Link'),
          ),
          if (_lastGeneratedLink != null) ...[
            SizedBox(height: 16),
            OutlinedButton(
              onPressed: _copyToClipboard,
              child: Text('Copy Link'),
            ),
          ],
        ],
      ],
    );
  }
}

Implementation Best Practices

Error Handling

Implement robust error handling in the callback to manage network failures, invalid parameters, or server issues.

  • Retry Logic: Implement exponential backoff for transient network errors
  • User Feedback: Display clear error messages when link creation fails
  • Fallback Option: Provide alternative sharing methods (e.g., share the full Singular Link if short link creation fails)
  • Validation: Verify parameters before calling createReferrerShortLink to catch issues early

Tracking and Analytics

Leverage referrer information to build viral loops and measure organic growth.

Best Practice: Use consistent referrer IDs that match your internal user identification system. This enables you to:

  • Attribute new installs to specific referring users
  • Reward users for successful referrals
  • Track viral coefficient and K-factor metrics
  • Identify your most valuable brand advocates

Link Expiration

Plan for the 30-day link lifecycle in your sharing strategy.

Important: Short links expire after 30 days. For long-term campaigns or persistent share features, generate new short links periodically or use the full Singular Link as a fallback.


Common Use Cases

In-App Referral Programs

Enable users to invite friends directly from your app with personalized referral links.

  • Reward System: Track referrals and reward users for successful friend signups
  • Social Sharing: Integrate with share_plus package for SMS, WhatsApp, email, and social media
  • Personal Invites: Include referrer name in the shared message for personalization

User-Generated Content

Create shareable links when users generate content they want to share with others.

  • Content Attribution: Track which content drives the most app installs
  • Creator Recognition: Attribute new users to content creators for gamification
  • Campaign Tagging: Add dynamic parameters based on content type or category

Event Invitations

Generate unique links for event invitations that track which attendees bring new users.

  • Event Context: Include event ID and details in link parameters
  • Attendee Tracking: Measure viral spread from event to event
  • Network Effects: Identify events with the highest conversion rates