Flutter通知管理插件own_notify的使用

own_notify #

own_notify 是一个用于在 Flutter 应用程序中管理通知的插件。它允许开发者通过简单的 API 创建本地通知。

快速开始 #

要开始使用 own_notify 插件,首先确保您的 Flutter 环境已正确配置。然后将插件添加到项目的 pubspec.yaml 文件中:

dependencies:
  own_notify: ^1.0.0

运行以下命令以安装依赖项:

flutter pub get

初始化插件

在应用程序启动时,调用 OwnNotify().initialize() 方法来初始化插件。

import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:own_notify/own_notify.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  OwnNotify().initialize(debug: true); // 初始化插件,设置 debug 模式为 true
  runApp(const MyApp());
}

创建通知

创建通知的基本步骤如下:

  1. 使用 OwnNotify().createNotification() 方法创建通知。
  2. 在按钮点击事件中调用该方法。

以下是完整的示例代码:

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Not Known';

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

  // 平台消息是异步的,因此我们通过异步方法进行初始化
  Future<void> initPlatformState() async {
    String platformVersion;
    try {
      // 获取平台版本
      _platformVersion = await OwnNotify().platformVersion ?? "未知平台版本";
    } on PlatformException {
      platformVersion = '获取平台版本失败。';
    }

    if (!mounted) return;

    setState(() {
      platformVersion = _platformVersion;
    });
  }

  Future<void> _showNotification() async {
    try {
      // 创建通知
      await OwnNotify().createNotification(
        title: "测试通知",
        body: "这是来自 own_notify 的测试通知。",
        showTime: DateTime.now(), // 设置通知显示时间
      );
      print("通知已成功创建!");
    } on PlatformException catch (e) {
      print("创建通知失败: ${e.message}");
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('own_notify 示例应用'),
        ),
        body: SizedBox(
          height: double.infinity,
          width: double.infinity,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text("当前平台版本: $_platformVersion", textAlign: TextAlign.center),
              ElevatedButton(
                onPressed: () {
                  _showNotification(); // 点击按钮时触发通知创建
                },
                child: const Text("显示通知"),
              )
            ],
          ),
        ),
      ),
    );
  }
}

运行效果

运行上述代码后,您会看到一个按钮,点击按钮后会在设备上显示一条通知。通知的内容包括标题、正文以及显示时间。

注意事项

  • 确保 Android 和 iOS 平台均已正确配置插件权限。

  • 在 Android 上,需要在 AndroidManifest.xml 中添加必要的权限:

    <uses-permission android:name="android.permission.VIBRATE"/>
    
  • 在 iOS 上,需要在 Info.plist 中配置通知权限:

    <key>NSUserNotificationUsageDescription</key>
    <string>我们需要访问通知权限以便向您发送通知。</string>
    

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

1 回复

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


own_notify 是一个用于 Flutter 的通知管理插件,它允许开发者在应用中自定义和管理通知。以下是如何使用 own_notify 插件的基本步骤:

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  own_notify: ^1.0.0  # 请检查最新版本

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

2. 初始化插件

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

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await OwnNotify.initialize();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'OwnNotify Example',
      home: NotificationScreen(),
    );
  }
}

3. 创建通知

你可以在应用中的任何地方创建通知。以下是一个简单的示例:

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

class NotificationScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('OwnNotify Example'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () async {
            await OwnNotify.showNotification(
              id: 1,
              title: 'Sample Notification',
              body: 'This is a sample notification from OwnNotify.',
              payload: 'sample_payload',
            );
          },
          child: Text('Show Notification'),
        ),
      ),
    );
  }
}

4. 处理通知点击

你可以通过监听通知的点击事件来处理用户点击通知后的操作。在你的 main.dart 文件中添加以下代码:

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await OwnNotify.initialize();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'OwnNotify Example',
      home: NotificationScreen(),
      navigatorKey: OwnNotify.navigatorKey, // 添加导航键
      onGenerateRoute: (settings) {
        if (settings.name == '/notification') {
          return MaterialPageRoute(
            builder: (context) => NotificationDetailScreen(payload: settings.arguments),
          );
        }
        return null;
      },
    );
  }
}

class NotificationScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('OwnNotify Example'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () async {
            await OwnNotify.showNotification(
              id: 1,
              title: 'Sample Notification',
              body: 'This is a sample notification from OwnNotify.',
              payload: 'sample_payload',
            );
          },
          child: Text('Show Notification'),
        ),
      ),
    );
  }
}

class NotificationDetailScreen extends StatelessWidget {
  final String payload;

  NotificationDetailScreen({required this.payload});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Notification Detail'),
      ),
      body: Center(
        child: Text('Payload: $payload'),
      ),
    );
  }
}

5. 自定义通知

你可以通过 OwnNotify.showNotification 方法自定义通知的标题、内容、图标、声音等属性。例如:

await OwnNotify.showNotification(
  id: 1,
  title: 'Custom Notification',
  body: 'This is a custom notification with sound and icon.',
  payload: 'custom_payload',
  sound: 'default',
  icon: 'app_icon',
);
回到顶部