Flutter集成Branch深度链接插件flutter_branch_sdk的使用

发布于 1周前 作者 htzhanglong 来自 Flutter

Flutter集成Branch深度链接插件flutter_branch_sdk的使用

Branch SDK Plugin

Branch 是一个帮助移动应用通过深度链接实现增长的工具,支持引荐系统、分享链接和邀请,并提供完整的归因和分析。Flutter插件flutter_branch_sdk实现了Branch SDK的功能,支持Android、iOS和Web平台。

功能列表

Function Android iOS Web
Test Branch Integration X X Not supported
Track users X X X
Enable / Disable User Tracking X X X
Get First and Last Parameters X X X
Generate Deep Link for Branch Universal Object (BUO) X X X
Show Share Sheet for Branch Universal Object (BUO) X X X
List BUO on Search / Remove BUO from Search X
Register view X X X
Track User Actions and Events X X X
Init Branch Session and Deep Link X X X
Last Attributed Touch Data X X X
QR codes X X X
Share with LPLinkMetadata X
Handle Links in Your Own App X X X

Getting Started

配置Branch Dashboard

  1. 注册您的应用程序。
  2. 配置Branch仪表板

平台项目配置

Android集成

iOS集成

禁用NativeLink™ Deferred Deep Linking

ios/Runner/Info.plist文件中添加:

<key>branch_disable_nativelink</key>
<true/>

更改Flutter Deep link标志(Android/iOS)

对于iOS,在ios/Runner/Info.plist文件中添加:

<key>FlutterDeepLinkingEnabled</key>
<false/>

对于Android,在android/app/src/main/AndroidManifest.xml文件中添加:

<meta-data android:name="flutter_deeplinking_enabled" android:value="false" />

Web集成

web/index.html中添加Branch JavaScript:

<script>
  // load Branch
  (function(b,r,a,n,c,h,_,s,d,k){if(!b[n]||!b[n]._q){for(;s<_.length;)c(h,_[s++]);d=r.createElement(a);d.async=1;d.src="https://cdn.branch.io/branch-latest.min.js";k=r.getElementsByTagName(a)[0];k.parentNode.insertBefore(d,k);b[n]=h}})(window,document,"script","branch",function(b,r){b[r]=function(){b._q.push([r,arguments])}},{_q:[],_v:1},"addListener banner closeBanner closeJourney data deepview deepviewCta first init link logout removeListener setBranchViewData setIdentity track trackCommerceEvent logEvent disableTracking getBrowserFingerprintId crossPlatformIds lastAttributedTouchData setAPIResponseCallback qrCode setRequestMetaData setAPIUrl getAPIUrl setDMAParamsForEEA".split(" "), 0);
  // init Branch
  branch.init('key_live_or_test_YOUR_KEY_GOES_HERE');
</script>

安装

pubspec.yaml文件中添加flutter_branch_sdk作为依赖项。

使用方法

初始化

import 'package:flutter_branch_sdk/flutter_branch_sdk.dart';

await FlutterBranchSdk.init(enableLogging: false, disableTracking: false);

测试Branch集成

FlutterBranchSdk.validateSDKIntegration();

读取深度链接

StreamSubscription<Map> streamSubscription = FlutterBranchSdk.listSession().listen((data) {
  if (data.containsKey("+clicked_branch_link") && data["+clicked_branch_link"] == true) {
    print('Custom string: ${data["custom_string"]}');
  }
}, onError: (error) {
  print('listSession error: ${error.toString()}');
});

创建内容引用(Branch Universal Object)

BranchUniversalObject buo = BranchUniversalObject(
  canonicalIdentifier: 'flutter/branch',
  title: 'Flutter Branch Plugin',
  imageUrl: 'https://raw.githubusercontent.com/RodrigoSMarques/flutter_branch_sdk/master/assets/branch_logo_qrcode.jpeg',
  contentDescription: 'Flutter Branch Description',
  keywords: ['Plugin', 'Branch', 'Flutter'],
  publiclyIndex: true,
  locallyIndex: true,
  contentMetadata: BranchContentMetaData()
    ..addCustomMetadata('custom_string', 'abc')
    ..addCustomMetadata('custom_number', 12345)
    ..addCustomMetadata('custom_bool', true)
    ..addCustomMetadata('custom_list_number', [1,2,3,4,5 ])
    ..addCustomMetadata('custom_list_string', ['a', 'b', 'c']),
);

创建链接引用(BranchLinkProperties)

