USING OF DYNAMIC LINKS WITH FIREBASE

OGZA Teknoloji
8 min readApr 5, 2021

With this story, I will explain you how to use Firebase Dynamic Links with images in your applications.

Firebase is a platform served by Google for application managers in order to develop, manage and enhance their applications. Firebase has several features for app developers and Dynamic Links is one of them.

Dynamic Links can be used in many fields such as sharing a content in an app from user to user or viewing a content ideally in regard to used device. It can be provided that the link created with Firebase Dynamic Links is opened. Besides, if the application is not installed in user’s mobile device, this link can open the download page in app store depending the platform which contains the link. In addition to these features, if this dynamic link is opened in a desktop browser, it can take users to the equivalent content on your website. Dynamic Links can be followed up via Google Analytics and in the shares across the social media, title, explanation and pictures can be added with the link.

Below, I will gradually indicate how to build up a Dynamic Link. First of all, click here, build a project and name your Firebase project in opening page.

After naming your project, click Continue button and create your project. In the first page after creating your project, you must choose proper button for which platform/s -IOS or Android- you will develop your project and continue.

If you create the application for IOS, you must fill Bundle ID and App nickname sections. To find Bundle ID, you should open project.pbxproj file in ios\Runner.xcodeproj folder of your app and search as PRODUCT_BUNDLE_IDENTIFIER.

If you create the application for Android, you must fill package name and App nickname sections. To find package name, you should open AndroidManifest.xml file in \android\app\src\main folder of your app, there must be a code as package=com.company.appname

After creating your project, the next screen will be seemed as the following.

When you choose IOS button or Android button, it will be a shift to the following pages.

Creating Dynamic Link for Android applications:

Creating Dynamic Link for IOS applications:

After creating your project and applications in Firebase, you must not forget to store up google-services.json files to /android/app folder for Android, googleservice-info.plist files to /ios/Runner folder for IOS.

Next, click the Dynamic Links on sidebar and get started.

Firebase offers a free domain for its users named as *.page.link but if you want you can use your domain name also.

After choosing your domain name, continue and finish the processes.

Open pubspec.yaml folder in your application and add firebase_core and firebase_dynamic_links packages. You can add package_info package if you want, it is not compulsory.

After that, to use Firebase in your application, into the main block in the main.dart folder, before RunApp() function, add

WidgetsFlutterBinding.ensureInitialized();await Firebase.initializeApp();

codes.

Gist

In this application, build a color code randomly and add into the link as parameter. On shared link open, a page which includes that built color will be opened in the application. First, we build our function.

Future<String> createDynamicLink() async {}

Then, generate DynamicLinkParameters object from firebase_dynamic_linking package.

Future<String> createDynamicLink() async {final DynamicLinkParameters parameters = DynamicLinkParameters(uriPrefix: "", link: Uri());}

uriPrefix and link parameters are compulsory.

uriPrefix domain is the address begins with *.page.link previously built on Firebase, link is the url which we will share (you can use the url you want).

Future<String> createDynamicLink() async {String dynamicLinkUriPrefix = "https://ogzatutorial.page.link/";String randomColor = Random().nextInt(0xffffffff).toString();String url = "$dynamicLinkUriPrefix?color=$randomColor";final DynamicLinkParameters parameters = DynamicLinkParameters(uriPrefix: dynamicLinkUriPrefix,link: Uri.parse(url),);}

Build a color code randomly and add this code ?color=$randomColor to the link as “query string”

Actually, to build a link you have many opportunities. If the application is not installed on your user’s device, you make them to open the page of application store according to which platform is used via the link.

For this procedure, you must add androidParameters and iosParameters parameters as shown below. For Android, you can write package name and minimum application function and for IOS, you can add appStoreId in addition to those. Here, instead of writing manually, I used package_info package, if you want you can manually write.

Future<String> createDynamicLink() async {String dynamicLinkUriPrefix = "https://ogzatutorial.page.link/";String randomColor = Random().nextInt(0xffffffff).toString();String url = "$dynamicLinkUriPrefix?color=$randomColor";PackageInfo packageInfo = await PackageInfo.fromPlatform();final DynamicLinkParameters parameters = DynamicLinkParameters(uriPrefix: dynamicLinkUriPrefix,link: Uri.parse(url),androidParameters: AndroidParameters(packageName: packageInfo.packageName,minimumVersion: 1,),iosParameters: IosParameters(bundleId: packageInfo.packageName,minimumVersion: '1.0.1',appStoreId: '123456789',),);}

