Flutter应用快捷方式管理插件flutter_app_shortcut的使用

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

Flutter应用快捷方式管理插件flutter_app_shortcut的使用

flutter_app_shortcut

一个用于实现Android原生应用快捷方式和iOS快速操作的插件。

开始使用

如何获取它?

访问插件官方页面 pub.dev 进行安装。

如何使用它?

查看 此文件 获取完整的使用示例。

示例

Android

添加一个新的快捷方式

FlutterAppShortcut().push(
    ShortcutArg(
        id: 'id_1',
        title: '主页',
        iconResourceName: 'ic_android_black',
        androidArg: AndroidArg(
            longLabel: '前往主页',
            uri: 'https://www.google.com',
        )
    );
)

添加一个新的图标

  1. 将图标资源添加到 android/app/src/main/res
  2. 设置 iconResourceName 为上一步中添加的图标的名称

iOS

FlutterAppShortcut().push(
    ShortcutArg(
        id: 'id_1',
        title: '主页',
        iconResourceName: 'register',
        iosArg: IosArg(subtitle: "我的副标题"),
    );
)

添加一个新的图标

  1. 使用Xcode添加图像集
  2. 设置 iconResourceName 为上一步中添加的图标的名称

参数

ShortcutArg

名称 类型 要求 描述
id String 唯一 当推送具有相同ID的快捷方式时,现有的快捷方式会被更新
title String 非空 应用快捷方式的标签(标题)
iconResourceName String 图标资源名称(参见以下说明)
androidArg AndroidArg Android快捷方式的额外参数
iosArg IosArg iOS快捷方式的额外参数

AndroidArg

名称 类型 要求 描述
longLabel String 如果设备有足够的空间,longLabel 会替换 title
uri String 点击快捷方式时的URI

IosArg

名称 类型 要求 描述
subtitle String 快捷方式的副标题

限制

Android

  • 已固定的快捷方式不能被删除,只能禁用
  • 禁用后的快捷方式不能启用,但已固定的快捷方式可以
  • 在调用 getShortcuts 时不能返回图标名称
  • 无法设置禁用消息(未来将实现)
  • 无法从Flutter侧设置图标(未来将实现)
  • 点击快捷方式时没有任何动作(未来将实现)

iOS

  • 在iOS上,无法启用或禁用快捷方式
  • 在调用 getShortcuts 时不能返回图标名称
  • 不支持禁用或启用图标
  • 无法从Flutter侧设置图标(未来将实现)
  • 点击快捷方式时没有任何动作(未来将实现)

TODO

Android

  • 允许为禁用的快捷方式添加禁用消息
  • 实现 getShortcuts
  • 允许从Flutter侧设置图标
  • 启用点击快捷方式的目标
  • 提供准确的错误信息

iOS

  • 允许设置副标题
  • 允许设置图标
  • 允许从Flutter侧设置图标
  • 启用点击快捷方式的目标
  • 提供准确的错误信息

Bug报告、想法和反馈

对于bug请使用 GitHub Issues。对于问题、想法和讨论,请使用 GitHub Discussions

许可证

版权所有 2021 Flutter App Shortcuts 项目作者

根据Apache许可证2.0版(“许可证”)授权;
除非遵守许可证,否则不允许使用此文件。
您可以获得许可证的副本:

http://www.apache.org/licenses/LICENSE-2.0

除非适用法律允许或以书面形式同意,否则根据许可证分发的软件是在“按原样”基础上分发的,
不附带任何形式的明示或暗示保证。
有关许可证具体语言的权限和限制,请参阅许可证。

完整示例代码

