在本教程中,我們將介紹如何在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