How to Use Deep Linking in Flutter?
Tags: flutter, programming, tutorial
Published: 2023-02-09 06:42:18

We will learn how to incorporate deep linking in Flutter applications with both the Android and iOS platforms in this tutorial. The capacity to connect to a specific page inside of a native iOS or Android mobile app is known as deep linking. Flutter web app enables deep linking in web browsers, iOS, and Android applications. The URL opens your program to that screen. You can launch and display routes using named routes, the Router widget, or both (either using the routes argument or onGenerateRoute).

Deep linking gives you access to a web browser link that directs you to a particular section of an already-installed app. Additionally, these links can be configured to direct viewers to particular content pages (such as events, news updates, and more) and transmit personalized data (like promo codes).

Deep links enable you to access specific content pages on a website as opposed to the home page and allow you to send unique data, such as coupon codes, through. This necessitates that we handle whether an application was launched manually or via a link. We also need to handle link clicks in the background of an application that is running because it can already be opened when the link is clicked. Let’s look at the best way to implement this with Flutter.

Setting up the proper permissions is important before you can begin working with links. Permissions are set up for the Flutter app in the exact same way as the comparable native options.

##IOS in URL Schemes

“Custom URL schemes” and “Universal Links” are the two methods for deep linking.

Custom URL schemes don’t require a host specification and allow operation with any scheme. However, a unique scheme must be guaranteed, and this strategy won’t operate without an installed program. You have the option to work with URLs using custom URL schemes: your_scheme://any_host

The complexity of Universal Links is a little higher. Only work with an HTTPS method, a specific server, entitlements, and a hosted file called apple-app-site association is permitted. You have the option to launch your app by URL using universal links: **https://your_host**

Let’s attempt the method with custom URL schemes first because it’s simpler. The following must be added to the Info.plist file (we set the application to use the URI poc://deeplink.flutter.dev):

```dart
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLName</key>
<string>deeplink.flutter.dev</string>
<key>CFBundleURLSchemes</key>
<array>
<string>poc</string>
</array>
</dict>
</array>
```

##Android App Links

“App Links” and “Deep Links” are two other methods that essentially have the same purpose.

App Links permit the use of a https method and demand a specific host in addition to a hosted file. resemble the iOS Universal Links.

Similar to iOS’s Custom URL schemes, Deep Links permit the use of a custom scheme without the need for a host or a hosted file.

Let’s take a shorter route for Android and connect the Deep Links functionality. The android.manifest should have the following element:

```dart
<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="https" android:host="tempexample.page.link">
</data></category></category></action></intent-filter>
```

Firebase Dynamic Links provides a range of tools for managing deep linking for applications and websites. The best feature is that each Firebase deep connection, regardless of magnitude, is free. Dynamic links enhance the user experience by directing the user to the intended corresponding site or app content rather than the Play Store. Applications for diverse platform domains appear to be developing, improving, and expanding as a result of this.

##Create Dynamic Link in Firebase

Let’s see how to create a dynamic link in firebase with the Flutter application.

Open the firebase console and Create a new project. To add Firebase Dynamic Links, open the Firebase project.

Open the DynamicLink section in firebase


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wyj9fsousqobls68se5i.jpg)

On a domain that you may customize by adding your own name, company name, trademark, etc., dynamic links are generated. More relevant links that have been customized appear. After displaying this window, click Finish.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n913bohc40p3lmyjtngb.jpg)

Now, on the newly opened page, select the “New Dynamic link” button.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mbdjd6a0fdfy450rlasy.jpg)

Click on the new dynamic link button.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j5e34xqv9ov75g8q2acb.jpg)

You can personalize your short link in the first stage. Any URL prefix is acceptable. I would propose giving it a name based on the function it will do, such as openApp or goToPage.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8uolpl6mkb0gfz30tvxg.jpg)

The behavior of what happens when someone clicks on the dynamic link on iOS can be modified in the next step.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ibh70zclblw7itynivkm.jpg)

If the link works, you should be directed to your app or the App Store after entering it in a browser on an actual mobile device or an emulator. You can also copy the link and click on it from a notes app.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qtu14krdnlj35zsodgos.jpg)

Finally, your link is created.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/64y1543n4lyusgcsqjr8.jpg)

