Flutter开发 使用FCM实现前后台的推送

前言:

     目前Flutter的FCM推送只支持Android,需要google service支持。下面我简单总结一下在Flutter中如何实现FCM前后台推送,主要包括“通知消息”的推送和“底部导航的未读消息”推送。

实现的代码:

1.Google官网注册应用

   首先去网址:https://console.firebase.google.com/ 去注册自己的应用,并下载google-services.json的文件,把它放到自己项目的app/目录。

2.添加依赖

  2.1 Project的build.gradle

 classpath 'com.google.gms:google-services:4.0.1' 

  2.2  Module的build.gradle

dependencies {
     implementation 'com.google.firebase:firebase-core:16.0.1'
}
apply plugin: 'com.google.gms.google-services'    //这一句一定要放在最下面,否则无效

3.配置AndroidMenifest.xml文件

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="项目包名">
   
    <uses-permission android:name="android.permission.INTERNET"/>

    <application>
        <activity> 
            <intent-filter>
                <action android:name="FLUTTER_NOTIFICATION_CLICK" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>
</manifest>

 

4.在pubspec.yaml添加sdk

dependencies:
  ...
  cupertino_icons: ^0.1.0
  firebase_messaging: ^4.0.0+1

5.导包

import 'package:firebase_messaging/firebase_messaging.dart';

6.通知消息的推送

class DashboardPageState extends State<DashboardPage>{
  final FirebaseMessaging _fireBaseMessaging = FirebaseMessaging();

  ...

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

    //push notification
    _fireBaseMessaging.requestNotificationPermissions(
        const IosNotificationSettings(sound: true, badge: true, alert: true));
    _fireBaseMessaging.getToken().then((token) {
//      print(token);
      if (token != null) {
        _postFcm(token);//推送的post请求
      }
    });
   
  }

  //推送的post请求
  Future _postFcm(String token) async {
      String url = url;
      var data = {"token": token};
      DioUtil.post(url, data: data).then((response) {       
    });
  }

}

7.底部导航的未读消息推送

class DashboardPageState extends State<DashboardPage>{
  final FirebaseMessaging _fireBaseMessaging = FirebaseMessaging();
  int _tabIndex = 0;
  bool clickBadge = false;
  var count=""; //初始化未读条数
  List<BottomNavigationBarItem> items;
  
  //自定义badger的样式
  BottomNavigationBadge badger = new BottomNavigationBadge(
      backgroundColor: Colors.red,
      badgeShape: BottomNavigationBadgeShape.circle,
      textColor: Colors.white,
      position: BottomNavigationBadgePosition.topRight,
      textSize: 8);

    @override
  void initState() {
    super.initState();
    _fireBaseMessaging.configure(onMessage: (Map message) {
      handleMessage(message);
    }, onLaunch: (Map message) {
      handleMessage(message);
    }, onResume: (Map message) {
      handleMessage(message);
    });
  }

  void handleMessage(Map message) {
    setState(() {
      var data = message["data"];
      count = data["count"]; //获取未读条数
    });
  }

  void _change(int index) {
    setState(() {
      _tabIndex = index;
       if (index == 1) {
         if(count.length!=0){
           items = badger.removeBadge(items,index);//点击相应的底部导航,移除badge
           clickBadge=true;
        }
      }
    });
  }

   @override
  Widget build(BuildContext context) {
    initData();
    return Scaffold(
        appBar: buildAppBar(),
        body: buildTabContent(),
        bottomNavigationBar: CupertinoTabBar(
          backgroundColor: Color(0xFF384F6F),
          currentIndex: _tabIndex,
          onTap: _change,
          items: items,
        ));
  }

  void initData() {
    //给底部导航的item添加图标和文字
    items = [
      BottomNavigationBarItem(icon: getTabIcon(0), title: getTabTitle(0)),
      BottomNavigationBarItem(icon: getTabIcon(1), title: getTabTitle(1)),
      BottomNavigationBarItem(icon: getTabIcon(2), title: getTabTitle(2)),
      BottomNavigationBarItem(icon: getTabIcon(3), title: getTabTitle(3))
    ];

    setState(() {
      if (clickBadge == false && count.length!=0) {//根据条件,动态添加badge
        badger.setBadge(items, count, 1);
      }
    });
  }

}

8.总结:

在Flutter上已经实现FCM前后台的推送功能啦,欢迎大家围观。如果有什么疑问的话,可以留言联系我哦!

转载于:https://my.oschina.net/wupeilin/blog/3034842

Flutter 实现后台消息推送通常涉及到使用第三方服务,如Firebase Cloud Messaging (FCM)、OneSignal、Apns(针对iOS)和Gcm(针对Android)。以下是使用Firebase Cloud Messaging(FCM)进行后台推送的基本步骤: 1. **设置 Firebase**: - 注册 Flutter 项目为 Firebase 应用,并下载配置文件。 - 配置 AndroidManifest.xml 和 info.plist 文件,添加必要的权限。 2. **安装 Firebase SDK**: - 在 Flutter 项目中添加 `firebase_messaging` 插件。 ```dart dependencies { ... implementation 'com.google.firebase:firebase-messaging:23.0.1' ... } ``` 3. **初始化 Firebase**: - 在 `main.dart` 中初始化 FirebaseMessaging 类并注册设备。 ```dart void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); FirebaseMessaging.onBackgroundMessage(_onBackgroundMessage); runApp(MyApp()); } Future<void> _onBackgroundMessage(RemoteMessage message) async { // 处理后台接收到的消息 } ``` 4. **监听消息**: - 在 `FirebaseMessaging` 中监听消息到达和点击事件。 ```dart FirebaseMessaging.onMessage.listen((RemoteMessage message) { // 处理台接收到的消息 }); FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage openedMessage) { // 当应用因用户点击消息而打开时的回调 }); ``` 5. **设置推送通知**: - 如果需要,设置通知的显示样式和行为。 6. **发送推送**: - 使用 Firebase 控制台或 API 发送推送消息,指定接收者。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值