You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flutter应用中通过Microsoft Azure Notification Hub实现推送通知?

在Flutter中使用Azure Notification Hub实现推送通知

是的,完全可以在Flutter应用中集成Azure Notification Hub实现推送通知。以下是完整落地流程,同时会修复你代码中的关键问题:

一、Azure端配置

  • 创建Azure Notification Hub实例:在Azure门户中新建Notification Hub,完成基础配置。
  • 配置推送服务凭证:
    • Android:在Hub的「Google (GCM/FCM)」选项卡中,填入Firebase项目的服务器密钥。
    • iOS:在「Apple (APNS)」选项卡中,上传APNS证书或使用Token认证方式,配置对应环境(开发/生产)。

二、Flutter项目依赖

在pubspec.yaml中添加必要依赖:

dependencies:
  flutter:
    sdk: flutter
  azure_notify_hub: ^latest_version # 替换为pub.dev上的最新版本
  firebase_core: ^latest_version
  firebase_messaging: ^latest_version # 用于获取FCM令牌

三、平台特定配置

Android端

  1. 在android/app/src/main/AndroidManifest.xml中添加权限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
  1. 在android/build.gradle的buildscript节点中添加Google服务依赖:
buildscript {
    dependencies {
        classpath 'com.google.gms:google-services:4.3.15'
    }
}
  1. 在android/app/build.gradle末尾添加插件引用:
apply plugin: 'com.google.gms.google-services'

iOS端

  1. 在ios/Runner/Info.plist中添加推送相关配置:
<key>UIBackgroundModes</key>
<array>
    <string>remote-notification</string>
</array>
<key>NSNotificationSettingsUsageDescription</key>
<string>需要推送通知权限来接收消息</string>
  1. 在Xcode中开启推送功能:打开项目 → 「Signing & Capabilities」 → 添加「Push Notifications」和「Background Modes」(勾选Remote notifications)。

四、代码实现(修复你的现有代码)

你的代码核心问题是_anh变量未初始化,导致configure方法从未执行。以下是修正后的完整代码:

import 'package:azure_notify_hub/azure_notify_hub.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

import 'firebase_options.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Azure推送示例',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyAppAzure(),
    );
  }
}

class MyAppAzure extends StatefulWidget {
  const MyAppAzure({super.key});

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

class _MyAppAzureState extends State<MyAppAzure> {
  late AzureNotificationhubsFlutter _anh;
  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;

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

  Future<void> _initAzureNotificationHub() async {
    // 初始化Azure Notification Hub实例
    _anh = AzureNotificationhubsFlutter();

    // 请求推送权限(iOS必须,Android可选)
    NotificationSettings settings = await _firebaseMessaging.requestPermission(
      alert: true,
      badge: true,
      sound: true,
    );

    if (settings.authorizationStatus == AuthorizationStatus.authorized) {
      // 获取FCM令牌
      String? fcmToken = await _firebaseMessaging.getToken();
      if (fcmToken != null && kDebugMode) {
        print("FCM Token: $fcmToken");
      }

      // 配置Azure Notification Hub
      await _anh.configure(
        hubName: "你的Azure Notification Hub名称",
        listenConnectionString: "你的Hub监听连接字符串",
        onMessage: (Map<String, dynamic> message) async {
          if (kDebugMode) {
            print("前台收到通知: $message");
          }
          _showNotificationDialog(message);
        },
        onResume: (Map<String, dynamic> message) async {
          if (kDebugMode) {
            print("后台恢复时收到通知: $message");
          }
          _showNotificationDialog(message);
        },
        onLaunch: (Map<String, dynamic> message) async {
          if (kDebugMode) {
            print("启动时收到通知: $message");
          }
          _showNotificationDialog(message);
        },
        onToken: (String token) async {
          if (kDebugMode) {
            print("Azure注册令牌: $token");
          }
        },
      );

      // 将FCM令牌注册到Azure Notification Hub
      if (fcmToken != null) {
        await _anh.registerDevice(fcmToken);
        // 可选:添加标签实现定向推送
        // await _anh.registerDeviceWithTags(fcmToken, ["user_123", "news"]);
      }
    }
  }

  void _showNotificationDialog(Map<String, dynamic> message) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        content: ListTile(
          title: Text(message['notification']['title'] ?? "通知"),
          subtitle: Text(message['notification']['body'] ?? ""),
        ),
        actions: <Widget>[
          TextButton(
            child: const Text('确定'),
            onPressed: () => Navigator.of(context).pop(),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Azure推送示例'),
      ),
      body: const Center(
        child: Text('运行中...'),
      ),
    );
  }
}

五、关键修复点说明

  1. 初始化Azure Hub实例:必须先实例化AzureNotificationhubsFlutter()才能调用configure方法,原代码中_anh为null导致配置未执行。
  2. 添加令牌注册逻辑:需要将Firebase获取的FCM令牌注册到Azure Hub,否则Azure无法定位到设备推送消息。
  3. 完善权限请求:iOS必须显式请求推送权限,否则无法接收通知。
  4. 填充Hub参数:需替换代码中的hubName和listenConnectionString为你自己Azure Hub的信息(在Azure门户「访问策略」中获取)。

六、测试推送通知

可通过Azure门户的「测试发送」功能验证:选择目标平台,输入测试消息内容,点击发送即可查看设备接收情况。

内容的提问来源于stack exchange,提问作者Huzaifa Zameer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 11:22:04