我使用flushbar向用户显示应用内通知,但我认为这个问题适用于任何想要覆盖在当前屏幕上的小部件,例如小吃店。
我希望能够显示独立于屏幕之间导航的通知,即,如果用户在屏幕之间导航,则通知应保留在所有屏幕上。因为刷新条通知仅在当前 BuildContext 上绘制,所以一旦用户关闭当前屏幕,通知也会消失(因为通知小部件是该屏幕小部件子树的一部分)。
无论导航如何,有没有办法在整个应用程序顶部显示小部件(例如通知)?
EDIT1:添加了示例代码。
import 'package:flushbar/flushbar_route.dart' as route;
import 'package:flushbar/flushbar.dart';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: FirstScreen(),
);
}
}
class FirstScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('First Screen'),
),
body: Center(
child: RaisedButton(
child: Text('go to second screen'),
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(builder: (BuildContext context) => SecondScreen())
);
},
),
),
);
}
}
class SecondScreen extends StatelessWidget {
final Flushbar _flushbar = Flushbar(message: 'Flushbar Notification');
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Second Screen'),
),
body: Center(
child: RaisedButton(
child: Text('show flushbar'),
onPressed: () {
showFlushbar(_flushbar, context);
},
),
),
);
}
}
Future showFlushbar(Flushbar instance, BuildContext context) {
final _route = route.showFlushbar(
context: context,
flushbar: instance,
);
return Navigator.of(context, rootNavigator: true).push(_route);
}
Run Code Online (Sandbox Code Playgroud)
结果将如下所示(返回第一个屏幕时,我希望通知保留在屏幕上):
EDIT2:乔治的解决方案有效。此外,对于其他人来说,使用叠加层也可能是一个合适的解决方案(请参阅此博客文章),即,即使在路线导航过程中,叠加层也会保持在屏幕上。但是,在我的情况下,覆盖解决方案不太优雅,因为它不允许刷新条被关闭或设置动画(或者至少它不那么简单)。
尝试从根导航器显示 Flushbar。
查看flushbar lib的来源,我们可以通过导入方法来创建我们自己的Flushbar路由。showFlushbarpackage:flushbar/flushbar_route.dart
例如
import 'package:flushbar/flushbar_route.dart' as route;
// ...
Future showFlushbar(Flushbar instance) {
final _route = route.showFlushbar(
context: context,
flushbar: instance,
);
return Navigator.of(context, rootNavigator: true).push(_route);
}
Run Code Online (Sandbox Code Playgroud)
感谢您在问题中添加的代码。
在我看来,最终的解决方案是Navigator在内部创建另一个右侧MaterialApp- 某种第二个“子根”导航器。
现在,您可以Navigator根据需要在 2 层之间进行选择。
Navigator.of(context, rootNavigator: true)将返回顶级导航器 - 将其用于您的 Flushbar 或您希望在所有屏幕上方保持持久的任何其他模式弹出窗口。
Navigator.of(context),其中rootNavigator为false默认值。使用它来获取“子根”导航器以显示新屏幕/页面。
例如,将另一个Navigator权利放在MaterialApp.
MaterialApp(
home: Navigator( // 'sub-root' navigator. Second in the hierarchy.
onGenerateRoute: (_) => MaterialPageRoute(
builder: (_) => FirstScreen(),
settings: RouteSettings(isInitialRoute: true),
),
),
);
Run Code Online (Sandbox Code Playgroud)
让我知道这是否有帮助。
| 归档时间: |
|
| 查看次数: |
6573 次 |
| 最近记录: |