Flutter Siri建议集成插件flutter_siri_suggestions的使用

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

Flutter Siri建议集成插件flutter_siri_suggestions的使用

flutter_siri_suggestions

Flutter plugin for exposure on Siri Suggestions.

Pub Version License

Note: This plugin only works in iOS.

Image1 Image2 Image3

Getting Started

Add flutter_siri_suggestions as a dependency in your pubspec.yaml file. Check out the example directory for a sample app.

Usage

Import the library via

import 'package:flutter_siri_suggestions/flutter_siri_suggestions.dart';

Example :

await FlutterSiriSuggestions.instance.buildActivity(
  FlutterSiriActivity(
     "Open App 👨‍💻",
     "mainActivity",
     isEligibleForSearch: true,
     isEligibleForPrediction: true,
     contentDescription: "Did you enjoy that?",
     suggestedInvocationPhrase: "open my app"
  )
);

FlutterSiriSuggestions.instance.configure(
  onLaunch: (Map<String, dynamic> message) async {
      // Awaken from Siri Suggestion
      // message = {title: "Open App 👨‍💻", key: "mainActivity", userInfo: {}}
      // Do what you want :)

      print("called by ${message['key']} suggestion.");

      switch (message["key"]) {
        case "mainActivity":
          __text = "redirect to mainActivity";
          break;
        case "beerActivity":
          __text = "redirect to beerActivity";
          break;
        case "searchActivity":
          __text = "redirect to searchActivity";
          break;
        case "talkActivity":
          __text = "redirect to talkActivity";
          break;
        default:
          __text = "hmmmm...... made a typo";
      }

      setState(() {
        _text = __text;
      });


  }
);

Call buildActivity method if you want.


suggestedInvocationPhrase

suggestedInvocationPhrase, only available iOS 12+

suggestedInvocationPhrase

enjoy! 💃


Contributors

❤️

github
@aaqibism

示例代码

import 'package:flutter/material.dart';

import 'package:flutter_siri_suggestions/flutter_siri_suggestions.dart';

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

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

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _text = 'added mainActivity, beerActivity suggestions 🙋‍♂️';
  @override
  void initState() {
    super.initState();
    initSuggestions();
  }

  void initSuggestions() async {
    FlutterSiriSuggestions.instance.configure(
        onLaunch: (Map<String, dynamic> message) async {
      debugPrint('[FlutterSiriSuggestions] [onLaunch] $message');
      //Awaken from Siri Suggestion
      ///// TO DO : do something!
      String __text;

      debugPrint(
          "[FlutterSiriSuggestions] Called by ${message['key']} suggestion.");

      switch (message["key"]) {
        case "mainActivity":
          __text = "redirect to mainActivity";
          break;
        case "beerActivity":
          __text = "redirect to beerActivity";
          break;
        case "searchActivity":
          __text = "redirect to searchActivity";
          break;
        case "talkActivity":
          __text = "redirect to talkActivity";
          break;
        default:
          __text = "hmmmm...... made a typo";
      }

      setState(() {
        _text = __text;
      });
    });

    await FlutterSiriSuggestions.instance.registerActivity(
        const FlutterSiriActivity("mainActivity Suggestion", "mainActivity",
            isEligibleForSearch: true,
            isEligibleForPrediction: true,
            contentDescription: "Open mainActivity",
            suggestedInvocationPhrase: "open my app",
            userInfo: {"info": "sample"}));

    await FlutterSiriSuggestions.instance
        .registerActivity(const FlutterSiriActivity(
      "beerActivity Suggestion",
      "beerActivity",
      isEligibleForSearch: true,
      isEligibleForPrediction: true,
      contentDescription: "Open beerActivity 🍺",
      suggestedInvocationPhrase: "coooooool",
    ));
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Siri Suggestions Sample'),
        ),
        body: Builder(builder: (context) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Padding(
                  padding: const EdgeInsets.only(bottom: 50.0),
                  child: Center(
                    child: Text(_text),
                  ),
                ),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    TextButton(
                      child: const Text(
                        "add searchActivity Suggestion\n(key: searchActivity)",
                        style: TextStyle(fontSize: 12),
                      ),
                      onPressed: () async {
                        FlutterSiriSuggestionsResult result =
                            await FlutterSiriSuggestions.instance
                                .registerActivity(const FlutterSiriActivity(
                          "searchActivity Suggestion",
                          "searchActivity",
                          isEligibleForSearch: true,
                          isEligibleForPrediction: true,
                          contentDescription: "Open searchActivity 🧐",
                          suggestedInvocationPhrase: "Search",
                        ));

                        showSnackBar(
                            "${result.key} suggestion added.\n(key: ${result.key}, persistentIdentifier: ${result.persistentIdentifier})",
                            context: context);
                      },
                    ),
                    TextButton(
                      child: const Text(
                          "remove searchActivity Suggestion by key\n(key: searchActivity)",
                          style: TextStyle(fontSize: 12)),
                      onPressed: () async {
                        FlutterSiriSuggestions.instance
                            .deleteSavedUserActivitiesWithPersistentIdentifier(
                                "searchActivity");

                        showSnackBar("removed searchActivity suggestion.",
                            context: context);
                      },
                    ),
                    TextButton(
                      child: const Text(
                        "add talkActivity Suggestion\n(key: talkActivity, persistentIdentifier: customID)",
                        style: TextStyle(fontSize: 12),
                      ),
                      onPressed: () async {
                        FlutterSiriSuggestionsResult result =
                            await FlutterSiriSuggestions.instance
                                .registerActivity(const FlutterSiriActivity(
                                    "talkActivity Suggestion", "talkActivity",
                                    isEligibleForSearch: true,
                                    isEligibleForPrediction: true,
                                    contentDescription: "Open talkActivity 💩",
                                    suggestedInvocationPhrase: "Talk",
                                    persistentIdentifier: "customID",
                                    userInfo: {"value": "helloworld"}));

                        showSnackBar(
                            "${result.key} suggestion added.\n(key: ${result.key}, persistentIdentifier: ${result.persistentIdentifier})",
                            context: context);
                      },
                    ),
                    TextButton(
                      child: const Text(
                          "remove talkActivity Suggestion by PersistentIdentifier\n(persistentIdentifier: customID)",
                          style: TextStyle(fontSize: 12)),
                      onPressed: () async {
                        FlutterSiriSuggestions.instance
                            .deleteSavedUserActivitiesWithPersistentIdentifier(
                                "customID");

                        showSnackBar("removed searchActivity suggestion.",
                            context: context);
                      },
                    ),
                    TextButton(
                      child: const Text("remove all Suggestions",
                          style: TextStyle(fontSize: 12)),
                      onPressed: () async {
                        FlutterSiriSuggestions.instance
                            .deleteAllSavedUserActivities();

                        showSnackBar("removed all suggestion.",
                            context: context);
                      },
                    ),
                  ],
                )
              ],
            ),
          );
        }),
      ),
    );
  }

  void showSnackBar(String text, {required BuildContext context}) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(text, style: const TextStyle(fontSize: 12))),
    );
  }
}