BranchLinkProperties lp = BranchLinkProperties(
  channel: 'facebook',
  feature: 'sharing',
  stage: 'new share',
  tags: ['one', 'two', 'three']
);
lp.addControlParam('url', 'http://www.google.com');
lp.addControlParam('url2', 'http://flutter.dev');

创建深度链接

BranchResponse response = await FlutterBranchSdk.getShortUrl(buo: buo, linkProperties: lp);
if (response.success) {
  print('Link generated: ${response.result}');
} else {
  print('Error : ${response.errorCode} - ${response.errorMessage}');
}

显示带有深度链接的分享表单

BranchResponse response = await FlutterBranchSdk.showShareSheet(
  buo: buo,
  linkProperties: lp,
  messageText: 'My Share text',
  androidMessageTitle: 'My Message Title',
  androidSharingTitle: 'My Share with');

if (response.success) {
  print('showShareSheet Sucess');
} else {
  print('Error : ${response.errorCode} - ${response.errorMessage}');
}

示例代码

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await FlutterBranchSdk.init(
      enableLogging: true, branchAttributionLevel: BranchAttributionLevel.FULL);
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  void initState() {
    super.initState();
    FlutterBranchSdk.listSession().listen((data) {
      if (data.containsKey("+clicked_branch_link") && data["+clicked_branch_link"] == true) {
        print('Custom string: ${data["custom_string"]}');
      }
    }, onError: (error) {
      print('listSession error: ${error.toString()}');
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

这个示例展示了如何初始化Branch SDK并处理深度链接事件。您可以在initState方法中监听深度链接点击事件,并根据需要处理接收到的数据。


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

1 回复

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


当然,以下是一个关于如何在Flutter项目中集成并使用flutter_branch_sdk插件来实现深度链接功能的代码示例。这个示例将展示如何初始化Branch SDK、设置深度链接监听器以及生成短链接。

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  flutter_branch_sdk: ^latest_version  # 替换为实际的最新版本号

2. 初始化Branch SDK

在你的Flutter应用的入口文件(通常是main.dart)中,初始化Branch SDK。

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

void main() {
  runApp(MyApp());
  // 初始化Branch SDK
  Branch.initSession(
    branchKey: 'your_branch_key_here',  // 替换为你的Branch Key
    debug: true,  // 设置为true以启用调试日志,发布时应设为false
  ).then((result) {
    // 初始化完成后的回调处理
    print('Branch SDK initialized with result: $result');
  }).catchError((error) {
    // 初始化失败的处理
    print('Failed to initialize Branch SDK: $error');
  });
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Branch SDK Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

3. 设置深度链接监听器

在你的首页或适当的组件中,设置深度链接监听器。

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

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  @override
  void initState() {
    super.initState();
    // 设置深度链接监听器
    Branch.addListener((params) {
      // 处理深度链接参数
      print('Received deep link params: $params');
      if (params.containsKey('+clicked_branch_link')) {
        // 处理点击Branch链接的情况
        String link = params['+clicked_branch_link'];
        // 在这里处理链接,例如导航到特定页面
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Branch SDK Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Generate Short Link',
            ),
            ElevatedButton(
              onPressed: () {
                _generateShortLink();
              },
              child: Text('Generate'),
            ),
          ],
        ),
      ),
    );
  }

  void _generateShortLink() async {
    try {
      var linkData = await Branch.createShortUrl(
        branchUniversalObject: BranchUniversalObject(
          canonicalIdentifier: 'item/12345',  // 替换为你的内容标识符
          canonicalUrl: 'https://example.com/item/12345',  // 替换为你的内容URL
          title: 'My Item',
          contentDescription: 'This is my item description',
          contentImageUrl: 'https://example.com/image.png',  // 替换为你的图片URL
        ),
        linkProperties: LinkProperties(
          feature: 'sharing',
          channel: 'facebook',
          campaign: 'spring_sale',
          stage: 'new_user',
          tags: ['hot', 'sale'],
        ),
      );
      print('Short link generated: ${linkData['url']}');
    } catch (error) {
      print('Failed to generate short link: $error');
    }
  }
}

4. 注意事项

  • 确保你已经在Branch Dashboard中正确配置了你的应用,并获取了Branch Key。
  • 在实际发布时,将debug参数设置为false以禁用调试日志。
  • 处理深度链接时,确保根据参数执行适当的操作,例如导航到应用的特定页面。

这个示例展示了如何在Flutter应用中集成Branch SDK并实现基本的深度链接功能。根据你的具体需求,你可能需要进一步定制和扩展这个示例。

回到顶部