Flutter通知提醒插件alert_notification的使用

发布于 1周前 作者 sinazl 来自 Flutter

Flutter通知提醒插件alert_notification的使用

标题

AlertNotification

内容

这个包展示了一个简单的的通知,用于通知用户所有需要知道的信息。

默认通知示例

默认通知示例如下:

AlertNotification(
    title: 'Info',
    body: 'You should know this.',
    type: AlertNotificationType.info,
),

出线条框通知示例

出线条框通知示例如下:

AlertNotification.outlined(
    title: 'Info',
    body: 'You should know this.',
    type: AlertNotificationType.info,
),

功能特性

  • 完全可定制的通知
  • 出线条框版本

即将添加的功能

  • 关闭按钮
  • 包含链接的带格式副标题
  • 显示时的动画效果
  • 隐藏时的动画效果

使用方法

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

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

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter AlertNotification Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter AlertNotification Demo'),
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: SingleChildScrollView(
        child: Center(
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const Text(
                  'Default notification',
                  style: TextStyle(fontSize: 25),
                ),
                const SizedBox(height: 16),
                const AlertNotification(
                  title: 'Info',
                  body: 'You should know this.',
                  type: AlertNotificationType.info,
                ),
                const SizedBox(height: 16),
                const AlertNotification(
                  title: 'Success',
                  body: 'All good!',
                  type: AlertNotificationType.success,
                ),
                const SizedBox(height: 16),
                const AlertNotification(
                  title: 'Warning',
                  body: 'You should probably worry about this.',
                  type: AlertNotificationType.warning,
                ),
                const SizedBox(height: 16),
                const AlertNotification(
                  title: 'Error',
                  body: 'Something is wrong!',
                  type: AlertNotificationType.error,
                ),
                const SizedBox(height: 16),
                const Text(
                  'Outlined notification',
                  style: TextStyle(fontSize: 25),
                ),
                const SizedBox(height: 16),
                AlertNotification.outlined(
                  title: 'Info',
                  body: ' you should know this.',
                  type: AlertNotificationType.info,
                ),
                const SizedBox(height: 16),
                AlertNotification.outlined(
                  title: 'Success',
                  body: 'All good!',
                  type: AlertNotificationType.success,
                ),
                const SizedBox(height: 16),
                AlertNotification.outlined(
                  title: 'Warning',
                  body: 'you should probably worry about this.',
                  type: AlertNotificationType.warning,
                ),
                const SizedBox(height: 16),
                AlertNotification.outlined(
                  title: 'Error',
                  body: 'Something is wrong!',
                  type: AlertNotificationType.error,
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

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

1 回复

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


当然,下面是一个关于如何在Flutter应用中使用alert_notification插件来实现通知提醒的示例代码。

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

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

然后,运行flutter pub get来获取依赖。

接下来,在你的Flutter项目中,你可以按照以下步骤配置和使用alert_notification插件。

1. 配置Android权限

android/app/src/main/AndroidManifest.xml文件中添加必要的权限,例如:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.VIBRATE"/>

2. 初始化插件

在你的主文件(例如main.dart)中,导入alert_notification插件并进行初始化:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Alert Notification Example'),
        ),
        body: Center(
          child: MyHomePage(),
        ),
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  late AlertNotification _alertNotification;

  @override
  void initState() {
    super.initState();
    _alertNotification = AlertNotification(
      android: AndroidInitializationSettings('@mipmap/ic_launcher'), // 替换为你的应用图标资源
      iOS: IOSInitializationSettings(
        requestAlertPermission: true,
        requestBadgePermission: true,
        requestSoundPermission: true,
      ),
    );

    // 初始化插件
    _alertNotification.initialize().then((_) {
      // 插件初始化成功后,可以在这里配置其他逻辑
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        ElevatedButton(
          onPressed: () {
            _showNotification();
          },
          child: Text('Show Notification'),
        ),
      ],
    );
  }

  Future<void> _showNotification() async {
    var androidPlatformChannelSpecifics = AndroidNotificationDetails(
      'your_channel_id',
      'Your Channel Name',
      'Your Channel Description',
      importance: Importance.max,
      priority: Priority.high,
      channelShowBadge: true,
    );
    var iOSPlatformChannelSpecifics = IOSNotificationDetails();
    var platformChannelSpecifics = NotificationDetails(
      android: androidPlatformChannelSpecifics,
      iOS: iOSPlatformChannelSpecifics,
    );
    await _alertNotification.show(
      title: 'Hello',
      body: 'This is a notification!',
      payload: 'item_id_123',
      notificationDetails: platformChannelSpecifics,
    );
  }
}

3. 配置Android通知渠道(可选)

对于Android 8.0(API级别26)及更高版本,你需要配置通知渠道。虽然alert_notification插件可以在内部为你处理一些默认设置,但你可能希望自定义这些设置。你可以在MainActivity.ktMainActivity.java中进一步配置。

例如,在MainActivity.kt中:

import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugins.generated.AlertNotificationPluginRegistrant
import com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin

class MainActivity: FlutterActivity() {
    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        AlertNotificationPluginRegistrant.registerWith(flutterEngine.dartExecutor.binaryMessenger)

        // 配置FlutterLocalNotificationsPlugin(如果需要)
        val notificationsPlugin = FlutterLocalNotificationsPlugin()
        notificationsPlugin.createNotificationChannelGroup(flutterEngine.dartExecutor.binaryMessenger, "group_key", "Group Channel")
        notificationsPlugin.createNotificationChannel(flutterEngine.dartExecutor.binaryMessenger, "your_channel_id",
            "Your Channel Name", "Your Channel Description", importance = Importance.MAX, priority = Priority.HIGH)
    }
}

请注意,上述Kotlin代码示例假设你也使用了flutter_local_notifications插件,因为alert_notification可能依赖于它来显示本地通知。如果你只使用alert_notification,则可能不需要这部分代码,或者它已经在插件内部处理。

总结

以上代码展示了如何在Flutter应用中使用alert_notification插件来显示通知。确保你遵循了插件的文档和API要求,并根据需要进行适当的调整。

回到顶部