As I told before, you can use googleAnalyticsParameters and itunesConnectAnalyticsParameters parameters to get information about the link built across Google Analytics ve ITunes Connect. The parameters campaign, content, medium, source and term are available in GoogleAnalyticsParameters class. affiliateToken, campaignToken ve providerToken parameters are available in ItunesConnectAnalyticsParameters class.

Future<String> createDynamicLink() async {String dynamicLinkUriPrefix = "https://ogzatutorial.page.link/";String randomColor = Random().nextInt(0xffffffff).toString();String url = "$dynamicLinkUriPrefix?color=$randomColor";PackageInfo packageInfo = await PackageInfo.fromPlatform();final DynamicLinkParameters parameters = DynamicLinkParameters(uriPrefix: dynamicLinkUriPrefix,link: Uri.parse(url),androidParameters: AndroidParameters(packageName: packageInfo.packageName,minimumVersion: 1,),iosParameters: IosParameters(bundleId: packageInfo.packageName,minimumVersion: '1.0.1',appStoreId: '123456789',),googleAnalyticsParameters: GoogleAnalyticsParameters(campaign: 'example',medium: 'social',source: 'app',),itunesConnectAnalyticsParameters: ItunesConnectAnalyticsParameters(providerToken: '123456',campaignToken: 'example',),);}

Lastly, you can use socialMetaTagParameters parameters so that user can understand content of the link which is shared on social media without clicking it. For example, when you build the link as shown below and send it to a user on social media such as Whatsapp or Instagram, it will appear as a description like Chosen image, Trial title and This is a trial.

Future<String> createDynamicLink() async {String dynamicLinkUriPrefix = "https://ogzatutorial.page.link/";String randomColor = Random().nextInt(0xffffffff).toString();String url = "$dynamicLinkUriPrefix?color=$randomColor";PackageInfo packageInfo = await PackageInfo.fromPlatform();final DynamicLinkParameters parameters = DynamicLinkParameters(uriPrefix: dynamicLinkUriPrefix,link: Uri.parse(url),androidParameters: AndroidParameters(packageName: packageInfo.packageName,minimumVersion: 1,),iosParameters: IosParameters(bundleId: packageInfo.packageName,minimumVersion: '1.0.1',appStoreId: '123456789',),googleAnalyticsParameters: GoogleAnalyticsParameters(campaign: 'example',medium: 'social',source: 'app',),itunesConnectAnalyticsParameters: ItunesConnectAnalyticsParameters(providerToken: '123456',campaignToken: 'example',),socialMetaTagParameters: SocialMetaTagParameters(title: 'Deneme',description: 'Bu bir denemedir!',imageUrl: Uri.parse("https://ogzatech.com/tr/img/core-img/logo.png"),),);}

We have completed our DynamicLinkParameters object henceforward for the rest, we only will build the link. If you want to build a long link, you can use buildUrl function, or, if you want to build a short link you can use buildShortLink function.

Gist

Future<String> createDynamicLink() async {String dynamicLinkUriPrefix = "https://ogzatutorial.page.link/";String randomColor = Random().nextInt(0xffffffff).toString();String url = "$dynamicLinkUriPrefix?color=$randomColor";PackageInfo packageInfo = await PackageInfo.fromPlatform();final DynamicLinkParameters parameters = DynamicLinkParameters(uriPrefix: dynamicLinkUriPrefix,link: Uri.parse(url),androidParameters: AndroidParameters(packageName: packageInfo.packageName,minimumVersion: 1,),iosParameters: IosParameters(bundleId: packageInfo.packageName,minimumVersion: '1.0.1',appStoreId: '123456789',),googleAnalyticsParameters: GoogleAnalyticsParameters(campaign: 'example',medium: 'social',source: 'app',),itunesConnectAnalyticsParameters: ItunesConnectAnalyticsParameters(providerToken: '123456',campaignToken: 'example',),socialMetaTagParameters: SocialMetaTagParameters(title: 'Deneme',description: 'Bu bir denemedir!',imageUrl: Uri.parse("https://ogzatech.com/tr/img/core-img/logo.png"),),);final Uri dynamicUrl = await parameters.buildUrl();final ShortDynamicLink shortenedLink = await parameters.buildShortLink();print("Full: ${dynamicUrl.toString()} Short:${shortenedLink.shortUrl}");return shortenedLink.shortUrl.toString();}

In this way, the link is built. You can call this link which is in debug console within a button that you created in the application. After clicking this link, you can make it do whichever function that you want to open in the application. For example, lets describe a function called initDynamicLinks and call this function in initState function.

