如何在 Flutter 中使用 pushNamed 导航后使 OverlayEntry 消失

How to make OverlayEntry disappear after navigating with pushNamed in Flutter

我正在尝试制作如下所示的叠加层: https://www.didierboelens.com/2018/06/how-to-create-a-toast-or-notifications-notion-of-overlay/ 使用 OverlayEntry.

import 'package:flutter/material.dart';
import 'dart:async';

class ShowNotificationIcon {

    void show(BuildContext context) async {
        OverlayState overlayState = Overlay.of(context);
        OverlayEntry overlayEntry = new OverlayEntry(builder: _build);

        overlayState.insert(overlayEntry);
    }

    Widget _build(BuildContext context){
      return new Positioned(
        top: 50.0,
        left: 50.0,
        child: new Material(
            color: Colors.transparent,
            child: new Icon(Icons.warning, color: Colors.purple),
        ),
      );
    }
}

调用方式:

ShowNotificationIcon _icon = new ShowNotificationIcon();

_icon.show(context);

但是,当我尝试导航到其他屏幕时,叠加层仍保留在屏幕中。

如何只在调用它的屏幕上显示叠加层,而不在其他屏幕上显示?

以防万一,这是我在 有状态小部件中尝试过的:

  ShowNotificationIcon _icon = new ShowNotificationIcon();

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _icon.show(context);
    });

    super.initState();
  }

  @override
  void dispose() {
    _icon.remove();
    super.dispose();
  }

我想建议使用软件包 flushbar。 https://github.com/AndreHaueisen/flushbar
正如包所说:如果您在通知用户时需要更多自定义,请使用此包。对于 Android 开发人员,它是用来替代 toasts 和 snackbars 的。

您还可以将 flushbarPosition 设置为 TOP 或 BOTTOM

Flushbar(
      title: "Hey Ninja",
      message: "Lorem Ipsum is simply dummy text of the printing and typesetting industry",
      flushbarPosition: FlushbarPosition.TOP,
      flushbarStyle: FlushbarStyle.FLOATING,
      reverseAnimationCurve: Curves.decelerate,
      forwardAnimationCurve: Curves.elasticOut,
      backgroundColor: Colors.red,
      boxShadows: [BoxShadow(color: Colors.blue[800], offset: Offset(0.0, 2.0), blurRadius: 3.0)],
      backgroundGradient: LinearGradient(colors: [Colors.blueGrey, Colors.black]),
      isDismissible: false,
      duration: Duration(seconds: 4),
      icon: Icon(
        Icons.check,
        color: Colors.greenAccent,
      ),
      mainButton: FlatButton(
        onPressed: () {},
        child: Text(
          "CLAP",
          style: TextStyle(color: Colors.amber),
        ),
      ),
      showProgressIndicator: true,
      progressIndicatorBackgroundColor: Colors.blueGrey,
      titleText: Text(
        "Hello Hero",
        style: TextStyle(
            fontWeight: FontWeight.bold, fontSize: 20.0, color: Colors.yellow[600], fontFamily: "ShadowsIntoLightTwo"),
      ),
      messageText: Text(
        "You killed that giant monster in the city. Congratulations!",
        style: TextStyle(fontSize: 18.0, color: Colors.green, fontFamily: "ShadowsIntoLightTwo"),
      ),
    )..show(context);

这通常使用 RouteAware+RouteObserver 执行。

RouteObserver 是一个对象,它让实现了 RouteAware 的对象对路由相关的一些变化做出反应,其中包括:

  • 一个路由被推到当前路由的顶部
  • 路线又回到了第一个计划

然后您可以使用这两个事件来hide/show您的叠加层


首先,您需要 RouteObserver

这可以创建为全局变量,需要传递给您的 Navigator。在基于 MaterialApp 的应用程序中,它通常看起来像这样:

final RouteObserver<PageRoute> routeObserver = RouteObserver<PageRoute>();

void main() {
  runApp(MaterialApp(
    home: Container(),
    navigatorObservers: [routeObserver],
  ));
}

然后,您拥有 OverlayEntry 的小部件现在可以像这样实现 RouteAware

class RouteAwareWidget extends StatefulWidget {
  State<RouteAwareWidget> createState() => RouteAwareWidgetState();
}

// Implement RouteAware in a widget's state and subscribe it to the RouteObserver.
class RouteAwareWidgetState extends State<RouteAwareWidget> with RouteAware {

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // routeObserver is the global variable we created before
    routeObserver.subscribe(this, ModalRoute.of(context) as PageRoute);
  }

  @override
  void dispose() {
    routeObserver.unsubscribe(this);
    super.dispose();
  }

  @override
  void didPush() {
    // Route was pushed onto navigator and is now topmost route.
  }

  @override
  void didPopNext() {
    // Covering route was popped off the navigator.
  }

  @override
  Widget build(BuildContext context) => Container();

}

此时,你可以使用didPushdidPopNext来show/hide你的OverlayEntry:

OverlayEntry myOverlay;

@override
void didPush() {
  myOverlay.remove();
}

@override
void didPopNext() {
  Overlay.of(context).insert(myOverlay);
}

你只需要 CompositedTransformTarget , CompositedTransformFollower LinkLayout.

多亏了这些,如果附加覆盖的小部件消失,覆盖也会消失。

final key = GlobalKey();
OverlayEntry? floatingEntry ;
final layerLink = LayerLink();

void hideEntry(){
  floatingEntry ?.remove();
}

void displayOverlay() {
    final overlay = Overlay.of(context);
    floatingEntry = OverlayEntry(builder: _buildFloatingButton);
    overlay!.insert(floatingEntry!);
  }


 Widget _buildFloatingButton(BuildContext context) {
    final render = key.currentContext!.findRenderObject() as RenderBox;
    final offset = render.localToGlobal(Offset.zero);
    final size = render.size;
    return Positioned(
      width: floatinSize,
      child: CompositedTransformFollower(
        link: layerLink,
        offset: Offset(0.0, -size.height / 2),
        showWhenUnlinked: false,
        child: Container(
          width: floatinSize,
          height: floatinSize,
          decoration: BoxDecoration(
            color: Get.theme.scaffoldBackgroundColor,
            shape: BoxShape.circle,
          ),
          padding: const EdgeInsets.all(10.0),
          child: Container(
            decoration: BoxDecoration(
              color: Get.theme.primaryColor,
              shape: BoxShape.circle,
            ),
            child: Icon(
              FontAwesomeIcons.plus,
              color: Get.theme.primaryColorDark,
            ),
          ),
        ),
      ),
    );
  }

 @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    return Container(
      width: size.width,
      height: _navigationHeight,
      color: Get.theme.bottomNavigationBarTheme.backgroundColor,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
              CompositedTransformTarget(
               link:linkLayout,
               child:Container(key:key),
              )
         ],
      ),
    );
  }