如何在Flutter应用中开发应用分享功能(含邀请下载场景)
Hey there! Let's tackle your two Flutter sharing questions with practical, actionable solutions – I’ve worked through these scenarios plenty of times, so let’s dive in.
For general sharing (text, links, files) across iOS and Android, the share_plus package is the go-to choice – it’s maintained by the Flutter Community and handles most platform-specific edge cases out of the box. Here’s how to set it up:
Add the dependency
Open yourpubspec.yamland add the latest version ofshare_plus:dependencies: flutter: sdk: flutter share_plus: ^7.2.2 # Check for the latest version on pub.devRun
flutter pub getto install it.Import the package
At the top of your Dart file where you want to implement sharing:import 'package:share_plus/share_plus.dart';Implement the sharing logic
You can create a reusable function to trigger sharing, and call it from a button or any user interaction. For example, sharing a text message with a link:void triggerShare(String content, String subject) { // Share.share() will open the system share sheet Share.share( content, subject: subject, // Optional: Used for email subjects on some platforms ); } // Use it in a button ElevatedButton( onPressed: () => triggerShare( "Check out this cool Flutter app I'm using!", "Recommend a great app", ), child: const Text("Share App"), )Pro tip: You can also share files (like images) using
Share.shareXFiles()– perfect if you want to share app-generated content.
This requires two key parts: generating a unique invite link/code, and handling the link when a new user opens your app. Here’s a step-by-step breakdown:
1. Generate a unique invite link
First, create a shareable link that includes a unique identifier tied to the inviting user (like an invite code or user ID). For example:https://your-app-download-page.com?invite_code=USER_12345
You can generate this code when a user signs up, store it in your backend, and fetch it when the user wants to share.
2. Share the invite link
Use the same share_plus package from the first section to share this link. Tweak the sharing function to include your invite message and link:
void shareInvite(String inviteCode) { String shareMessage = """ Hey! Try out this awesome app – use my invite code $inviteCode to unlock extra rewards when you sign up: https://your-app-download-page.com?invite_code=$inviteCode """; Share.share(shareMessage); }
3. Handle deep linking to capture the invite code
When a new user clicks the invite link, you need to open your app (or redirect to the app store if they don’t have it) and capture the invite_code to apply rewards. For this, use the uni_links package:
Step 3.1: Add the dependency
dependencies: uni_links: ^0.5.1
Step 3.2: Configure platform settings
- Android: Add an intent filter to your
AndroidManifest.xmlto handle your custom scheme (e.g.,yourapp://):<activity android:name=".MainActivity"> <!-- Existing code --> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <!-- Your custom scheme --> <data android:scheme="yourapp" /> <!-- If using Universal Links, add your host here --> <!-- <data android:host="your-app-download-page.com" /> --> </intent-filter> </activity> - iOS: Add your custom scheme to
Info.plist:
For Universal Links, you’ll also need to configure Associated Domains in your Xcode project.<key>LSApplicationQueriesSchemes</key> <array> <string>yourapp</string> </array>
Step 3.3: Listen for deep links in Flutter
Create a listener to capture the invite code when the app opens via the link:
import 'package:uni_links/uni_links.dart'; import 'package:flutter/services.dart'; class InviteHandler extends StatefulWidget { const InviteHandler({super.key}); @override State<InviteHandler> createState() => _InviteHandlerState(); } class _InviteHandlerState extends State<InviteHandler> { String? _capturedInviteCode; @override void initState() { super.initState(); _startDeepLinkListener(); } void _startDeepLinkListener() async { // Capture the initial link if the app was opened from a cold start final initialLink = await getInitialLink(); if (initialLink != null) { _parseInviteCode(initialLink); } // Listen for links when the app is already running in the background linkStream.listen((link) { if (link != null) { _parseInviteCode(link); } }, onError: (error) { // Handle errors (e.g., invalid link format) debugPrint("Deep link error: $error"); }); } void _parseInviteCode(String link) { final uri = Uri.parse(link); final inviteCode = uri.queryParameters['invite_code']; if (inviteCode != null) { setState(() { _capturedInviteCode = inviteCode; }); // Call your backend API here to validate the code and apply rewards _claimInviteReward(inviteCode); } } void _claimInviteReward(String inviteCode) { // Your business logic: e.g., send the code to your backend to credit the inviter debugPrint("Processing invite code: $inviteCode"); } @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Text( _capturedInviteCode != null ? "Thanks for joining with invite code: $_capturedInviteCode" : "Welcome!", ), ), ); } }
4. Fallback for users without the app
If a user clicks the link and doesn’t have your app installed, make sure your download page redirects them to the Apple App Store or Google Play Store. You can detect their device type on the web page and send them to the correct store.
内容的提问来源于stack exchange,提问作者user13749790




