保存当前路线并在Flutter中弹出上一条

时间:2019-06-02 21:59:00

标签: flutter

我有一个Flutter软件包,其中显示了一条通知,通知用户将新的路由推入堆栈顶部。 如果用户按下Android上的“后退”按钮或在IOS上使用后退手势并弹出上一条路线,我希望将通知的路线保持在最前面。

有办法吗?

1 个答案:

答案 0 :(得分:0)

Notification

class Notification {
  static OverlayEntry _overlayEntry;

  static void show({
    @required NotificationWidget notification,
    @required BuildContext context,
  }) {
    final OverlayState overlay =
        context.rootAncestorStateOfType(const TypeMatcher<OverlayState>());

    _overlayEntry = _buildOverlayEntry(notification);

    overlay.insert(_overlayEntry);
  }

  static OverlayEntry _buildOverlayEntry(NotificationWidget notification) {
    return OverlayEntry(
      builder: (_) {
        return Positioned(
          left: 8,
          top: 32,
          right: 8,
          child: notification,
        );
      },
    );
  }

  static void hide() {
    if (_overlayEntry != null) {
      _overlayEntry.remove();
      _overlayEntry = null;
    }
  }
}

NotificationWidget

class NotificationWidget extends StatelessWidget {
  final String title;
  final String description;

  NotificationWidget({
    Key key,
    @required this.title,
    @required this.description,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Card(
      elevation: 4,
      child: Padding(
        padding: EdgeInsets.all(16),
        child: Column(
          children: [
            Text(
              title,
              style: Theme.of(context).textTheme.title,
            ),
            SizedBox(height: 4),
            Text(
              description,
              style: Theme.of(context).textTheme.body1,
            ),
          ],
        ),
      ),
    );
  }
}

要显示或隐藏,用户可以编写:

void showNotification() {
  Notification.show(
    context: context,
    notification: NotificationWidget(
      title: 'Notification title',
      description: 'Notification description',
    ),
  );
}

void hideNotification() => Notification.hide();

NotificationNotificationWidget可以是一个类,但是我认为这样更好。此外,用户可以通过覆盖NotificationWidget来轻松创建他/她的自定义通知。