How to Use Deep Linking in Flutter Apps

What is Deep Linking in Flutter?

by Ans Ali

Deep linking refers to the practice of using a URL or URI (Uniform Resource Identifier) to link to a specific page or resource within a mobile app, rather than simply opening the app’s homepage.

In Flutter, deep linking plays a crucial role in improving the user experience by enabling seamless navigation from external sources like websites, emails, and social media directly into your app. In this article, we’ll explore the use cases of deep linking, why it's important, and how to implement it in Flutter.

Use Cases of Deep Linking

This functionality can be incredibly useful in a variety of use cases:

Promotional Campaigns

Users can be directed to a specific product or promotional offer directly from an ad or a marketing email.

Notifications

When users tap on a push notification, deep links can take them directly to the related content.

Social Sharing

Links shared on social media can open the app and take the user to a specific part of the app.

Types of Deep Linking

There are two main types of deep linking:

Basic Deep Linking

The app opens when a specific URL or URI is invoked.

Deferred Deep Linking

The user is redirected to a specific screen after installing the app from an external link, often used in user onboarding.

Why Use Deep Linking?

Here are some of the key benefits of deep linking in Flutter:

Improved User Experience

Users can be taken directly to the content they are looking for without navigating through multiple screens.

Better User Engagement

By directing users to specific app content, you increase the chances of engagement with that content.

Personalised Marketing

Deep links allow you to direct users to personalised content based on campaigns or user behaviour.

Conversion Tracking

Deep links can help track user activity from external sources to specific actions within the app.

Implementing Deep Linking in Flutter

Flutter makes it relatively easy to implement deep linking both for basic and advanced use cases. Here's a step-by-step guide on how to do it.

Step 1: Set Up URL Schemes

Before you can implement deep linking in your Flutter app, you need to set up URL schemes that define the custom URL structure your app will recognise. For example, you might want your app to handle URLs like myapp://profile/123, where 123 is the user ID.

For iOS
  1. Open the ios/Runner/Info.plist file.
  2. Add the following XML snippet inside the <dict> tag.
<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLName</key>
        <string>com.example.myapp</string>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>myapp</string>
        </array>
    </dict>
</array>
For Android
  1. Open the android/app/src/main/AndroidManifest.xml file.
  2. Add the following intent filter inside the <activity> tag.
<intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
    <data
        android:scheme="myapp"
        android:host="profile" />
</intent-filter>

This setup allows your Flutter app to handle URLs such as myapp://profile.

Step 2: Handle Deep Links in Flutter

Now that your app can handle custom URL schemes, it’s time to detect and respond to these deep links within the Flutter app.

1. Add the uni_links package to your pubspec.yaml file. This package provides support for both iOS and Android deep linking.

dependencies:
    uni_links: ^0.5.1

2. Import the package into your Dart code.

import 'package:uni_links/uni_links.dart';
import 'dart:async';
import 'package:flutter/services.dart';

3. Create a function to listen for incoming deep links.

Future<void> initDeepLinkListener() async {
  try {
     // Listen for incoming deep links while the app is running
     uriLinkStream.listen((Uri? uri) {
       if (uri != null) {
          // Handle the deep link here, e.g., navigate to a specific page
          if (uri.pathSegments.contains('profile')) {
             final id = uri.pathSegments.last;
             // Navigate to the profile page with the given ID
             Navigator.pushNamed(context, '/profile', arguments: id);
          }
       }
    });
  } on PlatformException {
    print("Failed to handle deep link");
  }
}

This function listens for any deep links while the app is running and navigates to the correct page based on the link’s content.

Step 3: Handling App Start from Deep Link

To handle a deep link that opens the app from a background or cold start, you’ll need to check for the initial deep link when the app is first launched.

Future<void> checkInitialLink() async {
  try {
     final initialUri = await getInitialUri();
     if (initialUri != null) {
        // Handle the deep link as you would when the app is running
        if (initialUri.pathSegments.contains('profile')) {
           final id = initialUri.pathSegments.last;
           // Navigate to the profile page with the given ID
           Navigator.pushNamed(context, '/profile', arguments: id);
        }
     }
   } on PlatformException {
     print("Failed to handle initial deep link");
   }
}

Call this function in your app’s initialisation code (e.g. in the initState of your main widget) to check if the app was launched from a deep link.

Wrap-Up

Deep linking in Flutter provides a powerful way to guide users to specific parts of your app directly from external sources. Whether you're implementing basic deep linking with custom URL schemes or advanced deep linking with Firebase Dynamic Links, this feature enhances user engagement and makes your app more accessible. By following this guide, you can implement deep linking efficiently in your Flutter apps, improving navigation and user experience.

Enhance Your Flutter Skills

Stay tuned to our blog for more insight on Flutter development.

Ans Ali 24 سبتمبر, 2024
أرشفة
تسجيل الدخول حتى تترك تعليقاً
How To Debug an App Successfully