Implementing Dynamic Deep Linking in Flutter with GoRouter
Deep linking is an essential feature for modern mobile applications, providing a seamless user experience by allowing direct navigation to specific pages within an app. In Flutter, implementing dynamic deep linking can be efficiently achieved with the go_router
package. This approach is particularly useful for apps that open with a homepage and require navigation to specific routes, such as products/1
, through deep links. Let's dive into how you can implement this in your Flutter app, catering to both Android and iOS platforms.
Understanding Deep Linking in Flutter
Deep linking in mobile apps refers to the process of using a URI (Uniform Resource Identifier) to direct a user to a specific page or resource within an application. In the context of a Flutter app, it means opening the app through a URL that takes the user directly to a specific screen, like a particular product detail page.
Setting Up GoRouter for Dynamic Deep Linking
GoRouter
is a powerful and flexible routing package in Flutter that simplifies the implementation of navigation and deep linking.
Step 1: Adding GoRouter to Your Flutter Project
Include go_router
in your project's dependencies:
dependencies:
go_router: ^latest_version
Step 2: Defining Routes with GoRouter
Define your app’s routes using GoRoute
. You'll have a home route and a dynamic route for product details.
final _router = GoRouter(
routes: [
GoRoute(
path: '/',
builder: (context, state) => HomePage(),
),
GoRoute(
path: '/products/:id',
builder: (context, state) {
final id = state.params['id'];
return ProductPage(id: id);
},
),
],
);
Step 3: Handling Deep Links
With go_router
, the handling of deep links is automatically managed. When a user opens a deep link that matches one of your defined routes, the router parses the URL and navigates to the appropriate screen in your app.
Step 4: Configuring Deep Linking for Android and iOS
Android Configuration:
- Update your
AndroidManifest.xml
to declare the intent filters for deep links.
<activity android:name=".MainActivity">
<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="http" android:host="www.example.com" android:pathPrefix="/products" />
</intent-filter>
</activity>
iOS Configuration:
- Configure deep linking in your
Info.plist
file.
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>example</string>
</array>
</dict>
</array>