Flutter通知管理插件elegant_notification的使用
Flutter通知管理插件elegant_notification的使用
Elegant Notification
An elegant notification to display important messages to users
特性
- 显示带有动画效果的顶部通知
- 友好的堆叠式吐司(Toast)
- 内置主题(成功、错误、信息)
- 多种显示动画(从左、从右、从上、从下)
- 支持所有对齐位置(左上、中上、右上、左中、中间、右中、左下、中下、右下)
- 支持自定义主题实现
- 提供关闭和进度完成的回调处理
- 带有动画效果的进度条指示器
- 自定义可滑动方向
- 背景定制化
- 动画时长定制化
- 通知位置定制化
- 添加可点击的动作组件到通知中
- 通知关闭方式定制化
- 可定制的通知尺寸(高度和宽度)
- 可定制的遮罩层关闭和关闭后的操作
- 滑回动画
- 可定制的关闭按钮
- 可定制的边框和圆角半径
- RTL支持
开始使用
要使用此优雅通知包,您需要在pubspec.yaml
文件中添加依赖项。
dependencies:
elegant_notification: ^2.4.1
参数说明
以下是ElegantNotification构造函数的一些重要参数:
title
: 通知标题Widgetdescription
: 通知描述Widgetaction
: 在描述Widget下方显示的次要Widget,默认为nullicon
: 通知图标,默认为nullanimation
: 通知动画类型(fromLeft
,fromRight
,fromTop
,fromBottom
),默认值为fromLeft
toastDuration
: 通知持续时间,默认为3000毫秒position
: 通知在屏幕上的位置,默认为Alignment.topRight
onDismiss
: 用户点击外部或按下返回键时触发的回调autoDismiss
: 是否自动关闭通知,默认为falsedismissDirection
: 通知的滑动关闭方向,默认为DismissDirection.horizontal
更多参数请参阅官方文档。
示例代码
成功主题动画示例
ElegantNotification.success(
title: Text("Update"),
description: Text("Your data has been updated"),
onDismiss: () {
print('Message when the notification is dismissed');
},
onTap: () {
print('Message when the notification is pressed');
},
closeOnTap: true,
).show(context);
堆叠通知示例
ElegantNotification.success(
width: 360,
isDismissable: false,
animationCurve: Curves.bounceOut,
stackedOptions: StackedOptions(
key: 'top',
type: StackedType.same,
itemOffset: Offset(-5, -5),
),
position: Alignment.topCenter,
animation: AnimationType.fromTop,
title: Text('Update'),
description: Text('Your data has been updated'),
onDismiss: () {},
onNotificationPressed: () {},
).show(context);
带阴影效果的通知
ElegantNotification.success(
width: 360,
isDismissable: false,
animationCurve: Curves.bounceOut,
position: Alignment.topCenter,
animation: AnimationType.fromTop,
title: Text('Update'),
description: Text('Your data has been updated'),
onDismiss: () {},
onNotificationPressed: () {},
shadow: BoxShadow(
color: Colors.green.withOpacity(0.2),
spreadRadius: 2,
blurRadius: 5,
offset: const Offset(0, 4),
),
).show(context);
最简单的通知展示方式
ElegantNotification(
description: Text("Please verifiy your data")
).show(context);
自定义主题动画示例
ElegantNotification(
title: Text("New version"),
description: Text("A new version is available to you please update."),
icon: Icon(
Icons.access_alarm,
color: Colors.orange,
),
progressIndicatorColor: Colors.orange,
).show(context);
不带标题的通知
ElegantNotification.error(
description: Text("Please verifiy your data")
).show(context);
带动作的通知
ElegantNotification.info(
description: Text('This account will be updated once you exit',),
action: InkWell(
onTap: (){
print('Link pressed')
},
child: Text( 'Link',
style: TextStyle(
decoration: TextDecoration.underline,
color: Colors.blue,
),
)
),
).show(context);
使用dismissDirection
属性
ElegantNotification.success(
width: 360,
position: Alignment.topCenter,
animation: AnimationType.fromTop,
title: Text('Update'),
description: Text('Your data has been updated'),
onDismiss: () {
print('Message when the notification is dismissed');
},
onNotificationPressed: () {
print('Message when the notification is pressed');
},
isDismissible: true,
dismissDirection: DismissDirection.up,
).show(context);
完整示例应用
以下是一个完整的Flutter应用程序示例,展示了如何使用ElegantNotification插件创建不同类型的通知:
import 'package:elegant_notification/elegant_notification.dart';
import 'package:elegant_notification/resources/arrays.dart';
import 'package:elegant_notification/resources/stacked_options.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
body: ExampleApp(),
),
);
}
}
class ExampleApp extends StatelessWidget {
late ElegantNotification notification;
ExampleApp({super.key});
@override
Widget build(BuildContext context) {
return SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// Success theme notification stacked (top center)
InkWell(
onTap: () {
ElegantNotification.success(
width: 360,
isDismissable: false,
stackedOptions: StackedOptions(
key: 'top',
type: StackedType.same,
itemOffset: const Offset(-5, -5),
),
title: const Text('Update'),
description: const Text('Your data has been updated'),
onDismiss: () {
// Message when the notification is dismissed
},
onNotificationPressed: () {
// Message when the notification is pressed
},
border: const Border(
bottom: BorderSide(
color: Colors.green,
width: 2,
),
),
).show(context);
},
child: Container(
width: 150,
height: 100,
color: Colors.blue,
child: const Center(
child: Padding(
padding: EdgeInsets.all(8.0),
child: Text(
'Success theme notification stacked\n(top center)',
style: TextStyle(color: Colors.white),
textAlign: TextAlign.center,
),
),
),
),
),
const SizedBox(width: 20),
// Error theme notification (top right)
InkWell(
onTap: () {
ElegantNotification.error(
width: 360,
stackedOptions: StackedOptions(
key: 'topRight',
type: StackedType.below,
itemOffset: const Offset(0, 5),
),
position: Alignment.topRight,
animation: AnimationType.fromRight,
title: const Text('Error'),
description: const Text('Error example notification'),
onDismiss: () {},
).show(context);
},
child: Container(
width: 150,
height: 100,
color: Colors.blue,
child: const Center(
child: Padding(
padding: EdgeInsets.all(8.0),
child: Text(
'Error theme notification\n(top right)',
style: TextStyle(color: Colors.white),
textAlign: TextAlign.center,
),
),
),
),
),
],
),
const SizedBox(height: 20),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// Info theme notification (center left)
InkWell(
onTap: () {
notification = ElegantNotification.info(
width: 360,
stackedOptions: StackedOptions(
key: 'left',
type: StackedType.same,
scaleFactor: 0.2,
itemOffset: const Offset(-20, 10),
),
toastDuration: const Duration(seconds: 5),
position: Alignment.centerLeft,
animation: AnimationType.fromLeft,
title: const Text('Info'),
description: const Text(
'This account will be updated once you exit',
),
onNotificationPressed: () {
notification.dismiss();
},
showProgressIndicator: false,
onDismiss: () {},
icon: const Icon(
Icons.ac_unit_rounded,
color: Colors.amber,
),
);
notification.show(context);
},
child: Container(
width: 150,
height: 100,
color: Colors.blue,
child: const Center(
child: Padding(
padding: EdgeInsets.all(8.0),
child: Text(
'Info theme notification\n(center left)',
style: TextStyle(color: Colors.white),
textAlign: TextAlign.center,
),
),
),
),
),
const SizedBox(width: 20),
// Custom notification (center right)
InkWell(
onTap: () {
ElegantNotification(
width: 360,
position: Alignment.centerRight,
animation: AnimationType.fromRight,
stackedOptions: StackedOptions(
key: 'top',
type: StackedType.same,
itemOffset: const Offset(-1, -6),
),
title: const Text(
'New version',
style: TextStyle(
color: Colors.red,
),
),
description: const Text(
'A new version is available to you please update.',
),
progressIndicatorColor: Colors.orange,
onDismiss: () {},
).show(context);
},
child: Container(
width: 150,
height: 100,
color: Colors.blue,
child: const Center(
child: Text(
'Custom notification\n(center right)',
style: TextStyle(color: Colors.white),
textAlign: TextAlign.center,
),
),
),
),
],
),
const SizedBox(height: 20),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// Notification with action (bottom left)
InkWell(
onTap: () {
ElegantNotification.info(
width: 360,
position: Alignment.bottomLeft,
animation: AnimationType.fromLeft,
title: const Text('Info'),
description: const Text(
'This account will be updated once you exit',
),
action: InkWell(
onTap: () {},
child: const Text(
'Link',
style: TextStyle(
decoration: TextDecoration.underline,
color: Colors.blue,
),
),
),
showProgressIndicator: false,
onDismiss: () {},
).show(context);
},
child: Container(
width: 150,
height: 100,
color: Colors.blue,
child: const Center(
child: Padding(
padding: EdgeInsets.all(8.0),
child: Text(
'Notification with action\n(bottom left)',
style: TextStyle(color: Colors.white),
textAlign: TextAlign.center,
),
),
),
),
),
const SizedBox(width: 20),
// Easiest way to display elegant notification
InkWell(
onTap: () {
ElegantNotification(
description: const Text(
'This is the easiest way to display an elegant notification',
),
).show(context);
},
child: Container(
width: 150,
height: 100,
color: Colors.blue,
child: const Center(
child: Text(
'Easiest way to display elegant notification',
style: TextStyle(color: Colors.white),
textAlign: TextAlign.center,
),
),
),
),
],
),
const SizedBox(height: 20),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// Notification with custom close button (top right)
InkWell(
onTap: () {
ElegantNotification(
width: 360,
position: Alignment.topRight,
animation: AnimationType.fromRight,
description: const Text(
'You can now leave the dashboard.',
),
icon: const Icon(
Icons.dashboard_customize_outlined,
color: Colors.purple,
),
progressIndicatorColor: Colors.purple,
showProgressIndicator: false,
autoDismiss: false,
closeButton: (dismiss) => Container(
margin: Directionality.of(context) == TextDirection.rtl
? const EdgeInsets.only(left: 20)
: const EdgeInsets.only(right: 20),
child: ElevatedButton(
onPressed: dismiss,
style: ElevatedButton.styleFrom(
shape: const CircleBorder(),
padding: const EdgeInsets.all(20),
backgroundColor: Colors.purple, // Button color
foregroundColor: Colors.white, // Splash color
),
child: const Icon(Icons.logout, color: Colors.white),
),
),
onDismiss: () {},
).show(context);
},
child: Container(
width: 150,
height: 100,
color: Colors.blue,
child: const Center(
child: Padding(
padding: EdgeInsets.all(8.0),
child: Text(
'Notification with custom close button\n(top right)',
style: TextStyle(color: Colors.white),
textAlign: TextAlign.center,
),
),
),
),
),
const SizedBox(width: 20),
// Custom progress bar sizes
InkWell(
onTap: () {
ElegantNotification.success(
key: const Key('value'),
description: const Text(
'Your account has been created successfully',
),
progressBarHeight: 10,
progressBarPadding: const EdgeInsets.symmetric(
horizontal: 20,
),
progressIndicatorBackground: Colors.green[100]!,
).show(context);
},
child: Container(
width: 150,
height: 100,
color: Colors.blue,
child: const Center(
child: Padding(
padding: EdgeInsets.all(8.0),
child: Text(
'Custom progress bar sizes',
style: TextStyle(color: Colors.white),
textAlign: TextAlign.center,
),
),
),
),
),
],
),
],
),
);
}
}
通过以上代码示例,您可以快速了解如何在Flutter项目中集成并使用ElegantNotification插件来创建各种类型的优雅通知。希望这些内容能帮助您更好地理解和使用该插件!
更多关于Flutter通知管理插件elegant_notification的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter通知管理插件elegant_notification的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter项目中使用elegant_notification
插件进行通知管理的示例代码。elegant_notification
是一个功能强大的Flutter插件,用于在Android和iOS平台上管理本地通知。
1. 添加依赖
首先,在你的pubspec.yaml
文件中添加elegant_notification
依赖:
dependencies:
flutter:
sdk: flutter
elegant_notification: ^x.y.z # 请替换为最新版本号
然后运行flutter pub get
来安装依赖。
2. 初始化插件
在你的Flutter应用的入口文件(通常是main.dart
)中,初始化ElegantNotification
插件。
import 'package:flutter/material.dart';
import 'package:elegant_notification/elegant_notification.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
// 初始化ElegantNotification
ElegantNotification.init(
onNotificationClick: (notification) {
// 处理通知点击事件
print("Notification clicked: ${notification.toMap()}");
},
onNotificationReceived: (notification) {
// 处理接收到通知的事件
print("Notification received: ${notification.toMap()}");
},
);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Elegant Notification Example'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
_showNotification();
},
child: Text('Show Notification'),
),
),
),
);
}
void _showNotification() {
// 创建一个简单的通知
ElegantNotification.show(
title: 'Hello',
body: 'This is a notification from Elegant Notification plugin!',
payload: {'key': 'value'}, // 可选,用于传递自定义数据
id: 1, // 通知的唯一标识符
autoCancel: true, // 是否在点击后自动取消通知
importance: NotificationImportance.High,
smallIcon: 'ic_notification', // 通知的小图标资源名(需要放在Android资源文件夹中)
channelId: 'default_channel', // 通知渠道ID(需要先创建)
);
}
}
3. 配置Android通知渠道(仅在Android上需要)
在android/app/src/main/java/com/your/package/name/MainActivity.kt
(或Java文件)中,添加以下代码来配置通知渠道(如果你使用的是Kotlin):
import android.app.Application
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugins.GeneratedPluginRegistrant
import com.elegant.notification.ElegantNotification
class MainActivity: FlutterActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
GeneratedPluginRegistrant.registerWith(this)
// 配置通知渠道(仅在Android O及以上版本需要)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = "Default Channel"
val descriptionText = "Channel description"
val importance = NotificationManagerCompat.IMPORTANCE_DEFAULT
val channel = NotificationChannel("default_channel", name, importance).apply {
description = descriptionText
}
val notificationManager: NotificationManagerCompat = NotificationManagerCompat.from(this)
notificationManager.createNotificationChannel(channel)
}
// 初始化ElegantNotification(在Flutter端已经初始化,这里可以省略,但为了演示完整性保留)
ElegantNotification.init(this)
}
}
4. 配置iOS通知权限(可选,如果你需要支持iOS)
在ios/Runner/Info.plist
中添加以下权限配置,以请求通知权限:
<key>UIBackgroundModes</key>
<array>
<string>remote-notification</string>
</array>
<key>UNNotificationBreakthroughPriority</key>
<integer>1</integer>
<key>NSAppleMusicUsageDescription</key>
<string>We need your permission to use Apple Music</string>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
<key>UIApplicationSupportsIndirectInputEvents</key>
<true/>
<key>NSUserNotificationCenterUsageDescription</key>
<string>We need your permission to show notifications</string>
5. 运行应用
现在,你可以运行你的Flutter应用,并点击按钮来显示通知。
请注意,这只是一个基本示例,elegant_notification
插件提供了许多其他功能,如进度通知、定时通知、自定义布局等,你可以查阅官方文档来了解更多高级用法。