Flutter 通知 Notification
封面图
•
2025-10-01
•
Flutter
0
0
0
0
在 Flutter 中,**通知(Notification)** 通常指的是系统级别的通知(如 Android 的 `Notification` 或 iOS 的 `UNUserNotificationCenter`),用于在应用不在前台时向用户发送消息。此外,Flutter 还提供了一种 **“本地事件通知”** 机制,用于在应用内部传递信息(例如状态变化、数据更新等)。 --- ## 一、Flutter 应用内通知(Event Notification) 这是 Flutter 框架本身提供的通知机制,常用于组件之间的通信,而不是系统通知。 ### 1. 使用 `Stream` 和 `StreamController` ```dart import 'dart:collection'; void main() { final streamController = StreamController<String>(); // 监听通知 streamController.stream.listen((data) { print("收到通知: $data"); }); // 发送通知 streamController.sink.add("Hello, this is a notification!"); } ``` ### 2. 使用 `Provider` + `ChangeNotifier` 如果你使用了 `Provider` 包,可以结合 `ChangeNotifier` 实现更高级的通知机制: ```dart import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; class MyNotifier with ChangeNotifier { String _message = "Initial message"; String get message => _message; void updateMessage(String newMessage) { _message = newMessage; notifyListeners(); } } void main() { runApp( ChangeNotifierProvider( create: (_) => MyNotifier(), child: MyApp(), ), ); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: Text("Notification Example")), body: Center( child: Consumer<MyNotifier>( builder: (context, notifier, _) { return Text(notifier.message); }, ), ), floatingActionButton: FloatingActionButton( onPressed: () { Provider.of<MyNotifier>(context, listen: false).updateMessage("New Message!"); }, child: Icon(Icons.edit), ), ), ); } } ``` --- ## 二、系统级通知(System Notification) 这是指应用在后台运行时,通过操作系统发送给用户的提醒(如 Android 的 `Notification` 或 iOS 的推送通知)。 ### 1. Android 系统通知 你可以使用 `flutter_local_notifications` 插件来实现本地通知。 #### 安装插件 在 `pubspec.yaml` 中添加: ```yaml dependencies: flutter_local_notifications: ^9.0.0 ``` #### 示例代码 ```dart import 'package:flutter/material.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; void main() { WidgetsFlutterBinding.ensureInitialized(); final flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); const AndroidInitializationSettings initializationSettingsAndroid = AndroidInitializationSettings('app_icon'); final InitializationSettings initializationSettings = InitializationSettings( android: initializationSettingsAndroid, ); flutterLocalNotificationsPlugin.initialize(initializationSettings); runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text("Notification Example")), body: const Center(child: Text("Click to show notification")), floatingActionButton: FloatingActionButton( onPressed: () async { await showNotification(flutterLocalNotificationsPlugin); }, child: const Icon(Icons.notifications), ), ), ); } Future<void> showNotification(FlutterLocalNotificationsPlugin plugin) async { const AndroidNotificationDetails androidPlatformChannelSpecifics = AndroidNotificationDetails( 'your_channel_id', 'your_channel_name', importance: Importance.high, priority: Priority.high, channelDescription: 'your_channel_description', ); const NotificationDetails platformChannelSpecifics = NotificationDetails(android: androidPlatformChannelSpecifics); await plugin.show( 0, 'Title', 'This is a notification message', platformChannelSpecifics, ); } } ``` ### 2. iOS 系统通知(Push Notification) iOS 推送通知需要使用 Apple Push Notification Service (APNS),一般通过 Firebase Cloud Messaging (FCM) 或其他后端服务实现。 你可以使用 `firebase_messaging` 插件来处理远程通知。 #### 安装插件 ```yaml dependencies: firebase_messaging: ^11.0.0 ``` #### 初始化并监听通知 ```dart import 'package:firebase_messaging/firebase_messaging.dart'; void main() { WidgetsFlutterBinding.ensureInitialized(); Firebase.initializeApp(); FirebaseMessaging.instance.getInitialMessage().then((remoteMessage) { if (remoteMessage != null) { print('Got initial message: ${remoteMessage.notification?.title}'); } }); FirebaseMessaging.onMessage.listen((RemoteMessage remoteMessage) { print('Got a message while in foreground: ${remoteMessage.notification?.title}'); }); runApp(MyApp()); } ``` --- ## 三、总结 | 类型 | 说明 | 使用场景 | |------|------|----------| | **应用内通知(Event Notification)** | 使用 `Stream`、`ChangeNotifier` 等机制 | 组件间通信、状态更新 | | **系统通知(System Notification)** | 使用 `flutter_local_notifications` 或 `firebase_messaging` | 后台提醒、推送通知 | --- 如果你有具体的需求(比如:如何发送推送通知?如何显示本地通知?),欢迎继续提问!
上一篇:
Flutter 使用Intl包
下一篇:
Flutter Hero动画
标题录入,一次不能超过6条
返回顶部
留言
留言
评论