Flutter深度链接管理插件legato_centralize_deep_link的使用

Flutter深度链接管理插件legato_centralize_deep_link的使用

特点

  • 生成集中式深度链接URL:创建一个链接到应用程序特定内容或功能的URL。
  • 从深度链接URL提取令牌:从深度链接URL中检索唯一的令牌,然后可以用来查询元数据并执行其他操作。

安装

pubspec.yaml文件中添加依赖:

dependencies:
  legato_centralize_deep_link: ^1.0.0

然后运行以下命令安装:

flutter pub get

使用方法

导入库:

import 'package:legato_centralize_deep_link/legato_centralize_deep_link.dart';
生成集中式深度链接URL

要创建一个集中式的深度链接URL,可以使用generateDeepLink方法。此方法接受一个令牌,并返回一个可以共享或用于导航到应用程序内特定内容的URL。

final _config = const DeepLinkConfiguration(
    projectId: '{PROJECT_ID}',
    apiKey: '{API_KEY}',
    secret: '{SECRET}');

final _env = DeepLinkEnvironment.dev;

Future<void> _generateDeepLink() async {
  String generateLink;
  
  try {
    generateLink = await DeepLink().generateDeepLink(
        _config,
        _env,
        const GenerateLinkRequest(metadata: {
          "page_type": "product",
          "page_id": 1,
          "page_title": "Aliquam erat volutpat."
        }, pageUrl: 'https://placeholder.com/'));
  } on PlatformException {
    generateLink = 'Failed to generate deep link';
  } on Exception {
    generateLink = 'On Exception';
  }

  if (!mounted) return;
  setState(() {
    _deepLink = generateLink;
  });
}
从深度链接URL中提取令牌

要从深度链接URL中提取令牌,可以使用extractTokenFromUrl方法。这将返回元数据,可以用来查询或其他操作。

import 'package:legato_centralize_deep_link/legato_centralize_deep_link.dart';

final _config = const DeepLinkConfiguration(
    projectId: '{PROJECT_ID}',
    apiKey: '{API_KEY}',
    secret: '{SECRET}');

final _env = DeepLinkEnvironment.dev;

Future<void> _extraMetadata(String token) async {
  Map<String, dynamic> metaData = {};

  try {
    final metaRequest = {
      'is_click': false,
      'is_redirect': true,
      'is_flutter': true
    };
    metaData = await DeepLink().extractLinkMetaData(_config, _env, token,
        metaData: metaRequest);
  } on PlatformException {
    _metaData = 'Failed to generate deep link';
  } on Exception {
    _metaData = 'On Exception';
  }

  if (!mounted) return;
  setState(() {
    _metaData = jsonEncode(metaData);
  });
}

Android配置

要在Android上处理深度链接,需要在AndroidManifest.xml文件中为主活动的<activity>标签下添加以下意图过滤器。

步骤1:添加深度链接配置
<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" />
    <data android:host="@string/centralize_host" />
</intent-filter>

<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" />
    <data android:host="@string/centralize_host" />
    <data android:pathPrefix="/token" />
</intent-filter>
步骤2:在res/values/strings.xml中定义centralize_host

打开res/values/strings.xml文件并添加以下行:

<string name="centralize_host">deeplinkdev-dynamic-{name}.legato.co</string>

示例代码

import 'dart:developer';

import 'package:legato_centralize_deep_link/legato_centralize_deep_link.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  return runApp(MainBody());
}

class MainBody extends StatelessWidget {
  final router = AppRouter(); // 假设有一个AppRouter类