The firebase dynamic links dependent must first be added in order to construct a dynamic link programmatically.

**[firebase_dynamic_links](https://pub.dev/packages/firebase_dynamic_links)** 

Create DynamicLink method (add your SHA 1 key in the firebase project and download json file and add in to your app project)
Let’s see a full example of how to implement a dynamic link:

Add below code in the main.dart file for the UI part.

```dart
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_dynamic_links/firebase_dynamic_links.dart';
import 'package:flutter/material.dart';
import 'package:share/share.dart';
import 'package:url_launcher/url_launcher.dart';
Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  final PendingDynamicLinkData? initialLink =
      await FirebaseDynamicLinks.instance.getInitialLink();
  runApp(const MyApp());
}
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: MyHomePage(),
    );
  }
}
class MyHomePage extends StatefulWidget {
  const MyHomePage({
    Key? key,
  }) : super(key: key);
  @override
  State<myhomepage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<myhomepage> {
  final DynamicLinkService _dynamicLinkService = DynamicLinkService();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          "Deeplink Example",
        ),
      ),
      body: Center(
        child: FutureBuilder<uri>(
            future: _dynamicLinkService.createDynamicLink(),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                Uri? uri = snapshot.data;
                return Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    const Text(
                      "This is your link",
                      style:
                          TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                    ),
                    GestureDetector(
                      onTap: () async {
                        if (snapshot.data != null) {
                          if (await canLaunchUrl((snapshot.data!))) {
                            await launchUrl(snapshot.data!,
                                mode: LaunchMode.inAppWebView);
                          } else {
                            throw 'Could not launch';
                          }
                        }
                      },
                      child: Text(
                        "URL: ${snapshot.data}",
                        style: const TextStyle(fontSize: 16),
                      ),
                    ),
                    const SizedBox(
                      height: 20,
                    ),
                    ElevatedButton(
                      // color: Colors.amber,
                      onPressed: () => Share.share(uri.toString()),
                      child: const Text('Share link'),
                    ),
                  ],
                );
              } else {
                return Container();
              }
            }),
      ),
    );
  }
}
</uri></myhomepage></myhomepage></void>
```

Create dynamicLinkService class in main.dart file for creating dynamic link programmatically.

##Example

```dart
class DynamicLinkService {
  Future<uri> createDynamicLink() async {
    final DynamicLinkParameters parameters = DynamicLinkParameters(
      uriPrefix: 'https://tempexample.page.link',
      link: Uri.parse('https://tempexample.page.link/Tbeh'),
      androidParameters: const AndroidParameters(
        packageName: 'com.android.application',
        minimumVersion: 1,
      ),
    );
    final ShortDynamicLink shortLink =
        await FirebaseDynamicLinks.instance.buildShortLink(parameters);
    final Uri shortUrl = shortLink.shortUrl;
    return shortUrl;
  }
}
</uri>
```

##Output


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e6j4oir4tyg662dl8nap.jpg)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lj95pqqbbvtbhe8h4ugk.jpg)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n8keldj9k2dsq1y46gjy.jpg)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lrqeuoapzp1gah229mxk.jpg)

##Conclusion

Suppose a default app for that action hasn’t been set. In that case, deep linking registers your app with the OS as capable of accessing a specific link and should therefore be one of the possibilities given to the user. While iOS custom URL schemes and Android deep links are acceptable methods of deep linking, App links (Android) and Universal links (iOS) are highly advised instead.

##Frequently Asked Questions (FAQs)

**1. What is the use of deep linking in the Flutter framework?**

Deep linking gives you a web browser link pointing to the specific part of an application already installed. These links are set to navigate users to particular content pages and pass through custom data.

**2. How will deep link work?**

Deep linking works by mapping out every application screen in the same manner as a website. Every individual webpage has a subsequent screen in the application so that consumers can transition easily from web browsing to the app. 

**3. What is deep link analysis used for?**

It includes identifying fraud patterns, finding user groups, and reporting weaknesses or bottlenecks in operations or the supply chain.

**4. What is the deep link in Push notifications?**

Dynamic links are intelligent URLs that permit you to send existing and potential users to any location within the Android or iOS app. It survives the app install procedure; even new users view the content they are looking for when they open the app for the first time.