如何处理 Flutter 应用程序的深度链接

2024-05-21

如何在 Flutter App 中处理 Web URL?

例如: 当任何人在 Whatsapp 中点击我的网站链接时,应用程序运行而不是浏览器,

我想处理 URL 部分,

例如: 点击后https://example.com/shop/{product-name},我得到product-name作为变量并在我的应用程序中加载此产品信息


您可以使用包https://pub.dev/packages/uni_links https://pub.dev/packages/uni_links
您可以查看详细信息https://github.com/avioli/uni_links https://github.com/avioli/uni_links

工作演示unilinks://example.com/path/portion/?uid=123&token=abc
pass uid=123 and token=abc

第 1 步:添加intent-filter to AndroidManifest.xml

<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="unilinks"
                    android:host="example.com" />
</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="unilinks"
                    android:host="host"
                    android:pathPrefix="/path/subpath" />
</intent-filter>

第 2 步:使用下面的示例代码

完整代码

import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:uni_links/uni_links.dart';

void main() => runApp(new MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

enum UniLinksType { string, uri }

class _MyAppState extends State<MyApp> with SingleTickerProviderStateMixin {
  String _latestLink = 'Unknown';
  Uri _latestUri;

  StreamSubscription _sub;

  TabController _tabController;
  UniLinksType _type = UniLinksType.string;

  final List<String> _cmds = getCmds();
  final TextStyle _cmdStyle = const TextStyle(
      fontFamily: 'Courier', fontSize: 12.0, fontWeight: FontWeight.w700);
  final _scaffoldKey = new GlobalKey<ScaffoldState>();

  @override
  initState() {
    super.initState();
    _tabController = new TabController(vsync: this, length: 2);
    _tabController.addListener(_handleTabChange);
    initPlatformState();
  }

  @override
  dispose() {
    if (_sub != null) _sub.cancel();
    _tabController.removeListener(_handleTabChange);
    _tabController.dispose();
    super.dispose();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  initPlatformState() async {
    if (_type == UniLinksType.string) {
      await initPlatformStateForStringUniLinks();
    } else {
      await initPlatformStateForUriUniLinks();
    }
  }

  /// An implementation using a [String] link
  initPlatformStateForStringUniLinks() async {
    // Attach a listener to the links stream
    _sub = getLinksStream().listen((String link) {
      if (!mounted) return;
      setState(() {
        _latestLink = link ?? 'Unknown';
        _latestUri = null;
        try {
          if (link != null) _latestUri = Uri.parse(link);
        } on FormatException {}
      });
    }, onError: (err) {
      if (!mounted) return;
      setState(() {
        _latestLink = 'Failed to get latest link: $err.';
        _latestUri = null;
      });
    });

    // Attach a second listener to the stream
    getLinksStream().listen((String link) {
      print('got link: $link');
    }, onError: (err) {
      print('got err: $err');
    });

    // Get the latest link
    String initialLink;
    Uri initialUri;
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      initialLink = await getInitialLink();
      print('initial link: $initialLink');
      if (initialLink != null) initialUri = Uri.parse(initialLink);
    } on PlatformException {
      initialLink = 'Failed to get initial link.';
      initialUri = null;
    } on FormatException {
      initialLink = 'Failed to parse the initial link as Uri.';
      initialUri = null;
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _latestLink = initialLink;
      _latestUri = initialUri;
    });
  }

  /// An implementation using the [Uri] convenience helpers
  initPlatformStateForUriUniLinks() async {
    // Attach a listener to the Uri links stream
    _sub = getUriLinksStream().listen((Uri uri) {
      if (!mounted) return;
      setState(() {
        _latestUri = uri;
        _latestLink = uri?.toString() ?? 'Unknown';
      });
    }, onError: (err) {
      if (!mounted) return;
      setState(() {
        _latestUri = null;
        _latestLink = 'Failed to get latest link: $err.';
      });
    });

    // Attach a second listener to the stream
    getUriLinksStream().listen((Uri uri) {
      print('got uri: ${uri?.path} ${uri?.queryParametersAll}');
    }, onError: (err) {
      print('got err: $err');
    });

    // Get the latest Uri
    Uri initialUri;
    String initialLink;
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      initialUri = await getInitialUri();
      print('initial uri: ${initialUri?.path}'
          ' ${initialUri?.queryParametersAll}');
      initialLink = initialUri?.toString();
    } on PlatformException {
      initialUri = null;
      initialLink = 'Failed to get initial uri.';
    } on FormatException {
      initialUri = null;
      initialLink = 'Bad parse the initial link as Uri.';
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _latestUri = initialUri;
      _latestLink = initialLink;
    });
  }

  @override
  Widget build(BuildContext context) {
    final queryParams = _latestUri?.queryParametersAll?.entries?.toList();

    return new MaterialApp(
      home: new Scaffold(
        key: _scaffoldKey,
        appBar: new AppBar(
          title: new Text('Plugin example app'),
          bottom: new TabBar(
            controller: _tabController,
            tabs: <Widget>[
              new Tab(text: 'STRING LINK'),
              new Tab(text: 'URI'),
            ],
          ),
        ),
        body: new ListView(
          shrinkWrap: true,
          padding: const EdgeInsets.all(8.0),
          children: <Widget>[
            new ListTile(
              title: const Text('Link'),
              subtitle: new Text('$_latestLink'),
            ),
            new ListTile(
              title: const Text('Uri Path'),
              subtitle: new Text('${_latestUri?.path}'),
            ),
            new ExpansionTile(
              initiallyExpanded: true,
              title: const Text('Query params'),
              children: queryParams?.map((item) {
                return new ListTile(
                  title: new Text('${item.key}'),
                  trailing: new Text('${item.value?.join(', ')}'),
                );
              })?.toList() ??
                  <Widget>[
                    new ListTile(
                      dense: true,
                      title: const Text('null'),
                    ),
                  ],
            ),
            _cmdsCard(_cmds),
          ],
        ),
      ),
    );
  }

  Widget _cmdsCard(commands) {
    Widget platformCmds;

    if (commands == null) {
      platformCmds = const Center(child: const Text('Unsupported platform'));
    } else {
      platformCmds = new Column(
        children: <List<Widget>>[
          [
            const Text(
                'To populate above fields open a terminal shell and run:\n')
          ],
          intersperse(
              commands.map<Widget>((cmd) => new InkWell(
                onTap: () => _printAndCopy(cmd),
                child: new Text('\n$cmd\n', style: _cmdStyle),
              )),
              const Text('or')),
          [
            new Text(
                '(tap on any of the above commands to print it to'
                    ' the console/logger and copy to the device clipboard.)',
                textAlign: TextAlign.center,
                style: Theme.of(context).textTheme.caption),
          ]
        ].expand((el) => el).toList(),
      );
    }

    return new Card(
      margin: const EdgeInsets.only(top: 20.0),
      child: new Padding(
        padding: const EdgeInsets.all(10.0),
        child: platformCmds,
      ),
    );
  }

  _handleTabChange() {
    if (_tabController.indexIsChanging) {
      setState(() {
        _type = UniLinksType.values[_tabController.index];
      });
      initPlatformState();
    }
  }

  _printAndCopy(String cmd) async {
    print(cmd);

    await Clipboard.setData(new ClipboardData(text: cmd));
    _scaffoldKey.currentState.showSnackBar(new SnackBar(
      content: const Text('Copied to Clipboard'),
    ));
  }
}

