Flutter推送通知插件push_fire_notifications的使用

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

Flutter推送通知插件push_fire_notifications的使用

推送通知是一个处理通知的包。您可以将其与Firebase一起使用。它有助于提高代码可读性,并减少实现推送通知所需的时间。

特点

  • 只有一个小部件可以实现推送通知。

开始使用

开始使用该包。

首先,将Firebase集成到您的Flutter项目中

然后,在所有Firebase设置完成后导入此包

将MaterialApp包装在PushFireNotification小部件中

使用这些函数:onNotification、onTapNotification、onTapAppTerminatedNotification

就这样,您已经实现了推送通知!

使用代码片段

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase?.initializeApp(); // 初始化Firebase应用
  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> {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return PushFireNotifications(
      fcmTokenGet: (String token) {
          // 这里可以在应用程序启动时获取FCM令牌。
      },
      onNotification: (String payload) {

        // 每当发生通知时,此函数会被触发
        // 获取payload中的数据
      
      },
      onTapNotification: (String payload) {

        // 当应用程序处于运行模式时,此函数用于处理点击通知的操作
        
      },
      onTapAppTerminatedNotification: (String payload) {
         // 当应用程序处于终止模式时,此函数用于处理点击通知的操作
      },
      child: MaterialApp(
        title: 'Flutter',
        debugShowCheckedModeBanner: true,
        home: Home() // 设置主页为Home小部件
      ),
    );
  }
}

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

1 回复

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


当然,下面是一个关于如何在Flutter项目中使用push_fire_notifications插件来实现推送通知的代码示例。请注意,push_fire_notifications插件的具体实现和使用方式可能会随着版本的更新而有所变化,因此确保你查阅的是最新版本的文档。以下代码是一个基本的实现示例:

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  push_fire_notifications: ^最新版本号  # 请替换为最新版本号

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

2. 配置Firebase

在Firebase控制台中为你的应用创建一个项目,并下载google-services.json(对于Android)和GoogleService-Info.plist(对于iOS)文件,将它们分别放置在android/app/ios/Runner/目录下。

3. 初始化插件

在你的main.dart文件中初始化push_fire_notifications插件:

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

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

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

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

class _MyHomePageState extends State<MyHomePage> {
  final PushFireNotifications _pushFireNotifications = PushFireNotifications();

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

  Future<void> _initializePushNotifications() async {
    // Initialize Firebase
    await Firebase.initializeApp();

    // Configure Push Notifications
    _pushFireNotifications.initialize(
      onInit: (data) {
        print("Push Notifications Initialized: $data");
      },
      onMessage: (RemoteMessage message) {
        // Handle incoming message
        print("Received message: ${message.data}");
      },
    );

    // Request notification permissions
    await _pushFireNotifications.requestNotificationPermissions(
      android: AndroidNotificationSettings(
        channelId: 'high_importance_channel',
        channelName: 'High Importance Notifications',
        channelDescription: 'This channel is used for important notifications.',
        importance: Importance.high,
        playSound: true,
      ),
      ios: IOSNotificationSettings(
        requestAlertPermission: true,
        requestBadgePermission: true,
        requestSoundPermission: true,
      ),
    );

    // Subscribe to a topic (optional)
    await _pushFireNotifications.subscribeToTopic('your_topic_name');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Push Notifications'),
      ),
      body: Center(
        child: Text('Waiting for notifications...'),
      ),
    );
  }
}

4. Android配置

android/app/src/main/AndroidManifest.xml文件中确保你有以下权限和服务声明:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/>

<application
    ...>
    <!-- Add the following line inside the application tag -->
    <service
        android:name=".MyFirebaseMessagingService"
        android:exported="true">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>

    <!-- Add your default notification channel (required for Android Oreo and above) -->
    <meta-data
        android:name="com.google.firebase.messaging.default_notification_channel_id"
        android:value="high_importance_channel" />
</application>

注意:MyFirebaseMessagingService通常是由Firebase SDK自动处理的,但如果你需要自定义处理,可以创建这个服务类并扩展FirebaseMessagingService

5. iOS配置

ios/Runner/Info.plist文件中添加以下配置:

<key>FirebaseAppDelegateProxyEnabled</key>
<false/>
<key>UIBackgroundModes</key>
<array>
    <string>remote-notification</string>
</array>

并确保GoogleService-Info.plist文件已经正确放置在ios/Runner/目录下。

总结

以上代码展示了如何在Flutter项目中集成和使用push_fire_notifications插件来处理推送通知。请根据你的具体需求调整代码,并查阅最新的官方文档以获取更多信息和最佳实践。

回到顶部