更多关于Flutter Siri建议集成插件flutter_siri_suggestions的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter Siri建议集成插件flutter_siri_suggestions的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter应用中集成flutter_siri_suggestions插件的示例代码。这个插件允许你将Siri建议集成到你的应用中,从而提高用户体验。

首先,确保你已经在pubspec.yaml文件中添加了flutter_siri_suggestions依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_siri_suggestions: ^x.y.z  # 请替换为最新版本号

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

接下来,你可以在你的Flutter应用中按照以下步骤使用flutter_siri_suggestions插件。

1. 导入插件

在你的Dart文件中导入插件:

import 'package:flutter_siri_suggestions/flutter_siri_suggestions.dart';

2. 配置Siri建议

在应用的适当位置(例如,在初始化过程中),配置Siri建议。下面是一个示例,展示了如何设置Siri建议的短语和动作:

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

  // 设置Siri建议
  _configureSiriSuggestions();
}

void _configureSiriSuggestions() async {
  // 定义Siri建议的短语
  final List<String> shortcuts = [
    '查看新闻',
    '查看天气',
    '播放音乐',
  ];

  // 注册Siri建议
  await SiriSuggestions.setSuggestions(shortcuts);

  // 处理Siri触发的动作
  SiriSuggestions.onShortcutReceived.listen((String shortcut) {
    if (shortcut == '查看新闻') {
      // 打开新闻页面
      Navigator.pushNamed(context, '/news');
    } else if (shortcut == '查看天气') {
      // 打开天气页面
      Navigator.pushNamed(context, '/weather');
    } else if (shortcut == '播放音乐') {
      // 播放音乐
      // 假设你有一个播放音乐的方法
      playMusic();
    }
  });
}

void playMusic() {
  // 实现播放音乐的逻辑
  print('Playing music...');
}

注意:在上面的代码中,Navigator.pushNamed(context, '/news')Navigator.pushNamed(context, '/weather')假设你已经在应用中定义了相应的路由。你需要确保你的应用有一个路由系统来处理这些命名路由。

3. 在iOS上启用Siri建议

为了使Siri建议生效,你还需要在iOS项目中进行一些配置。

  1. 打开ios/Runner/Info.plist文件。
  2. 添加NSSiriUsageDescription键,并为其提供一个描述Siri用途的字符串值。例如:
<key>NSSiriUsageDescription</key>
<string>此应用使用Siri来提供快捷操作。</string>
  1. 确保你的iOS项目已经配置了适当的URL Scheme和Intent Handling(如果你的Siri建议需要与特定的Intent配合使用)。

4. 测试Siri建议

现在,你可以在你的设备上运行应用,并通过Siri触发这些建议。例如,你可以说“嘿Siri,查看新闻”来测试你的应用是否响应了正确的动作。

这个示例展示了如何使用flutter_siri_suggestions插件在Flutter应用中集成Siri建议。根据你的具体需求,你可能需要调整这些代码来适应你的应用逻辑和UI。

回到顶部