  MainBody({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp.router(
      title: 'Centralize DeepLinks Example',
      routerConfig: router.config(deepLinkTransformer: _transformDeepLink),
    );
  }

  Future<Uri> _transformDeepLink(Uri uri) async {
    log('_transformDeepLink: $uri');
    if ('deeplinkdev-dynamic-{name}.legato.co' == uri.host) {
      log('_transformDeepLink onDeeplink: $uri');
      final segments = uri.pathSegments;
      if (segments.isNotEmpty && segments.last.isNotEmpty) {
        final token = segments.last;
        final metadata = await HandleDeepLinks.instance.extraMetadata(token);
        final referralCode = metadata['referral_code'];
        if (referralCode != null && referralCode is String && referralCode.isNotEmpty) {
          final transform = uri.replace(
              path: '/location',
              queryParameters: {'referral_code': referralCode});
          log('_transformDeepLink onDeeplink transform: $transform');
          return SynchronousFuture(transform);
        }
      }
    }
    return SynchronousFuture(uri);
  }
}

更多关于Flutter深度链接管理插件legato_centralize_deep_link的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter深度链接管理插件legato_centralize_deep_link的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


legato_centralize_deep_link 是一个用于 Flutter 应用的深度链接管理插件。它可以帮助开发者集中管理应用内的深度链接,简化深度链接的处理流程。以下是如何使用 legato_centralize_deep_link 插件的详细步骤:

1. 添加依赖

首先,在 pubspec.yaml 文件中添加 legato_centralize_deep_link 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  legato_centralize_deep_link: ^1.0.0  # 请使用最新版本

然后运行 flutter pub get 来安装依赖。

2. 配置 Android 和 iOS 的深度链接

为了确保深度链接在 Android 和 iOS 上正常工作,你需要分别在 AndroidManifest.xmlInfo.plist 文件中进行配置。

Android 配置

AndroidManifest.xml 文件中,添加以下配置:

<activity
    android:name=".MainActivity"
    android:launchMode="singleTask">
    <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="yourapp" android:host="example.com" />
    </intent-filter>
</activity>

yourappexample.com 替换为你的应用的实际 scheme 和 host。

iOS 配置

Info.plist 文件中,添加以下配置:

<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLName</key>
        <string>com.example.yourapp</string>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>yourapp</string>
        </array>
    </dict>
</array>

同样,将 yourapp 替换为你的应用的实际 scheme。

3. 初始化插件

在你的 Flutter 应用的 main.dart 文件中,初始化 legato_centralize_deep_link 插件:

import 'package:flutter/material.dart';
import 'package:legato_centralize_deep_link/legato_centralize_deep_link.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: DeepLinkHandler(),
    );
  }
}

class DeepLinkHandler extends StatefulWidget {
  @override
  _DeepLinkHandlerState createState() => _DeepLinkHandlerState();
}

class _DeepLinkHandlerState extends State<DeepLinkHandler> {
  final LegatoCentralizeDeepLink _deepLink = LegatoCentralizeDeepLink();

  @override
  void initState() {
    super.initState();
    _initializeDeepLinks();
  }

  void _initializeDeepLinks() async {
    // 监听深度链接
    _deepLink.onDeepLinkReceived.listen((String? deepLink) {
      if (deepLink != null) {
        // 处理深度链接
        _handleDeepLink(deepLink);
      }
    });

    // 初始化深度链接
    await _deepLink.initialize();
  }

  void _handleDeepLink(String deepLink) {
    // 根据深度链接跳转到相应的页面
    // 例如: deepLink = "yourapp://example.com/profile?id=123"
    // 你可以解析 deepLink 并跳转到相应的页面
    print("Received deep link: $deepLink");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Deep Link Example'),
      ),
      body: Center(
        child: Text('Deep Link Handling'),
      ),
    );
  }
}

4. 处理深度链接

在上面的代码中,_handleDeepLink 方法用于处理接收到的深度链接。你可以根据深度链接的内容跳转到相应的页面或执行相应的操作。

5. 测试深度链接

你可以通过以下方式测试深度链接:

  • Android: 在终端中运行以下命令:
    adb shell am start -W -a android.intent.action.VIEW -d "yourapp://example.com/profile?id=123" com.example.yourapp
回到顶部