我要开通Drawer
以编程方式而不是通过滑动它,如何禁用该滑动功能(抽屉的触摸功能)
最佳答案
drawerEnableOpenDragGesture
在脚手架上为假。
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
// this to prevent the default sliding behaviour
drawerEnableOpenDragGesture: false,
drawer: Drawer(),
appBar: AppBar(
leading: Builder(builder: (context) => // Ensure Scaffold is in context
IconButton(
icon: Icon(Icons.menu),
onPressed: () => Scaffold.of(context).openDrawer()
),
),
)
)
);
}
}
Scaffold.of(context)
以编程方式打开抽屉您必须确保(感谢 Krolaw !)进行调用的上下文知道 Scaffold。一种干净的方法是将按钮包装在构建器中。
我已经编辑了答案以包含一个最小的完整工作示例。
Scaffold 是一个实现 Material 设计原则的小部件,因此请注意,要能够调用此方法,您需要
import 'package:flutter/material.dart';
并且您的小部件需要有一个 MaterialApp 作为祖先。Codepen demo
与许多 Flutter 事物一样,还有其他解决方案可以确保 Scaffold 处于上下文中。
错误消息是 IMO 中 Flutter 框架的最佳功能之一,请允许我谦虚地建议始终彻底阅读它们并探索它们指向的文档。
例如,这是在正确上下文之外调用 openDrawer 时得到的错误消息的一部分:
Scaffold.of() called with a context that does not contain a Scaffold.
No Scaffold ancestor could be found starting from the context that was passed to Scaffold.of(). This usually happens when the context provided is from the same StatefulWidget as that whose build function actually creates the Scaffold widget being sought.
There are several ways to avoid this problem. The simplest is to use a Builder to get a context that is "under" the Scaffold. For an example of this, please see the documentation for Scaffold.of(): https://api.flutter.dev/flutter/material/Scaffold/of.html
A more efficient solution is to split your build function into several widgets. This introduces a new context from which you can obtain the Scaffold. In this solution, you would have an outer widget that creates the Scaffold populated by instances of your new inner widgets, and then in these inner widgets you would use Scaffold.of().
A less elegant but more expedient solution is assign a GlobalKey to the Scaffold, then use the key.currentState property to obtain the ScaffoldState rather than using the Scaffold.of() function.
关于Flutter:如何以编程方式打开 Drawer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57748170/