Flutter推送通知插件onesignal_flutter的使用

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

Flutter推送通知插件onesignal_flutter的使用

介绍

OneSignal Logo

OneSignal 提供了免费的电子邮件、短信、推送通知和应用内消息服务。通过这个SDK,可以轻松地将您的Flutter iOS和/或Android应用程序与OneSignal集成。

安装

请参考 Setup Guide 获取详细的安装指南。

示例代码

以下是一个完整的示例代码,展示了如何在Flutter项目中使用onesignal_flutter插件。

import 'package:flutter/material.dart';
import 'dart:async';
import 'package:onesignal_flutter/onesignal_flutter.dart';

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

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

class _MyAppState extends State<MyApp> {
  String _debugLabelString = "";
  String? _emailAddress;
  String? _smsNumber;
  String? _externalUserId;
  String? _language;
  String? _liveActivityId;
  bool _enableConsentButton = false;

  // CHANGE THIS parameter to true if you want to test GDPR privacy consent
  bool _requireConsent = false;

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

  Future<void> initPlatformState() async {
    if (!mounted) return;

    OneSignal.Debug.setLogLevel(OSLogLevel.verbose);
    OneSignal.Debug.setAlertLevel(OSLogLevel.none);
    OneSignal.consentRequired(_requireConsent);

    // 替换为您的OneSignal App ID
    OneSignal.initialize("YOUR_ONESIGNAL_APP_ID");

    OneSignal.LiveActivities.setupDefault();

    OneSignal.Notifications.clearAll();

    OneSignal.User.pushSubscription.addObserver((state) {
      print(OneSignal.User.pushSubscription.optedIn);
      print(OneSignal.User.pushSubscription.id);
      print(OneSignal.User.pushSubscription.token);
      print(state.current.jsonRepresentation());
    });

    OneSignal.User.addObserver((state) {
      var userState = state.jsonRepresentation();
      print('OneSignal user changed: $userState');
    });

    OneSignal.Notifications.addPermissionObserver((state) {
      print("Has permission " + state.toString());
    });

    OneSignal.Notifications.addClickListener((event) {
      print('NOTIFICATION CLICK LISTENER CALLED WITH EVENT: $event');
      setState(() {
        _debugLabelString =
            "Clicked notification: \n${event.notification.jsonRepresentation().replaceAll("\\n", "\n")}";
      });
    });

    OneSignal.Notifications.addForegroundWillDisplayListener((event) {
      print(
          'NOTIFICATION WILL DISPLAY LISTENER CALLED WITH: ${event.notification.jsonRepresentation()}');

      event.preventDefault();

      event.notification.display();

      setState(() {
        _debugLabelString =
            "Notification received in foreground notification: \n${event.notification.jsonRepresentation().replaceAll("\\n", "\n")}";
      });
    });

    OneSignal.InAppMessages.addClickListener((event) {
      setState(() {
        _debugLabelString =
            "In App Message Clicked: \n${event.result.jsonRepresentation().replaceAll("\\n", "\n")}";
      });
    });

    OneSignal.InAppMessages.addWillDisplayListener((event) {
      print("ON WILL DISPLAY IN APP MESSAGE ${event.message.messageId}");
    });

    OneSignal.InAppMessages.addDidDisplayListener((event) {
      print("ON DID DISPLAY IN APP MESSAGE ${event.message.messageId}");
    });

    OneSignal.InAppMessages.addWillDismissListener((event) {
      print("ON WILL DISMISS IN APP MESSAGE ${event.message.messageId}");
    });

    OneSignal.InAppMessages.addDidDismissListener((event) {
      print("ON DID DISMISS IN APP MESSAGE ${event.message.messageId}");
    });

    setState(() {
      _enableConsentButton = _requireConsent;
    });

    oneSignalInAppMessagingTriggerExamples();
    oneSignalOutcomeExamples();

    OneSignal.InAppMessages.paused(true);
  }