List<String> getCmds() {
  String cmd;
  String cmdSuffix = '';

  if (Platform.isIOS) {
    cmd = '/usr/bin/xcrun simctl openurl booted';
  } else if (Platform.isAndroid) {
    cmd = '\$ANDROID_HOME/platform-tools/adb shell \'am start'
        ' -a android.intent.action.VIEW'
        ' -c android.intent.category.BROWSABLE -d';
    cmdSuffix = "'";
  } else {
    return null;
  }

  // https://orchid-forgery.glitch.me/mobile/redirect/
  return [
    '$cmd "unilinks://host/path/subpath"$cmdSuffix',
    '$cmd "unilinks://example.com/path/portion/?uid=123&token=abc"$cmdSuffix',
    '$cmd "unilinks://example.com/?arr%5b%5d=123&arr%5b%5d=abc'
        '&addr=1%20Nowhere%20Rd&addr=Rand%20City%F0%9F%98%82"$cmdSuffix',
  ];
}

List<Widget> intersperse(Iterable<Widget> list, Widget item) {
  List<Widget> initialValue = [];
  return list.fold(initialValue, (all, el) {
    if (all.length != 0) all.add(item);
    all.add(el);
    return all;
  });
}

第 3 步:使用 Android Studio 进行测试

3.1 前往$ANDROID_HOME/platform-tools
3.2 执行命令adb shell
3.3 执行下面命令

am start -W -a android.intent.action.VIEW -c android.intent.category.BROWSABLE -d "unilinks://example.com/path/portion/?uid=123&token=abc"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何处理 Flutter 应用程序的深度链接 的相关文章

