← Back to posts Cover image for Mastering Flutter Share Extensions: Building a Cross-Platform Link Saver

Mastering Flutter Share Extensions: Building a Cross-Platform Link Saver

· 4 min read
Weekly Digest

The Flutter news you actually need

No spam, ever. Unsubscribe in one click.

Chris
By Chris

Tired of sending yourself links in a chat only to watch them vanish into the digital void? If you’re a Flutter developer, you can build your own solution. In this post, we’ll walk through creating a cross-platform link saver that integrates directly into your device’s share menu. We’ll tackle the core challenge—receiving shared content—and navigate common pitfalls like handling tricky URLs from platforms like Instagram.

The Core Concept: Platform-Specific Share Targets

Your app can’t just “listen” for shares globally. Instead, you must register as a share target (or “Share Extension”) within the operating system. This is inherently platform-specific.

We’ll use the receive_sharing_intent package to handle the initial data transfer. First, add it to your pubspec.yaml:

dependencies:
  receive_sharing_intent: ^3.0.0

Setting Up the Share Receiver

The core logic involves listening for shared intents (Android) or extension contexts (iOS) when your app is started or is already running. Here’s a basic setup in your main widget’s initState:

import 'package:receive_sharing_intent/receive_sharing_intent.dart';

class LinkSaverHomePage extends StatefulWidget {
  @override
  _LinkSaverHomePageState createState() => _LinkSaverHomePageState();
}

class _LinkSaverHomePageState extends State<LinkSaverHomePage> {
  String? _sharedLink;

  @override
  void initState() {
    super.initState();
    // For when the app is STARTED by a share action
    ReceiveSharingIntent.getInitialText().then((String? value) {
      if (value != null) _processIncomingLink(value);
    });

    // For when the app is already RUNNING and receives a share
    ReceiveSharingIntent.getTextStream().listen((String value) {
      _processIncomingLink(value);
    }, onError: (err) {
      print("Error in sharing stream: $err");
    });
  }

  void _processIncomingLink(String sharedText) {
    // Basic URL extraction - you'd want a more robust regex in production
    final uri = Uri.tryParse(sharedText);
    if (uri != null && (uri.scheme == 'http' || uri.scheme == 'https')) {
      setState(() {
        _sharedLink = sharedText;
      });
      // Here you would save to your database and fetch metadata
      print('Link to save: $_sharedLink');
    }
  }

  @override
  void dispose() {
    ReceiveSharingIntent.reset();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('My Link Vault')),
      body: Center(
        child: _sharedLink != null
            ? Text('Received: $_sharedLink')
            : Text('Share a link to see it here!'),
      ),
    );
  }
}

The Platform Configuration Hurdle

The Dart code is just one piece. You must configure each platform to declare your app as a share target.

For Android: Edit android/app/src/main/AndroidManifest.xml. Inside your main <activity> tag, add an intent filter for the ACTION_SEND action with a text type.

<intent-filter>
    <action android:name="android.intent.action.SEND" />
    <category android:name="android.intent.category.DEFAULT" />
    <data android:mimeType="text/plain" />
</intent-filter>

For iOS: Edit ios/Runner/Info.plist. Add key-value pairs to declare support for plain text and URLs.

<key>CFBundleDocumentTypes</key>
<array>
    <dict>
        <key>CFBundleTypeName</key>
        <string>Text</string>
        <key>LSItemContentTypes</key>
        <array>
            <string>public.plain-text</string>
            <string>public.url</string>
        </array>
    </dict>
</array>

Beyond the Basics: Fetching Reliable Previews

Simply fetching a URL’s Open Graph tags often fails, especially with walled gardens like Instagram. Their servers may return a login page instead of useful metadata. You need a smarter, multi-fallback strategy.

  1. User-Agent is Key: Some sites serve different content to bots. Use a common browser user-agent in your HTTP request headers.
  2. Multiple Fallbacks: Parse Open Graph tags first, then fall back to standard <meta> tags, and finally the <title> element.
  3. Local Caching: Always store the title and a thumbnail URL locally immediately. A link with no preview is better than a broken one.

Here’s a simplified metadata fetcher using the http and html packages:

import 'package:http/http.dart' as http;
import 'package:html/parser.dart' as html;

Future<LinkMetadata> fetchMetadata(String url) async {
  final client = http.Client();
  try {
    final response = await client.get(
      Uri.parse(url),
      headers: {'User-Agent': 'Mozilla/5.0 (compatible; LinkSaverBot/1.0)'},
    );
    final document = html.parse(response.body);

    // Try Open Graph Title
    String? title = document
        .querySelector('meta[property="og:title"]')
        ?.attributes['content'];
    // Fallback to HTML Title
    title ??= document.querySelector('title')?.text;

    // Try Open Graph Image
    String? imageUrl = document
        .querySelector('meta[property="og:image"]')
        ?.attributes['content'];

    return LinkMetadata(
      title: title ?? 'No title found',
      imageUrl: imageUrl,
      sourceUrl: url,
    );
  } catch (e) {
    // Critical: Return a valid object even on failure
    return LinkMetadata(title: 'Failed to fetch', sourceUrl: url);
  } finally {
    client.close();
  }
}

Managing Duplicates and State

Before saving, check your local database (using sqflite or isar) for an existing entry with the same normalized URL. A simple deduplication check prevents clutter. Once saved, clear the _sharedLink state and show a confirmation to the user. Consider adding a notification or a non-intrusive snackbar to confirm the save, completing the “one-tap” experience.

By combining a robust share receiver with intelligent, fault-tolerant metadata fetching, you can build a link-saving app that actually works. It’s a satisfying project that solves a real-world problem and showcases Flutter’s strength in creating integrated, cross-platform experiences.

This blog is produced with the assistance of AI by a human editor. Learn more

Related Posts

Cover image for Choosing the Right Storage for Flutter: Beyond SharedPreferences for Persistent Data

Choosing the Right Storage for Flutter: Beyond SharedPreferences for Persistent Data

Developers frequently struggle with persistent storage in Flutter, especially when dealing with OS-level backups and app reinstalls. This post will clarify the nuances of different storage solutions like `SharedPreferences`, `path_provider`, and `flutter_secure_storage`, focusing on how to correctly manage data lifetimes (per-install vs. per-user) and avoid issues like device IDs migrating to new phones or data being unexpectedly backed up.

Cover image for Optimizing Flutter UI Performance: Solving `ImageFiltered` Lag and Smooth Blurring

Optimizing Flutter UI Performance: Solving `ImageFiltered` Lag and Smooth Blurring

Flutter's `ImageFiltered` can cause significant lag when blurring large or frequently changing content like text. This post will explain the performance bottlenecks, provide solutions like caching blurred outputs with `RepaintBoundary` or `SnapshotWidget`, and offer practical tips to ensure smooth UI effects without sacrificing frame rates.