  void _handleSendTags() {
    print("Sending tags");
    OneSignal.User.addTagWithKey("test2", "val2");

    print("Sending tags array");
    var sendTags = {'test': 'value', 'test2': 'value2'};
    OneSignal.User.addTags(sendTags);
  }

  void _handleRemoveTag() {
    print("Deleting tag");
    OneSignal.User.removeTag("test2");

    print("Deleting tags array");
    OneSignal.User.removeTags(['test']);
  }

  void _handleGetTags() async {
    print("Get tags");

    var tags = await OneSignal.User.getTags();
    print(tags);
  }

  void _handlePromptForPushPermission() {
    print("Prompting for Permission");
    OneSignal.Notifications.requestPermission(true);
  }

  void _handleSetLanguage() {
    if (_language == null) return;
    print("Setting language");
    OneSignal.User.setLanguage(_language!);
  }

  void _handleSetEmail() {
    if (_emailAddress == null) return;
    print("Setting email");

    OneSignal.User.addEmail(_emailAddress!);
  }

  void _handleRemoveEmail() {
    if (_emailAddress == null) return;
    print("Remove email");

    OneSignal.User.removeEmail(_emailAddress!);
  }

  void _handleSetSMSNumber() {
    if (_smsNumber == null) return;
    print("Setting SMS Number");

    OneSignal.User.addSms(_smsNumber!);
  }

  void _handleRemoveSMSNumber() {
    if (_smsNumber == null) return;
    print("Remove smsNumber");

    OneSignal.User.removeSms(_smsNumber!);
  }

  void _handleConsent() {
    print("Setting consent to true");
    OneSignal.consentGiven(true);

    print("Setting state");
    setState(() {
      _enableConsentButton = false;
    });
  }

  void _handleSetLocationShared() {
    print("Setting location shared to true");
    OneSignal.Location.setShared(true);
  }

  void _handleGetExternalId() async {
    var externalId = await OneSignal.User.getExternalId();
    print('External ID: $externalId');
  }

  void _handleLogin() {
    print("Setting external user ID");
    if (_externalUserId == null) return;
    OneSignal.login(_externalUserId!);
    OneSignal.User.addAlias("fb_id", "1341524");
  }

  void _handleLogout() {
    OneSignal.logout();
    OneSignal.User.removeAlias("fb_id");
  }

  void _handleGetOnesignalId() async {
    var onesignalId = await OneSignal.User.getOnesignalId();
    print('OneSignal ID: $onesignalId');
  }

  oneSignalInAppMessagingTriggerExamples() async {
    OneSignal.InAppMessages.addTrigger("trigger_1", "one");

    Map<String, String> triggers = new Map<String, String>();
    triggers["trigger_2"] = "two";
    triggers["trigger_3"] = "three";
    OneSignal.InAppMessages.addTriggers(triggers);

    OneSignal.InAppMessages.removeTrigger("trigger_2");

    List<String> keys = ["trigger_1", "trigger_3"];
    OneSignal.InAppMessages.removeTriggers(keys);

    OneSignal.InAppMessages.paused(true);
    var arePaused = await OneSignal.InAppMessages.arePaused();
    print('Notifications paused $arePaused');
  }

  oneSignalOutcomeExamples() async {
    OneSignal.Session.addOutcome("normal_1");
    OneSignal.Session.addUniqueOutcome("unique_1");
    OneSignal.Session.addOutcomeWithValue("value_1", 3.2);
  }

  void _handleOptIn() {
    OneSignal.User.pushSubscription.optIn();
  }

  void _handleOptOut() {
    OneSignal.User.pushSubscription.optOut();
  }

  void _handleStartDefaultLiveActivity() {
    if (_liveActivityId == null) return;
    print("Starting default live activity");
    OneSignal.LiveActivities.startDefault(_liveActivityId!, {
      "title": "Welcome!"
    }, {
      "message": {"en": "Hello World!"},
      "intValue": 3,
      "doubleValue": 3.14,
      "boolValue": true
    });
  }

