Chapters

Hide chapters

Real-World Flutter by Tutorials

First Edition · Flutter 3.3 · Dart 2.18 · Android Studio or VS Code

Real-World Flutter by Tutorials

Section 1: 16 chapters
Show chapters Hide chapters

8. Deep Linking
Written by Edson Bueno

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

You just went through an entire chapter on routing and navigation. Since this isn’t a beginner’s book, that surely wasn’t a new topic for you at that point, but the reason it had to be covered was that the routing system you were probably familiar with, Navigator 1, doesn’t have good deep link support.

You then learned how to use Flutter’s Navigator 2, built from the ground up with deep links in mind. This chapter is where deep links finally come into play, and all the work from the previous chapter pays off. But what are deep links?

An app that supports deep links is an app that can launch in response to the user opening a link. Have you ever tapped a link, and that link opens an app instead of a web page? That’s because that app supports deep links. Notice the link doesn’t simply launch the app; it navigates to specific content within the app — hence the deep in the name.

Deep links are primarily used to allow users to share content — Spotify playlists, social media posts, etc. — the examples are countless. Another example of deep links in action is when you receive a notification, tap it, and that takes you to a related screen inside the app — you see that a lot in chat apps.

Adding deep link support to an app isn’t as easy as one might imagine. It involves two different challenges:

  • Making the system know it has to launch your app when the user opens certain links.
  • Making your app take the user to the right screen once the system launches it.

The second part is pretty much complete, thanks to the robust routing strategy you already have in place. The first part, though, can be quite complicated, as it involves some web knowledge, like domains. Luckily, Firebase is your friend here. Firebase’s specialty is saving client developers from having to know stuff they don’t care about.

You’ll implement deep links with the help of Firebase Dynamic Links. Firebase’s solution works on top of an enhanced type of deep links, called dynamic links. Dynamic links are deep links that can:

  • Work across different platforms: If a user opens the link on their phone, they can be taken directly to the linked content in your native app. If a user opens the same link in a desktop browser, they can be taken to the equivalent content on your website.
  • Work across app installs: If a user opens the link on their phone and doesn’t have your app installed, the user is sent to the Play Store or App Store to install it. Then, after installation, your app starts and opens the specific content.

Roll up your sleeves! In this chapter, you’ll learn how to:

  • Configure a Firebase project to support dynamic links.
  • Generate dynamic links on the fly.
  • Launch your app in response to a dynamic link.
  • Respond to a dynamic link coming in when your app is already open.

Throughout this chapter, you’ll work on the starter project from this chapter’s assets folder.

Getting Started

Use your IDE of choice to open the starter project. Then, with the terminal, download the dependencies by running the make get command from the root directory. Wait a while for the command to finish executing, then build and run your app on an Android device — either physical or virtual.

Why Android? You can’t test dynamic links on iOS unless you have a paid Apple Developer Account; thus, very few readers of this book probably have one. Therefore, for brevity, this chapter will proceed using an Android emulator but will give you a link with the additional instructions you need for iOS.

After running your app, this is what you should see:

Note: If you’re having trouble running the app, it’s because you forgot to propagate the configurations you did in the first chapter’s starter project to the following chapters’ materials. If that’s the case, please revisit Chapter 1, “Setting up Your Environment”.

Your app is pretty much complete, except it can’t handle deep links yet. Tap a quote to go to the quote details screen, and you’ll notice the Share button on the app bar doesn’t respond when you tap it.

What that Share button should do is allow the user to share a deep link that, when opened, takes the recipient to that same exact quote inside the WonderWords app. From here on, your job is to make sure that:

  • The button responds appropriately when users tap it.
  • The app can open that same quote when the link is opened.

Your first step on that mission is to configure your Firebase’s dashboard.

Setting up Firebase

Go to Firebase’s console, and open the project you created in Chapter 1, “Setting up Your Environment”.

Building a Dynamic Link on Demand

You might think generating a dynamic link is just a matter of appending the path of the screen you want to open to the base URL you created on Firebase, something like: https://wonderwords1.page.link/quotes/27231. It’s actually a bit more complicated than that.

static const _domainUriPrefix = 'YOUR_FIREBASE_DYNAMIC_LINK_URL';
// 1
Future<String> generateDynamicLinkUrl({
  required String path,
  SocialMetaTagParameters? socialMetaTagParameters,
}) async {
  // 2
  final parameters = DynamicLinkParameters(
    link: Uri.parse(
      '$_domainUriPrefix$path',
    ),
    uriPrefix: _domainUriPrefix,
    androidParameters: const AndroidParameters(
      packageName: _androidPackageName,
    ),
    iosParameters: const IOSParameters(
      bundleId: _iOSBundleId,
    ),
    socialMetaTagParameters: socialMetaTagParameters,
  );

  // 3
  final shortLink = await _dynamicLinks.buildShortLink(parameters);
  return shortLink.shortUrl.toString();
}

// 1
shareableLinkGenerator: (quote) {
  // 2
  return dynamicLinkService.generateDynamicLinkUrl(
    path: _PathConstants.quoteDetailsPath(
      quoteId: quote.id,
    ),
    socialMetaTagParameters: SocialMetaTagParameters(
      title: quote.body,
      description: quote.author,
    ),
  );
},

Opening a Dynamic Link When Your App Is Closed

Go back to lib/src/dynamic_link_service.dart under the monitoring package.

Future<String?> getInitialDynamicLinkPath() async {
  final data = await _dynamicLinks.getInitialLink();
  final link = data?.link;
  return link?.path;
}

@override
void initState() {
  super.initState();
    
  _openInitialDynamicLinkIfAny();
    
  // TODO: Listen to new dynamic links.
}

Future<void> _openInitialDynamicLinkIfAny() async {
  // 1
  final path = await _dynamicLinkService.getInitialDynamicLinkPath();
  if (path != null) {
    // 2
    _routerDelegate.push(path);
  }
}

Opening a Dynamic Link When Your App Is Already Open

You just covered the scenario in which a dynamic link launches your app. But what if your app was already open? To handle that, go back to the monitoring internal package and open lib/src/dynamic_link_service.dart.

// 1
Stream<String> get onNewDynamicLinkPath {
  // 2
  return _dynamicLinks.onLink.map(
    (PendingDynamicLinkData data) {
      final link = data.link;
      final path = link.path;
      // 3
      return path;
    },
  );
}

// 1
_incomingDynamicLinksSubscription =
    // 2
    _dynamicLinkService.onNewDynamicLinkPath.listen(
          // 3
          _routerDelegate.push,
        );

Key Points

  • An app that supports deep links can be launched in response to the user tapping a link.
  • Using Firebase Dynamic Links is the easiest and most robust way to implement deep links in an app.
  • Dynamic links are just special deep links that:
  • When generating dynamic links, use the functions provided by the official package so you can build shortened links easily.
  • When writing the code that handles an incoming dynamic link, you always need to consider that your app can be in two different states: closed or minimized.
Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.

You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now