Flutter应用链接管理插件app_links_ohos的使用
Flutter应用链接管理插件app_links_ohos的使用
app_links_ohos
Flutter插件用于在OpenHarmony上处理深度链接。
安装 / Installation
在pubspec.yaml
文件中添加以下依赖:
dependencies:
app_links: ^3.4.5
app_links_ohos: any
限制 / Limitations
在OpenHarmony平台上,系统限制从浏览器直接通过自定义Scheme打开应用。如果有需求,推荐使用App Linking。
初始化 / Initialization
在OpenHarmony项目的module.json
文件中添加uris
配置。更多细节请参考App Linking文档。
Flutter
在Flutter中的使用方法和app_links
一致,请参考app_links。
示例代码
以下是一个完整的示例代码,展示了如何使用app_links_ohos
插件来处理深度链接。
示例代码
// ignore_for_file: avoid_print
import 'dart:async';
import 'dart:io';
import 'package:app_links/app_links.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'web_url_protocol.dart'
if (dart.library.io) 'package:url_protocol/url_protocol.dart';
///////////////////////////////////////////////////////////////////////////////
/// 请确保按照以下说明进行设置
///
/// 请查看:
/// - example/android/app/main/AndroidManifest.xml(适用于Android)。
///
/// - example/ios/Runner/Runner.entitlements(通用链接示例)。
/// - example/ios/Runner/Info.plist(自定义URL方案示例)。
///
/// 您可以在Android模拟器上启动一个Intent,如下所示:
/// adb shell am start -a android.intent.action.VIEW \
/// -d "sample://open.my.app/#/book/hello-world"
///
/// 在Windows和macOS上:
/// 最简单的测试方法是打开浏览器并输入:sample://foo/#/book/hello-world2
///////////////////////////////////////////////////////////////////////////////
const kWindowsScheme = 'sample';
void main() {
// 注册我们的协议仅限于Windows平台
_registerWindowsProtocol();
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
[@override](/user/override)
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final _navigatorKey = GlobalKey<NavigatorState>();
late AppLinks _appLinks;
StreamSubscription<Uri>? _linkSubscription;
[@override](/user/override)
void initState() {
super.initState();
initDeepLinks();
}
[@override](/user/override)
void dispose() {
_linkSubscription?.cancel();
super.dispose();
}
Future<void> initDeepLinks() async {
_appLinks = AppLinks();
// 检查初始链接(如果应用处于冷启动状态)
final appLink = await _appLinks.getInitialAppLink();
if (appLink != null) {
print('getInitialAppLink: $appLink');
openAppLink(appLink);
}
// 处理链接(当应用处于热启动状态时)
_linkSubscription = _appLinks.uriLinkStream.listen((uri) {
print('onAppLink: $uri');
openAppLink(uri);
});
}
void openAppLink(Uri uri) {
_navigatorKey.currentState?.pushNamed(uri.fragment);
}
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
navigatorKey: _navigatorKey,
initialRoute: "/",
onGenerateRoute: (RouteSettings settings) {
Widget routeWidget = defaultScreen();
// 模仿Web路由
final routeName = settings.name;
if (routeName != null) {
if (routeName.startsWith('/book/')) {
// 导航到 /book/:id
routeWidget = customScreen(
routeName.substring(routeName.indexOf('/book/')),
);
} else if (routeName == '/book') {
// 导航到 /book 没有其他参数
routeWidget = customScreen("None");
}
}
return MaterialPageRoute(
builder: (context) => routeWidget,
settings: settings,
fullscreenDialog: true,
);
},
);
}
Widget defaultScreen() {
return Scaffold(
appBar: AppBar(title: const Text('默认屏幕')),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const SelectableText('''
启动Intent以进入第二个屏幕。
在Web上:
http://localhost:<port>/#/book/1 例如。
在Windows和macOS上,打开浏览器:
sample://foo/#/book/hello-deep-linking
此示例代码通过URL片段触发新页面。
'''),
const SizedBox(height: 20),
buildWindowsUnregisterBtn(),
],
),
),
);
}
Widget customScreen(String bookId) {
return Scaffold(
appBar: AppBar(title: const Text('第二个屏幕')),
body: Center(child: Text('已打开参数: ' + bookId)),
);
}
Widget buildWindowsUnregisterBtn() {
if (!kIsWeb) {
if (Platform.isWindows) {
return TextButton(
onPressed: () => unregisterProtocolHandler(kWindowsScheme),
child: const Text('移除Windows协议注册'));
}
}
return const SizedBox.shrink();
}
}
void _registerWindowsProtocol() {
// 注册我们的协议仅限于Windows平台
if (!kIsWeb) {
if (Platform.isWindows) {
registerProtocolHandler(kWindowsScheme);
}
}
}
更多关于Flutter应用链接管理插件app_links_ohos的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter应用链接管理插件app_links_ohos的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
app_links_ohos
是一个用于在 Flutter 应用中管理应用链接的插件,特别适用于 OpenHarmony(OHOS)平台。它允许你处理深度链接(Deep Links)和应用链接(App Links),以便在用户点击链接时直接打开你的应用并导航到特定页面。
安装插件
首先,你需要在 pubspec.yaml
文件中添加 app_links_ohos
插件的依赖:
dependencies:
flutter:
sdk: flutter
app_links_ohos: ^1.0.0 # 请使用最新版本
然后运行 flutter pub get
来安装插件。
配置应用链接
1. 配置 AndroidManifest.xml
(仅适用于 Android)
如果你在 Android 平台上使用 app_links_ohos
,你需要在 AndroidManifest.xml
中配置应用链接。以下是一个示例配置:
<activity
android:name=".MainActivity"
android:launchMode="singleTask">
<intent-filter android:autoVerify="true">
<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" android:host="example.com" />
</intent-filter>
</activity>
2. 配置 Info.plist
(仅适用于 iOS)
在 iOS 平台上,你需要在 Info.plist
中配置应用链接。以下是一个示例配置:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLSchemes</key>
<array>
<string>example</string>
</array>
</dict>
</array>
<key>CFBundleURLName</key>
<string>com.example.app</string>
使用 app_links_ohos
插件
1. 初始化插件
在你的 Flutter 应用中,首先需要初始化 app_links_ohos
插件:
import 'package:app_links_ohos/app_links_ohos.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final appLinks = AppLinksOhos();
await appLinks.init();
runApp(MyApp(appLinks: appLinks));
}
2. 监听链接
你可以通过监听 appLinks
来获取用户点击的链接,并根据链接导航到相应的页面:
class MyApp extends StatelessWidget {
final AppLinksOhos appLinks;
MyApp({required this.appLinks});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomeScreen(appLinks: appLinks),
);
}
}
class HomeScreen extends StatefulWidget {
final AppLinksOhos appLinks;
HomeScreen({required this.appLinks});
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
StreamSubscription? _linkSubscription;
@override
void initState() {
super.initState();
_linkSubscription = widget.appLinks.uriLinkStream.listen((Uri uri) {
// 根据 uri 导航到相应的页面
if (uri.path == '/details') {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => DetailsScreen()),
);
}
});
}
@override
void dispose() {
_linkSubscription?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Home'),
),
body: Center(
child: Text('Welcome to the Home Screen!'),
),
);
}
}
3. 处理冷启动链接
在应用冷启动时,你可能需要处理初始链接。你可以通过 getInitialAppLink
方法来获取初始链接:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final appLinks = AppLinksOhos();
await appLinks.init();
// 获取初始链接
final initialUri = await appLinks.getInitialAppLink();
if (initialUri != null) {
// 根据初始链接导航到相应的页面
}
runApp(MyApp(appLinks: appLinks));
}