随机推荐

  • 如果我拒绝确认,如何防止更改选择框值

    我正在使用国家 地区选择框 当用户选择一个国家 地区时 会出现添加分支链接 并且用户在该国家 地区下添加分支 但是当用户想要更改国家 地区时 则应销毁有关该国家 地区的所有分支 在更改国家 地区之前 会出现一个确认框并显示警告 一切正常 但
  • 在 Excel 中打开文件而不重新计算 NOW()

    在 Excel 2010 2011 和 2013 尝试了所有三个 中 以只读方式打开文件仍然会重新计算 NOW 有没有办法让excel在打开文件时不重新计算 最简单的方法是将自动 默认 计算选项切换为手动 update 首先打开一个空白的新
  • Python Tkinter 错误,“创建图像太早”

    所以我有一个作业 我必须使用 Tkinter 来创建一个棋盘游戏 这只是程序的一部分 我想在其中引入电路板的图像 但我不断收到错误 创建图像太早 并且我不确定我做错了什么 到目前为止 这是我的代码 from Tkinter import f
  • .NET 标准消息实际上与用于通用消息发送的 .NET Framework BrokeredMessage 不兼容吗?

    我可以指出的最好的地方之一是这个线程 https github com Azure azure service bus dotnet issues 239 https github com Azure azure service bus d
  • Java EE 快速通道(快速学习企业 Java)[关闭]

    就目前情况而言 这个问题不太适合我们的问答形式 我们希望答案得到事实 参考资料或专业知识的支持 但这个问题可能会引发辩论 争论 民意调查或扩展讨论 如果您觉得这个问题可以改进并可能重新开放 访问帮助中心 help reopen questi
  • MacOS 10.15 (Catalina) 中的 ASWebAuthenticationSession

    我正在尝试实施新的ASWebAuthenticationSession在 MacOS 10 15 中 我对callbackURLScheme 头文件为ASWebAuthenticationSession says 回调 URL 通常具有自定
  • 如何在没有嵌入数据源配置的情况下在 Spring Boot 测试期间执行 `schema.sql`?

    有一个带有 h2 数据库的 Spring Boot 应用程序 用作主数据库 还有一个resource schema sql由 Spring Boot 在启动时加载 但在集成测试期间 SpringBootTestSpring Boot 确实n
  • Typescript:按值检查对象是否存在于数组中

    我有这个数据 roles roleId 69801 role ADMIN roleId 69806 role SUPER ADMIN roleId 69805 role RB roleId 69804 role PILOTE roleId
  • 使用行内 r 代码作为 R markdown 标头的一部分

    我希望使用行 R 代码作为 r markdown 文件中标头的一部分 然而 当我编织文件时 标题上使用的字体是不同的 如何确保字体相同 下面是一个简单的例子 r 1 1 Header 您可以将内容括在反引号中以表示内联 r 代码 如下所示
  • Azure 服务总线是否可在 Azure Stack(本地)上使用

    我目前正在通过 Azure Pack 运行 Windows Service Bus 1 1 此版本的官方支持期限于 2018 年 1 月结束 我需要长期的本地服务总线选项 Azure 服务总线是否可以通过 Azure Stack 使用 也在
  • AmCharts:隐藏/显示图表的自定义按钮

    我想要有自己的按钮来隐藏 显示线性图上的线条 图例很好 但我想要我自己的 HTML CSS 有没有办法做到这一点 也许附加隐藏 显示事件 谢谢 您可以致电showGraph http docs amcharts com 3 javascri
  • 我在代码和 Interface Builder 之间建立连接时遇到问题

    我在使用 iPhone SDK 时遇到了一个特殊问题 我尝试在我的开发计算机上运行来自不同来源的多个教程 问题似乎总是在于将代码连接到 Interface Builder 中的视图 如果我有一个按钮或数据字段 或其他一些库函数 并且我在vi
  • Django DateField 表单在 clean_data 中生成 None

    从 django 中的 DateField 表单中选择日期并点击提交按钮后 is valid 成功 但 clean data 显示 None 有谁知道是什么问题 谢谢 forms py class DateForm forms Form d
  • BluetoothAdapter.getDefaultAdapter() 不返回 null

    这是我的第一篇文章 所以如果我做了一些愚蠢的事情 请告诉我 这个问题可能看起来与其他帖子类似 但或多或 少与我所看到的所有内容相反 关于该项目的事情 我正在开发 android 4 0 4 4 应用程序 我正在使用蓝牙 我正在运行 andr
  • Docker 错误绑定:地址已在使用中

    当我跑步时docker compose up在我的 Docker 项目中 它失败并显示以下消息 启动用户层代理时出错 监听 tcp 0 0 0 0 3000 绑定 地址已在使用中 netstat pna grep 3000 显示这个 tcp
  • 如何使用 ggplot2 将 IPCC 点画添加到全球地图

    我需要将 IPCC style 点画添加到全球地图中 如下所示这个帖子 https stackoverflow com questions 11736996 adding stippling to image contour plot 不过
  • 仅显示某些路由的组件 - React

    我正在 React 中开发一个带有登录界面的网站 该网站显示一个自定义导航组件 但是我不希望它显示在主路线 即登录页面 上 但据我了解 静态组件不会在路线更改时重新呈现 这准确吗 我正在使用 React Router 来处理所有路由 这是我
  • 正则表达式查找数字后跟字母[关闭]

    Closed 这个问题需要细节或清晰度 help closed questions 目前不接受答案 我是正则表达式的新手 所以对愚蠢的问题表示歉意 如何识别字符串包含数字后跟字母 例如 在这个地址中 Flat 3a Butterfly St
  • 如何区分列表框中显示的文本和实际值?

    我有一个带有多选选项的列表框 我使用以下方式填充它addItem功能 我在 Google 上找不到任何有关此内容的文章 但我需要区分列表框中显示的文本和实际值 例如 shown hiddenvalue monday A1 tuesday A
  • 如何处理 Flutter 应用程序的深度链接

    如何在 Flutter App 中处理 Web URL 例如 当任何人在 Whatsapp 中点击我的网站链接时 应用程序运行而不是浏览器 我想处理 URL 部分 例如 点击后https example com shop product n