首页 > 解决方案 > 在颤动中关闭包含 DraggableScrollableSheet 的 BottomSheet

问题描述

我正在使用 showButtomSheet 显示一个包含 DraggableScrollableSheet 的 BottomSheet。我想通过单击 DarggableScrollableSheet 上的按钮来关闭 BottomSheet。我怎样才能做到这一点?

只要 DraggableScrollableSheet 不靠近屏幕顶部,我就可以使其工作,但是当它靠近顶部时,工作表下方会出现模态叠加,当我关闭工作表时,模态覆盖仍然存在。

我曾尝试使用 PersistentBottomSheetController.close() 关闭工作表并使用 Navigator.pop 如下所示,但结果是相同的:关闭工作表后,深色覆盖仍然存在,我找不到方法去掉它。

飞镖板: http ://dartpad.dev/7ec436f3c850936d74dcdbb6ff17f97c

屏幕录像:https ://i.stack.imgur.com/vE1VE.gif

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  static const String _title = 'Flutter Code Sample';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      home: Scaffold(
        body: MyStatelessWidget(),
      ),
    );
  }
}

class MyStatelessWidget extends StatelessWidget {
  MyStatelessWidget({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Center(
      child: ElevatedButton(
        child: const Text('showBottomSheet'),
        onPressed: () {
          Scaffold.of(context).showBottomSheet<void>(
                (BuildContext context) {

              return DraggableScrollableSheet(
                  expand: false,
                  maxChildSize: 0.935,
                  builder: (context, scrollController) => ListView(
                    controller: scrollController,
                    padding: const EdgeInsets.all(8),
                    children: <Widget>[
                      Container(
                        height: 200,
                        color: Colors.amber[600],
                        child: Center(
                          child: ElevatedButton(
                            child: const Text('Close BottomSheet'),
                            onPressed: () => Navigator.pop(context),
                          ),
                        ),
                      ),
                      Container(
                        height: 500,
                        color: Colors.amber[500],
                        child: const Center(child: Text('Entry B')),
                      ),
                    ],
                  ),
              );
            },
          );
        },
      ),
    );
  }
}

标签: flutterflutter-layout

解决方案


解决方案是将关闭操作更改为:

ElevatedButton(
    child: const Text('Close BottomSheet'),
    onPressed: () {
        Navigator.pop(context);
        Scaffold.of(context).showBodyScrim(false, 0.0);
    }
),

当 BottomSheet 一直拖到顶部时,Scaffold 在 BottomSheet 下方添加一个 ModalBarrier。ModalBarrier 可以通过 ScaffoldState 方法 showBodyScrim 进行控制:https ://api.flutter.dev/flutter/material/ScaffoldState/showBodyScrim.html


推荐阅读