如何在页面加载时打开脚手架的抽屉?

时间:2018-09-26 13:33:24

标签: dart flutter material-design

登录到我们的Flutter应用程序将打开一个仪表板,该仪表板具有一个带有抽屉的,装有菜单项的支架。

我想执行一些A / B测试,即在页面加载时打开抽屉,或者至少使加载时立即打开的抽屉动画。

我知道Scaffold.of(context).openDrawer(),但是我不确定将代码放在哪里,以便它在build()方法之后立即运行。我也不知道在抽屉或脚手架上会在抽屉打开时加载的任何字段。

感谢您的时间和帮助。

3 个答案:

答案 0 :(得分:3)

第一帧加载后,您需要等待。

    _onLayoutDone(_) {
       //your logic here

    }

    @override
    void initState() {
      WidgetsBinding.instance.addPostFrameCallback(_onLayoutDone);
      super.initState();
    }

我写了一篇关于此的文章,如果需要,可以看一下:https://medium.com/@diegoveloper/flutter-widget-size-and-position-b0a9ffed9407

答案 1 :(得分:1)

我使用Timer完成了工作。完成build()方法后,请确保使用以下代码,以便您具有有效的上下文。

Timer(Duration(seconds: 3), () => Scaffold.of(context).openDrawer());

上面的代码使您可以更好地控制确切的时间。当您想显示打开的抽屉时。

答案 2 :(得分:0)

存储状态变量以隐藏和显示抽屉-isDrawerBeingShown

基于状态变量切换抽屉状态。默认情况下将其设置为false,因此将首次显示。

void _showDrawer(BuildContext context) async必须标记为异步,以便在构建方法之后运行。

创建showDrawerUtility方法以在需要时按需显示抽屉。

编辑:

使用GlobalKey

GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey();


class MainScreen extends StatefulWidget {

  MainScreen({Key key }) : super(key: key);

  @override
  State<MainScreen> createState() => new MainScreenState();
}

class MainScreenState extends State<MainScreen> {
  bool isDrawerBeingShown;

  @override
  void initState() {
    super.initState();
    isDrawerBeingShown = false;
    _showDrawer(context);
  }

  void _showDrawer(BuildContext context) async {
    if(!isDrawerBeingShown) {
     _scaffoldKey.currentState.openDrawer();
      setState(() => isDrawerBeingShown = true);
    }
  }
 @override
  Widget build(BuildContext context) { // build method goes here}
}