import 'dart:io';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_app_shortcut/flutter_app_shortcut.dart';
import 'package:flutter_app_shortcut/short_cut_arg.dart';

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

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

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  List<ShortcutArg> _shortcuts = [];
  FlutterAppShortcut flutterAppShortcut = FlutterAppShortcut();

  final _chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890';
  final Random _rnd = Random();

  String getRandomString(int length) => String.fromCharCodes(Iterable.generate(
      length, (_) => _chars.codeUnitAt(_rnd.nextInt(_chars.length))));

  [@override](/user/override)
  void initState() {
    super.initState();
    _removeShortcuts();
  }

  void _removeShortcuts() async {
    await flutterAppShortcut.removeAll();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('应用快捷方式插件示例应用'),
        ),
        body: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            _getAllBtn(),
            _setBtn(),
            _pushBtn(),
            _removeBtn(),
            _removeAllBtn(),
            _enableBtn(),
            _disableBtn(),
            Expanded(
              child: ListView.builder(
                itemCount: _shortcuts.length,
                itemBuilder: (context, i) {
                  final item = _shortcuts[i];
                  return Container(
                    margin: const EdgeInsets.symmetric(vertical: 4, horizontal: 16),
                    padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
                    child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(item.toString()),
                        ]),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  ShortcutArg _randomShortcut() => ShortcutArg(
      id: getRandomString(5),
      title: getRandomString(10),
      iconResourceName: 'ic_android_black',
      androidArg: AndroidArg(
          uri: 'https://www.google.com', longLabel: "非常长的标签"),
      iosArg: IosArg(subtitle: '我的副标题'));

  Widget _getAllBtn() {
    return Builder(builder: (context) {
      return TextButton(
          onPressed: () async {
            final result = await flutterAppShortcut.getAll();
            var text = "";

            for (var element in result) {
              text += "id=" + element.id + "|";
            }
            ScaffoldMessenger.of(context)
                .showSnackBar(SnackBar(content: Text(text)));
          },
          child: const Text('获取当前快捷方式'));
    });
  }

  Widget _setBtn() {
    return TextButton(
        onPressed: () async {
          final newShortcuts = [
            _randomShortcut(),
            _randomShortcut(),
          ];
          await flutterAppShortcut.set(newShortcuts);
          setState(() {
            _shortcuts = newShortcuts;
          });
        },
        child: const Text('设置随机快捷方式'));
  }

  Widget _pushBtn() {
    return TextButton(
        onPressed: () async {
          final shortcut = _randomShortcut();
          await flutterAppShortcut.push(shortcut);
          setState(() {
            _shortcuts.add(shortcut);
          });
        },
        child: const Text('推送一个快捷方式'));
  }

  Widget _removeBtn() {
    return TextButton(
        onPressed: () async {
          if (_shortcuts.isNotEmpty) {
            await flutterAppShortcut.removeById(_shortcuts.first.id);
            setState(() {
              _shortcuts.removeAt(0);
            });
          }
        },
        child: const Text('移除一个快捷方式'));
  }

  Widget _removeAllBtn() {
    return TextButton(
        onPressed: () async {
          await flutterAppShortcut.removeAll();
          setState(() {
            _shortcuts.clear();
          });
        },
        child: const Text('移除所有快捷方式'));
  }

  Widget _enableBtn() {
    return Builder(
      builder: (ctx) => TextButton(
          onPressed: () async {
            if (_isIos(ctx)) {
              return;
            }
            await flutterAppShortcut
                .enableShortcuts(_shortcuts.map((e) => e.id).toList());
            setState(() {
              _shortcuts = _shortcuts
                  .map((e) => e.copyWith(
                      androidArg: e.androidArg?.copyWith(enabled: true)))
                  .toList();
            });
          },
          child: const Text('启用快捷方式')),
    );
  }

  bool _isIos(BuildContext context) {
    if (Platform.isIOS) {
      ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('功能在iOS上不可用')));
      return true;
    }

    return false;
  }

  Widget _disableBtn() {
    return Builder(
      builder: (ctx) => TextButton(
          onPressed: () async {
            if (_isIos(ctx)) {
              return;
            }
            await flutterAppShortcut
                .disableShortcuts(_shortcuts.map((e) => e.id).toList());
            setState(() {
              _shortcuts = _shortcuts
                  .map((e) => e.copyWith(
                      androidArg: e.androidArg?.copyWith(enabled: false)))
                  .toList();
            });
          },
          child: const Text('禁用快捷方式')),
    );
  }
}

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

1 回复

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


当然,下面是一个关于如何在Flutter应用中使用flutter_app_shortcut插件来管理应用快捷方式的代码案例。这个插件允许你为你的Flutter应用添加和管理动态和静态快捷方式。

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

dependencies:
  flutter:
    sdk: flutter
  flutter_app_shortcut: ^0.4.0  # 请确保使用最新版本

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

接下来,你需要进行一些平台特定的设置。

Android 设置

android/app/src/main/AndroidManifest.xml中,添加以下权限(如果需要的话)和<activity>标签内的配置:

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

    <application
        ... >
        <activity
            ... >
            <!-- 添加以下meta-data标签 -->
            <meta-data
                android:name="io.flutter.embedding.android.NormalTheme"
                android:resource="@style/NormalTheme" />
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            
            <!-- 添加快捷方式接收器 -->
            <receiver android:name="me.yohom.flutter_app_shortcut.FlutterAppShortcutReceiver"
                android:exported="true">
                <intent-filter>
                    <action android:name="com.android.launcher.action.INSTALL_SHORTCUT" />
                </intent-filter>
            </receiver>
        </activity>
    </application>
</manifest>

iOS 设置

对于iOS,通常不需要额外的设置,但确保你的Info.plist文件配置正确。

Flutter 代码实现

接下来,在你的Flutter代码中实现快捷方式的创建和管理。

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

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

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

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

class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    super.initState();
    // 注册快捷方式
    _registerAppShortcuts();
  }

  Future<void> _registerAppShortcuts() async {
    // 创建快捷方式项
    final List<ShortcutItem> shortcutItems = [
      ShortcutItem(
        type: 'action_one',
        localizedTitle: 'Action One',
        iconPath: 'assets/icons/ic_action_one.png', // 确保你有这个图标资源
      ),
      ShortcutItem(
        type: 'action_two',
        localizedTitle: 'Action Two',
        iconPath: 'assets/icons/ic_action_two.png', // 确保你有这个图标资源
      ),
    ];

    // 注册快捷方式
    await FlutterAppShortcut.registerMany(shortcutItems);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter App Shortcut Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Press and hold the app icon on your home screen to see shortcuts.',
            ),
          ],
        ),
      ),
    );
  }

  // 处理快捷方式点击事件
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    FlutterAppShortcut.activate().then((_) {
      FlutterAppShortcut.callback = (String shortcutType) {
        // 根据快捷方式的type处理不同的动作
        if (shortcutType == 'action_one') {
          // 处理 Action One
          ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Action One selected')));
        } else if (shortcutType == 'action_two') {
          // 处理 Action Two
          ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Action Two selected')));
        }
      };
    });
  }

  @override
  void dispose() {
    // 注销快捷方式回调
    FlutterAppShortcut.callback = null;
    super.dispose();
  }
}

确保你的assets/icons/目录下有相应的图标文件(ic_action_one.pngic_action_two.png)。

这个示例展示了如何注册两个快捷方式,并在用户点击快捷方式时显示一个SnackBar。你可以根据需要调整快捷方式的数量和动作。

回到顶部