Flutter固定快捷方式插件flutter_pinned_shortcut的使用

Flutter固定快捷方式插件flutter_pinned_shortcut的使用

flutter_pinned_shortcut 是一个用于在 Android 设备上创建类似 Messenger 聊天气泡的固定快捷方式的 Flutter 插件。

截图

Screenshot

导入插件

首先,确保您已经在 pubspec.yaml 文件中添加了该插件,并导入它:

import 'package:flutter_pinned_shortcut/flutter_pinned_shortcut.dart';

创建对象

接下来,创建插件的对象实例:

final FlutterPinnedShortcut flutterPinnedShortcutPlugin = FlutterPinnedShortcut();

添加快捷方式

定义一个方法来添加快捷方式:

void addPinnedShortcut() {
  flutterPinnedShortcutPlugin.createPinnedShortcut(
    id: "1",
    label: "Followers",
    action: "followers",
    iconAssetName: "assets/icon.png"
  );
}

注意:iconAssetName 应该是您应用中的图标资源路径。

获取启动动作并导航到正确的屏幕

在应用启动时获取传入的动作,并根据动作导航到相应的屏幕:

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

void getIncomingAction() {
  flutterPinnedShortcutPlugin.getLaunchAction((action) {
    switch (action) {
      case "followers":
        // navigate to follower screen.
        break;
      case "profile":
        // navigate to profile screen.
        break;
    }
  });
}

完整示例 Demo

以下是一个完整的示例应用程序,展示如何使用 flutter_pinned_shortcut 插件:

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

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

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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final _flutterPinnedShortcutPlugin = FlutterPinnedShortcut();

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: ElevatedButton(
            onPressed: addPinnedShortcut,
            child: const Text("Add Pinned Shortcut"),
          ),
        ),
      ),
    );
  }

  void addPinnedShortcut() {
    _flutterPinnedShortcutPlugin.createPinnedShortcut(
      id: "1",
      label: "Followers",
      action: "followers",
      iconAssetName: "assets/icon.png" // 确保这个图标文件存在
    );
  }

  void getIncomingAction() {
    _flutterPinnedShortcutPlugin.getLaunchAction((action) {
      print(action);
      switch (action) {
        case "followers":
          // navigate to follower screen.
          break;
        case "profile":
          // navigate to profile screen.
          break;
      }
    });
  }
}

请确保您的项目中有适当的图标资源,并且已在 pubspec.yaml 中正确声明。这样,您就可以通过此插件轻松地为您的 Flutter 应用程序添加固定快捷方式。


更多关于Flutter固定快捷方式插件flutter_pinned_shortcut的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter固定快捷方式插件flutter_pinned_shortcut的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用flutter_pinned_shortcut插件来创建固定快捷方式的示例代码。这个插件允许你在Android设备的主屏幕上创建快捷方式。

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

dependencies:
  flutter:
    sdk: flutter
  flutter_pinned_shortcut: ^x.y.z  # 请使用最新版本号替换x.y.z

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

接下来,你需要在AndroidManifest.xml中声明必要的权限:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.yourapp">

    <uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
    <uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT" />

    <!-- 其他配置 -->

</manifest>

请注意,这些权限在某些设备上可能不是必需的,因为它们通常默认授予给应用程序。不过,为了代码的健壮性,最好还是声明它们。

现在,让我们在Dart代码中实现快捷方式的创建和删除。

  1. 导入必要的包
import 'package:flutter/material.dart';
import 'package:flutter_pinned_shortcut/flutter_pinned_shortcut.dart';
  1. 创建快捷方式
void createPinnedShortcut() async {
  try {
    await FlutterPinnedShortcut.pinShortcut(
      shortcutId: "my_shortcut_id", // 唯一标识符
      icon: "ic_launcher", // 图标资源名(放在res/drawable中)
      label: "My Shortcut", // 快捷方式的名称
      intentName: "open_shortcut", // 意图名称(用于在MainActivity中处理)
      dynamicLink: Uri.parse("https://example.com/open_shortcut"), // 可选的动态链接
    );
    print("Shortcut created successfully!");
  } catch (e) {
    print("Failed to create shortcut: $e");
  }
}

注意:icon属性需要使用Android资源名称,这意味着你需要在android/app/src/main/res/drawable目录下放置一个名为ic_launcher.png的图标文件。

  1. 删除快捷方式
void removePinnedShortcut() async {
  try {
    await FlutterPinnedShortcut.unpinShortcut(shortcutId: "my_shortcut_id");
    print("Shortcut removed successfully!");
  } catch (e) {
    print("Failed to remove shortcut: $e");
  }
}
  1. 在UI中调用这些方法
void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Pinned Shortcut Example'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              ElevatedButton(
                onPressed: createPinnedShortcut,
                child: Text('Create Shortcut'),
              ),
              ElevatedButton(
                onPressed: removePinnedShortcut,
                child: Text('Remove Shortcut'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
  1. 处理动态链接(可选)

如果你使用了动态链接,你需要在你的MainActivity中处理这个意图。在android/app/src/main/kotlin/.../MainActivity.kt中添加以下代码:

import android.content.Intent
import android.net.Uri
import io.flutter.embedding.android.FlutterActivity

class MainActivity: FlutterActivity() {
    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        handleIntent(intent)
    }

    private fun handleIntent(intent: Intent?) {
        intent?.action?.let { action ->
            if (action == Intent.ACTION_VIEW) {
                intent.data?.let { uri ->
                    if (uri.host == "example.com" && uri.path == "/open_shortcut") {
                        // 处理快捷方式打开的逻辑
                        println("Shortcut opened with URI: $uri")
                    }
                }
            }
        }
    }
}

这段代码将监听应用启动或恢复时的意图,并检查是否有匹配的动态链接。

这样,你就完成了在Flutter中使用flutter_pinned_shortcut插件来创建和删除固定快捷方式的全部步骤。

回到顶部