In this function, we will use FirebaseDynamicLinks.instance.onLink() listener and FirebaseDynamicLinks.instance.getInitialLink() functions.

While the application called Listener is running actively, we will be notified as soon as the link delivered. In addition, while the application is offline, getInitialLink function will deliver the link as soon as the app is online.

Lets start with Listener.

void initDynamicLinks() async {FirebaseDynamicLinks.instance.onLink(onSuccess: (PendingDynamicLinkData dynamicLink) async {final Uri deepLink = dynamicLink?.link;if (deepLink != null) {var deepLinkPath = deepLink.path;var deepLinkQueryParameters = deepLink.queryParameters;}}, onError: (OnLinkErrorException e) async {print('onLinkError');print(e.message);});}

If deepLink is not null, deepLinkPath will give us the url that delivered to us. deepLinkQueryParameters will give us query strings.

While creating the link, we added color query. We will convert this color to Color object and open it in a new page.

Firstly, create new page. I will add appBar into Scaffold and a Text into body in this page. I will use the color which come from the link for backgroundColor of Scaffold.

Gist

import 'package:flutter/material.dart';class DynamicPage extends StatelessWidget {final Color backgroundColor;const DynamicPage({Key key, @required this.backgroundColor}): super(key: key);@overrideWidget build(BuildContext context) {return Scaffold(backgroundColor: backgroundColor,appBar: AppBar(backgroundColor: backgroundColor,title: Text("Başlık",style: Theme.of(context).textTheme.headline6.copyWith(color: Colors.white),),),body: Center(child: Text("${backgroundColor.toString()}",style: TextStyle(color: Colors.white),),),);}}

After creating second page, now we are approaching the end.

Both the application is offline and online, we will use common codes. If you want, you can make it separately.

Create a function called parseColorAndNavigate and in this function, use deepLinkQueryParameters which you take from the link. Because this is a map, check for containsKey function and “color” key is inside the map or not. If it is found in map, first convert it to int, then create Color object. After that, go to generated page with Navigator.push

Gist

void initDynamicLinks() async {FirebaseDynamicLinks.instance.onLink(onSuccess: (PendingDynamicLinkData dynamicLink) async {final Uri deepLink = dynamicLink?.link;if (deepLink != null) {var deepLinkPath = deepLink.path;var deepLinkQueryParameters = deepLink.queryParameters;parseColorAndNavigate(deepLinkQueryParameters);}}, onError: (OnLinkErrorException e) async {print('onLinkError');print(e.message);});}void parseColorAndNavigate(Map<String, String> deepLinkQueryParameters) {if (deepLinkQueryParameters.containsKey("color")) {String colorStringValue = deepLinkQueryParameters["color"].toString();try {int colorIntegerValue = int.tryParse(colorStringValue);Color color = Color(colorIntegerValue);Navigator.push(context,MaterialPageRoute(builder: (context) => DynamicPage(backgroundColor: color),),);} catch (e) {print("Integer parsing hata.");}}}

We completed the process that taking the link and switching it another page while the application is online. Let’s complete the process that will occur when the application is opened if it is offline.

We will use parseColorAndNavigate function after calling and checking FirebaseDynamicLinks.instance.getInitialLink function.

Gist

void initDynamicLinks() async {FirebaseDynamicLinks.instance.onLink(onSuccess: (PendingDynamicLinkData dynamicLink) async {final Uri deepLink = dynamicLink?.link;if (deepLink != null) {var deepLinkPath = deepLink.path;var deepLinkQueryParameters = deepLink.queryParameters;parseColorAndNavigate(deepLinkQueryParameters);}}, onError: (OnLinkErrorException e) async {print('onLinkError');print(e.message);});final PendingDynamicLinkData data =await FirebaseDynamicLinks.instance.getInitialLink();final Uri deepLink = data?.link;if (deepLink != null) {var deepLinkPath = deepLink.path;var deepLinkQueryParameters = deepLink.queryParameters;parseColorAndNavigate(deepLinkQueryParameters);}}

When you respectively follow the steps aforementioned, you will have created Dynamic Link successfully.

Good luck!

If you want to see codes in one page, you can click the links below.

For ready main file, click here.

For Dynamic page file, click here.

--

--

OGZA Teknoloji

Görüntü işleme üzerine ar-ge projeleri başta olmak üzere mobil uygulamalar ve optimizasyon alanında projeler geliştirmektedir.