如何通过
bottomSheet
知道Scaffold
的scaffoldKey
是否打开?
工作表的打开方式如下:
scaffoldKey.currentState!.showBottomSheet(.....);
较新版本的 flutter
scaffoldKey.currentState
中没有可用于决定是否打开的封装方法。
如果您需要检查代码,请转到该gist
scaffoldKey
中没有内置方法可以直接检查底页是否打开。但是,当您使用 scaffoldKey.currentState!.showBottomSheet()
打开底部工作表时,它会返回 PersistentBottomSheetController
。您可以存储此控制器并使用其 closed
getter 来确定底部工作表是否仍然打开。控制器还提供了close
方法来手动关闭底板。
要实现此目的,您可以按照以下步骤操作:
PersistentBottomSheetController? controller;
controller = _scaffoldKey.currentState?.showBottomSheet(
(_) => Container(
height: 200,
color: Colors.grey,
),
);
closed
getter 监听底部工作表何时关闭并将控制器重置为 null
:controller?.closed.then((_) => controller = null);
null
:if (controller != null) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Bottom Sheet is open'),
),
);
} else {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Bottom Sheet is closed'),
),
);
}
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(
home: MainApp(),
));
}
class MainApp extends StatelessWidget {
const MainApp({super.key});
// Global key to access the ScaffoldState
static final _scaffoldKey = GlobalKey<ScaffoldState>();
@override
Widget build(BuildContext context) {
PersistentBottomSheetController? controller;
return Scaffold(
key: _scaffoldKey,
appBar: AppBar(
title: const Text('Bottom Sheet Example'),
),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ElevatedButton(
onPressed: () {
// Open the bottom sheet and store the controller
controller = _scaffoldKey.currentState?.showBottomSheet(
(_) => Container(
height: 200,
color: Colors.grey,
),
);
// Listen for when the bottom sheet is closed and reset the controller
controller?.closed.then((_) => controller = null);
},
child: const Text('Open Bottom Sheet'),
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: () => controller?.close(), // Close the bottom sheet if open
child: const Text('Close Bottom Sheet'),
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: () {
ScaffoldMessenger.of(context).hideCurrentSnackBar();
// Check if the bottom sheet is open and show a corresponding message
if (controller != null) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Bottom Sheet is open'),
),
);
} else {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Bottom Sheet is closed'),
),
);
}
},
child: const Text('Check if Bottom Sheet is Open'),
),
],
),
),
);
}
}