Flutter中的应用程序内通知
2019-07-10 本文已影响2人
开心人开发世界

在本教程中,我们将介绍如何在Flutter应用程序中显示应用内通知。我们将首先添加overlay_support包
overlay_support: ^1.0.0
要使用叠加功能,我们必须将材质应用程序包装在OverlaySupport
窗口小部件中。
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return OverlaySupport(
child: MaterialApp(
title: 'Flutter Demo',
home: Scaffold(),
),
);
}
}
我们将显示通知叠加层的修改。这个库可以做更多的通知。我们将涵盖:
- 自动解除的基本通知
- 使用按钮解除通知的固定通知
- 消息样式自定义通知
我们将在scaffold的FloatingActionButton中的onPressed回调中编写所有代码。
Widget build(BuildContext context) {
return OverlaySupport(
..
home: Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: () {
// notification code will go here
},
)
),
);
}
基本通知
我们将从基本通知开始。带有一些文字的紫色通知
showSimpleNotification(
Text("Subscribe to FilledStacks"),
background: Colors.purple,
);

“关闭”按钮的通知
要在没有自动解除的情况下保持通知,我们将其设置autoDismiss
为false。我们不希望通知始终保持在那里,因此我们将构建一个用户可以点按以关闭的尾随按钮。
showSimpleNotification(
Text("Subscribe to FilledStacks"),
background: Colors.purple,
autoDismiss: false,
trailing: Builder(builder: (context) {
return FlatButton(
textColor: Colors.yellow,
onPressed: () {
OverlaySupportEntry.of(context).dismiss();
},
child: Text('Dismiss'));
}),
);

自定义通知
要显示一些自定义UI,您可以使用该showOverlayNotification
功能。它将构建器作为第一个位置参数。我们将返回带有一些边距的卡片,卡片的内容我们将包装在SafeArea中,因为它将显示在屏幕顶部,槽口可能会干扰。通知的内容将是一个基本的ListTile,其中包含所有属性。
showOverlayNotification((context) {
return Card(
margin: const EdgeInsets.symmetric(horizontal: 4),
child: SafeArea(
child: ListTile(
leading: SizedBox.fromSize(
size: const Size(40, 40),
child: ClipOval(
child: Container(
color: Colors.black,
))),
title: Text('FilledStacks'),
subtitle: Text('Thanks for checking out my tutorial'),
trailing: IconButton(
icon: Icon(Icons.close),
onPressed: () {
OverlaySupportEntry.of(context).dismiss();
}),
),
),
);
}, duration: Duration(milliseconds: 4000));

您可以构建一个通知窗口小部件,如果要显示多条消息,则可以在标题和消息中传递该窗口小部件。查看网站上的其他片段,了解更多Flutter教程。
转:https://medium.com/flutter-community/in-app-notifications-in-flutter-9c1e92ea10b3