import 'dart:async'; import 'package:flutter/material.dart'; import 'package:receive_sharing_intent/receive_sharing_intent.dart'; import 'quick_share_sheet.dart'; class ShareReceiverService { StreamSubscription? _intentSub; void init(BuildContext context) { // 1. Listen to shared media/text while app is in memory _intentSub = ReceiveSharingIntent.instance.getMediaStream().listen((List value) { if (value.isNotEmpty) { _handleSharedMedia(context, value); } }, onError: (err) { debugPrint("getMediaStream error: $err"); }); // 2. Get the shared media/text when the app is launched from closed state ReceiveSharingIntent.instance.getInitialMedia().then((List value) { if (value.isNotEmpty) { _handleSharedMedia(context, value); } }); } void _handleSharedMedia(BuildContext context, List files) { if (files.isEmpty) return; for (final file in files) { final path = file.path; if (path.isEmpty) continue; // Check if it's an image file final lower = path.toLowerCase(); if (file.type == SharedMediaType.image || lower.endsWith('.jpg') || lower.endsWith('.png') || lower.endsWith('.jpeg') || lower.endsWith('.webp')) { showModalBottomSheet( context: context, isScrollControlled: true, backgroundColor: Colors.transparent, builder: (ctx) => QuickShareSheet(imagePath: path), ); return; } // Otherwise it's shared text or URL final urlRegex = RegExp(r'https?://[^\s]+'); final match = urlRegex.firstMatch(path); final url = match?.group(0); final rawCaption = path.replaceFirst(url ?? '', '').trim(); showModalBottomSheet( context: context, isScrollControlled: true, backgroundColor: Colors.transparent, builder: (ctx) => QuickShareSheet( url: url, rawCaption: rawCaption.isNotEmpty ? rawCaption : null, ), ); return; } } void dispose() { _intentSub?.cancel(); } }