  void _handleEnterLiveActivity() {
    if (_liveActivityId == null) return;
    print("Entering live activity");
    OneSignal.LiveActivities.enterLiveActivity(_liveActivityId!, "FAKE_TOKEN");
  }

  void _handleExitLiveActivity() {
    if (_liveActivityId == null) return;
    print("Exiting live activity");
    OneSignal.LiveActivities.exitLiveActivity(_liveActivityId!);
  }

  void _handleSetPushToStartLiveActivity() {
    if (_liveActivityId == null) return;
    print("Setting Push-To-Start live activity");
    OneSignal.LiveActivities.setPushToStartToken(_liveActivityId!, "FAKE_TOKEN");
  }

  void _handleRemovePushToStartLiveActivity() {
    if (_liveActivityId == null) return;
    print("Setting Push-To-Start live activity");
    OneSignal.LiveActivities.removePushToStartToken(_liveActivityId!);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('OneSignal Flutter Demo'),
          backgroundColor: Color.fromARGB(255, 212, 86, 83),
        ),
        body: Container(
          padding: EdgeInsets.all(10.0),
          child: SingleChildScrollView(
            child: Table(
              children: [
                TableRow(children: [
                  OneSignalButton("Send Tags", _handleSendTags, !_enableConsentButton)
                ]),
                TableRow(children: [
                  OneSignalButton("Get Tags", _handleGetTags, !_enableConsentButton)
                ]),
                TableRow(children: [
                  OneSignalButton("Prompt for Push Permission", _handlePromptForPushPermission, !_enableConsentButton)
                ]),
                TableRow(children: [
                  TextField(
                    textAlign: TextAlign.center,
                    decoration: InputDecoration(
                        hintText: "Email Address",
                        labelStyle: TextStyle(color: Color.fromARGB(255, 212, 86, 83))),
                    onChanged: (text) {
                      setState(() {
                        _emailAddress = text == "" ? null : text;
                      });
                    },
                  )
                ]),
                TableRow(children: [
                  OneSignalButton("Set Email", _handleSetEmail, !_enableConsentButton)
                ]),
                TableRow(children: [
                  OneSignalButton("Logout Email", _handleRemoveEmail, !_enableConsentButton)
                ]),
                TableRow(children: [
                  TextField(
                    textAlign: TextAlign.center,
                    decoration: InputDecoration(
                        hintText: "SMS Number",
                        labelStyle: TextStyle(color: Color.fromARGB(255, 212, 86, 83))),
                    onChanged: (text) {
                      setState(() {
                        _smsNumber = text == "" ? null : text;
                      });
                    },
                  )
                ]),
                TableRow(children: [
                  OneSignalButton("Set SMS Number", _handleSetSMSNumber, !_enableConsentButton)
                ]),
                TableRow(children: [
                  OneSignalButton("Remove SMS Number", _handleRemoveSMSNumber, !_enableConsentButton)
                ]),
                TableRow(children: [
                  OneSignalButton("Provide GDPR Consent", _handleConsent, _enableConsentButton)
                ]),
                TableRow(children: [
                  OneSignalButton("Set Location Shared", _handleSetLocationShared, !_enableConsentButton)
                ]),
                TableRow(children: [
                  OneSignalButton("Remove Tag", _handleRemoveTag, !_enableConsentButton)
                ]),
                TableRow(children: [
                  TextField(
                    textAlign: TextAlign.center,
                    decoration: InputDecoration(
                        hintText: "External User ID",
                        labelStyle: TextStyle(color: Color.fromARGB(255, 212, 86, 83))),
                    onChanged: (text) {
                      setState(() {
                        _externalUserId = text == "" ? null : text;
                      });
                    },
                  )
                ]),
                TableRow(children: [
                  OneSignalButton("Get External User ID", _handleGetExternalId, !_enableConsentButton)
                ]),
                TableRow(children: [
                  OneSignalButton("Set External User ID", _handleLogin, !_enableConsentButton)
                ]),
                TableRow(children: [
                  OneSignalButton("Remove External User ID", _handleLogout, !_enableConsentButton)
                ]),
                TableRow(children: [
                  OneSignalButton("Get OneSignal ID", _handleGetOnesignalId, !_enableConsentButton)
                ]),
                TableRow(children: [
                  TextField(
                    textAlign: TextAlign.center,
                    decoration: InputDecoration(
                        hintText: "Language",
                        labelStyle: TextStyle(color: Color.fromARGB(255, 212, 86, 83))),
                    onChanged: (text) {
                      setState(() {
                        _language = text == "" ? null : text;
                      });
                    },
                  )
                ]),
                TableRow(children: [
                  OneSignalButton("Set Language", _handleSetLanguage, !_enableConsentButton)
                ]),
                TableRow(children: [
                  Container(child: Text(_debugLabelString), alignment: Alignment.center,)
                ]),
                TableRow(children: [
                  OneSignalButton("Opt In", _handleOptIn, !_enableConsentButton)
                ]),
                TableRow(children: [
                  OneSignalButton("Opt Out", _handleOptOut, !_enableConsentButton)
                ]),
                TableRow(children: [
                  TextField(
                    textAlign: TextAlign.center,
                    decoration: InputDecoration(
                        hintText: "Live Activity ID",
                        labelStyle: TextStyle(color: Color.fromARGB(255, 212, 86, 83))),
                    onChanged: (text) {
                      setState(() {
                        _liveActivityId = text == "" ? null : text;
                      });
                    },
                  )
                ]),
                TableRow(children: [
                  OneSignalButton("Start Default Live Activity", _handleStartDefaultLiveActivity, !_enableConsentButton)
                ]),
                TableRow(children: [
                  OneSignalButton("Enter Live Activity", _handleEnterLiveActivity, !_enableConsentButton)
                ]),
                TableRow(children: [
                  OneSignalButton("Exit Live Activity", _handleExitLiveActivity, !_enableConsentButton)
                ]),
                TableRow(children: [
                  OneSignalButton("Set Push-To-Start Live Activity", _handleSetPushToStartLiveActivity, !_enableConsentButton)
                ]),
                TableRow(children: [
                  OneSignalButton("Remove Push-To-Start Live Activity", _handleRemovePushToStartLiveActivity, !_enableConsentButton)
                ]),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

typedef void OnButtonPressed();

class OneSignalButton extends StatefulWidget {
  final String title;
  final OnButtonPressed onPressed;
  final bool enabled;

  OneSignalButton(this.title, this.onPressed, this.enabled);

  State<StatefulWidget> createState() => OneSignalButtonState();
}

class OneSignalButtonState extends State<OneSignalButton> {
  @override
  Widget build(BuildContext context) {
    return Table(
      children: [
        TableRow(children: [
          TextButton(
            style: TextButton.styleFrom(
              foregroundColor: Colors.white,
              disabledForegroundColor: Colors.white,
              backgroundColor: Color.fromARGB(255, 212, 86, 83),
              disabledBackgroundColor: Color.fromARGB(180, 212, 86, 83),
              padding: EdgeInsets.all(8.0),
            ),
            child: Text(widget.title),
            onPressed: widget.enabled ? widget.onPressed : null,
          )
        ]),
        TableRow(children: [
          Container(height: 8.0,)
        ]),
      ],
    );
  }
}

注意事项

  1. 替换App ID:请确保将 YOUR_ONESIGNAL_APP_ID 替换为您自己的OneSignal App ID。
  2. GDPR同意:如果您需要测试GDPR隐私同意,请将 _requireConsent 设置为 true
  3. 权限请求:确保在适当的时间点请求用户的通知权限。

希望这些信息对您有帮助!如果有任何问题,请随时联系OneSignal支持团队 support@onesignal.com 或访问 GitHub issue tracker 进行反馈。


更多关于Flutter推送通知插件onesignal_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter推送通知插件onesignal_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter项目中使用onesignal_flutter插件来实现推送通知的示例代码。这段代码涵盖了基本的安装、配置和实现通知接收的过程。

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  onesignal_flutter: ^3.2.7  # 请确保使用最新版本

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

2. 配置OneSignal

iOS配置

  1. CocoaPods: 打开ios/Podfile并确保在target下添加了platform :ios, '10.0'(或更高版本)。

  2. AppDelegate: 打开ios/Runner/AppDelegate.swift(如果是Objective-C项目则是AppDelegate.m),并添加以下代码:

import UIKit
import Flutter
import OneSignal

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GeneratedPluginRegistrant.register(with: self)
    
    // OneSignal Initialization
    OneSignal.initWith(
      launchOptions: launchOptions,
      appId: "YOUR_ONESIGNAL_APP_ID",
      handleNotificationAction: nil,
      settings: [kOSSettingsKeyAutoPrompt: false]
    )
    
    OneSignal.promptForPushNotifications(userResponse: { accepted in
      print("User accepted notifications: \(accepted)")
    })
    
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

确保将YOUR_ONESIGNAL_APP_ID替换为你的OneSignal应用ID。

Android配置

  1. Manifest文件: 打开android/app/src/main/AndroidManifest.xml并添加以下权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.VIBRATE" />
  1. Gradle文件: 确保在android/app/build.gradle文件中应用了Google服务插件:
dependencies {
    classpath 'com.google.gms:google-services:4.3.10'  // 请确保使用最新版本
}

并在android/app/build.gradleapp级别配置中添加:

apply plugin: 'com.google.gms.google-services'
  1. OneSignal配置: 在android/app/src/main/kotlin/com/example/yourappname/MainActivity.kt(或Java文件)中添加初始化代码(如果该文件不存在,Flutter通常会自动处理,但你可以手动添加):
package com.example.yourappname

import io.flutter.embedding.android.FlutterActivity
import com.onesignal.OneSignal

class MainActivity: FlutterActivity() {
    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        OneSignal.initWith(
            applicationContext,
            "YOUR_ONESIGNAL_APP_ID",
            OneSignal.InitOptions.Builder()
                .setInFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification)
                .build()
        )
    }
}

同样,替换YOUR_ONESIGNAL_APP_ID

3. 在Flutter中使用OneSignal

在你的Dart代码中,你可以这样使用OneSignal:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('OneSignal Flutter Demo'),
        ),
        body: Center(
          child: MyHomePage(),
        ),
      ),
    );
  }
}

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

class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    super.initState();
    // Initialize OneSignal
    OneSignal.shared.init("YOUR_ONESIGNAL_APP_ID");

    // Subscribe to notification events
    OneSignal.shared.setSubscription(true);

    OneSignal.shared.setInFocusDisplayType(OSNotificationDisplayType.notification);

    // Listen for incoming notifications
    OneSignal.shared.onNotificationOpened.listen((OSNotificationOpenedResult result) {
      print("Notification opened: ${result.notification.payload.body}");
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Text('Waiting for notifications...'),
        ElevatedButton(
          onPressed: () {
            // Send a test notification (usually done from OneSignal dashboard)
            // This is just an example of how you might trigger something
          },
          child: Text('Send Test Notification'),
        ),
      ],
    );
  }
}

确保替换YOUR_ONESIGNAL_APP_ID

4. 运行应用

现在,你可以运行你的Flutter应用,并应该能够接收到来自OneSignal的推送通知。

这个示例展示了基本的OneSignal集成,包括初始化、配置和监听通知打开事件。你可以根据需要进一步自定义和扩展这些功能。

回到顶部