首页 > 解决方案 > Flutter 无法添加抽屉

问题描述

我发现在最新版本的颤振中添加抽屉很困难。我的代码看起来像这样

class HomeScreen extends StatelessWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: buildAppbar(),
      body: const Body(),
      drawer: DrawerSlide(),
    ); 
  }

  AppBar buildAppbar() {
    return AppBar(
      elevation: 3,
      leading: GestureDetector(
        child: Padding(
          padding: const EdgeInsets.all(12.0),
          child: SvgPicture.asset('assets/icons/menu.svg', width: 10, height: 10, fit: BoxFit.fitWidth,),
        ),
        onTap: () => Scaffold.of(context).openDrawer(),
      ),
    );
  }
}

Scaffold.of(context).openDrawe() 中显示上下文未定义的错误。在我更新颤振之前它一直有效,但在新的颤振中我认为它不起作用。

标签: flutter

解决方案


The buildAppbar method requires context as a positional argument :

AppBar buildAppbar(BuildContext context) {
    return AppBar(
      elevation: 3,
      leading: GestureDetector(
        child: Padding(
          padding: const EdgeInsets.all(12.0),
          child: SvgPicture.asset('assets/icons/menu.svg', width: 10, height: 10, fit: BoxFit.fitWidth,),
        ),
        onTap: () => Scaffold.of(context).openDrawer(),
      ),
    );
  }

use it like :

return Scaffold(
      appBar: buildAppbar(context),
      body: const Body(),
      drawer: DrawerSlide(),
    );

推荐阅读