Flutter通知管理插件notification_centre的使用

Flutter通知管理插件notification_centre的使用

NotificationCenter 是一个轻量级的消息发布/订阅库,用于在整个 Flutter 应用程序中传递消息。它受到 iOS 中的 NotificationCenter 和 Android 中的 EventBus 的启发。

开始使用

在 Flutter 中,NotificationCentre 受到 iOS 中的 NotificationCenter 和 Android 中的 EventBus 的启发。由于它可以在 iOS(Swift/Objective-C)代码库中的任何地方使用,我们非常熟悉发布者-观察者模型。对于 Android 开发者来说,如果你已经熟悉 EventBus,那么你将很容易上手。

特性

  • 观察者:如果接收到消息,则观察事件。
  • 发布者:将事件发布给所有观察者。

使用方法

添加观察者

建议你在 initState() 方法中添加观察者,但你也可以在其他地方添加观察者。

[@override](/user/override)
void initState() { 
    super.initState(); 
    NotificationCenter().addObserver(NOTIFICATION_NAME_USER_SIGNED_IN, this, () {
        // 用户登录后执行的操作。
    });
}

移除观察者

建议你在 dispose() 方法中移除观察者,但你也可以在其他地方移除观察者。

[@override](/user/override)
void dispose() { 
    NotificationCenter().removeObserver(NOTIFICATION_NAME_USER_SIGNED_IN, this);
    super.dispose();
}

发布消息

你可以通过以下代码轻松地在整个应用程序中发布消息。

NotificationCenter().postNotification(
    NOTIFICATION_NAME_PURCHASE_COMPLETED, 
    data: {"data": YOUR_DATA, "type": "completed"},
);

注意事项

NotificationName 只是一个普通的字符串值,可以是任何字符串。请记住,在调用 addObserver()removeObserver()postNotification() 这三个方法时,传递的 NotificationName 必须一致。

完整示例代码

以下是一个完整的示例代码,展示了如何使用 NotificationCenter 来处理用户登录状态的变化。

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

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});
    
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(    
      onGenerateRoute: (RouteSettings routeSettings) {
        return MaterialPageRoute<void>(
          settings: routeSettings,
          builder: (BuildContext context) {
            switch (routeSettings.name) {
              case LoginPage.routeName: return LoginPage(); 
              default: return MainPage();
            }
          }
        );
      }
    ); 
  }
}

class MainPage extends StatefulWidget {

  [@override](/user/override)
  State<StatefulWidget> createState() => _MainPageState();

}

class _MainPageState extends State<MainPage> {

  String loginState = "Not Sign In";

  [@override](/user/override)
  void initState() { 
    super.initState();
    NotificationCenter().addObserver(NOTIFICATION_NAME_USER_SIGNED_IN, this, () {
      // 更新 UI,一旦用户已登录。
      setState(() {
        loginState = "You signed in!";
      });
    });
  }
  
  [@override](/user/override)
  void dispose() {
    NotificationCenter().removeObserver(NOTIFICATION_NAME_USER_SIGNED_IN, this);
    super.dispose();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text(loginState),
      ),
    );
  }

}

class LoginPage extends StatelessWidget {

  static const routeName = "/login";

  String notificationName = "";

  LoginPage({super.key}) {
    // 对于 NotificationName,它只是一个字符串值,可以是任何字符串。 
    // 请记住,你定义或自定义的 NotificationName 必须与观察者和发布者一致。
    notificationName = NOTIFICATION_NAME_USER_SIGNED_IN;
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: TextButton(
          onPressed: () {
            NotificationCenter().postNotification(
              notificationName, 
              data: {"userId": 123456789, "type": "normal"},
            );
          },
          child: Text("Go to Sign In"),
        ),
      ),
    );
  }

}

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

1 回复

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


当然,以下是如何在Flutter应用中使用notification_centre插件来管理通知的一个简单示例。这个插件可以帮助你显示、处理本地和系统通知。请注意,具体功能可能会根据插件版本有所不同,因此确保你查阅了最新的官方文档。

首先,确保你已经在pubspec.yaml文件中添加了notification_centre依赖:

dependencies:
  flutter:
    sdk: flutter
  notification_centre: ^最新版本号 # 替换为实际最新版本号

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

接下来,让我们编写一些代码来展示如何使用这个插件。

1. 初始化插件并请求通知权限

在你的主应用文件(通常是main.dart)中,初始化插件并请求通知权限:

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

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

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

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    _requestNotificationPermissions();
  }

  Future<void> _requestNotificationPermissions() async {
    NotificationCentre.requestNotificationPermissions().then((permissionStatus) {
      if (permissionStatus == NotificationPermissionStatus.granted) {
        print('Notification permissions granted.');
      } else {
        print('Notification permissions denied.');
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Notification Centre Example'),
        ),
        body: Center(
          child: ElevatedButton(
            onPressed: () => _showNotification(),
            child: Text('Show Notification'),
          ),
        ),
      ),
    );
  }

  Future<void> _showNotification() async {
    var notification = Notification(
      title: 'Hello',
      body: 'This is a test notification!',
      payload: 'some_payload',
    );

    await NotificationCentre.show(notification);
  }
}

2. 处理接收到的通知

你可能还希望处理应用在前台或后台时接收到的通知。为此,你可以监听通知点击事件:

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

  // 监听通知点击事件
  NotificationCentre.notificationClickedStream.listen((ReceivedNotification notification) {
    print('Notification clicked: ${notification.title}, Payload: ${notification.payload}');
    // 在这里处理点击事件,比如导航到特定页面
  });
}

3. 发送带动作的通知(可选)

你还可以发送带有动作按钮的通知。以下是一个示例:

Future<void> _showNotificationWithActions() async {
  var notification = Notification(
    title: 'Hello',
    body: 'This notification has actions!',
    payload: 'some_payload',
    android: AndroidNotificationDetails(
      'channel_id',
      'Channel Name',
      'Channel Description',
      importance: Importance.max,
      priority: Priority.max,
      actions: [
        NotificationAction(
          icon: 'ic_action_accept',
          title: 'Accept',
          callback: () {
            print('Accept button clicked!');
          },
        ),
        NotificationAction(
          icon: 'ic_action_reject',
          title: 'Reject',
          callback: () {
            print('Reject button clicked!');
          },
        ),
      ],
    ),
    iOS: IOSNotificationDetails(),
  );

  await NotificationCentre.show(notification);
}

在这个示例中,我们定义了两个动作按钮“Accept”和“Reject”,并为每个按钮指定了一个回调函数。

总结

以上代码展示了如何在Flutter应用中使用notification_centre插件来发送和接收通知。你可以根据实际需求进一步自定义通知内容和行为。确保查阅最新的插件文档以获取更多功能和最佳实践。

回到顶部