在 Flutter 中删除后退按钮上的 OverLayEntry

Abu*_*lim 6 flutter flutter-layout

我正在使用 OverlayEntry 并且我想在 Back Press 上删除条目。

OverlayEntry overlayEntry;
    overlayEntry = OverlayEntry(builder: (c) {
      return FullScreenLoader(
          loaderText: "Placing Order",
          );
    },maintainState: true);
    Overlay.of(context).insert(overlayEntry);
Run Code Online (Sandbox Code Playgroud)

Build我使用过的Inside FullScreenLoader方法,onWillScope但它仍然无法正常工作。

 @override
  Widget build(BuildContext context) {
    return new WillPopScope(
        onWillPop: _onWillPop,
    );
  }

Future<bool> _onWillPop() {
    return "" ?? false;
}
Run Code Online (Sandbox Code Playgroud)

我只想检测物理后按按钮,以便我可以删除后按上的覆盖层。

我错过了什么吗?或者overLay不可能?

小智 4

你尝试的方式应该有效。使用 WillPopScope 检测后按并移除覆盖层(如果可见)。

这是一个工作示例代码。保留对覆盖条目的全局引用,并在状态类的 build 方法中添加 WillPopScope:

class _XYZState extends State<XYZ> {
  OverlayEntry _detailsOverlayEntry;

  @override
  Widget build(BuildContext context) {
    return Container(
      child: WillPopScope(
        onWillPop: _onWillPop,
        child: GoogleMap(
          mapType: MapType.normal,
          initialCameraPosition: _kFallbackInitialCameraPosition,
          polylines: _polylines.toSet(),
          myLocationEnabled: false,
          myLocationButtonEnabled: false,
          onMapCreated: (GoogleMapController controller) {
            _controller.complete(controller);
          },
        ),
      ),
    );
  }

  Future<bool> _onWillPop() {
    if(_detailsOverlayEntry != null){
      _detailsOverlayEntry.remove();
      _detailsOverlayEntry = null;
      return Future.value(false);
    }
    return Future.value(true);
  }
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,_detailsOverlayEntry == null条件检查用于检查覆盖条目是否可见。如果它可见,请将其删除并将引用设置为 null。

下次按下返回键时,它将弹出该路线。