在集团模式下打开抽屉

时间:2019-05-20 07:39:35

标签: flutter flutter-layout bloc

几天后,我无法解决

我在我的应用上实现了简单的blok模式,我想通过按DrawerFloatingActionButton图标来打开Icons.menu,但我的代码为

Scaffold.of(context).openDrawer();

不工作

我的代码:

return Scaffold(
  body: BlocBuilder<HomeEvent, HomeState>(
      bloc: _homeBloc,
      builder: (BuildContext context, HomeState state) {
        Scaffold.of(context).openDrawer(); //<---- don't work
        if (state is HandleDrawerMenuClick) {
          _onWidgetDidBuild(() {
            Scaffold.of(context).openDrawer(); //<---- don't work
            _showToast(context); //<---- work fine
          });
        }
        return WillPopScope(
          onWillPop: () {
            customPop(context);
          },
          child: Directionality(
            textDirection: TextDirection.rtl,
            child: Scaffold(
              primary: true,
              appBar: ApplicationToolbar(homeBloc: _homeBloc),
              floatingActionButton: FloatingActionButton(
                child: Icon(Icons.add),
                onPressed: () {
                  Scaffold.of(context).openDrawer(); //<---- don't work
                  _showToast(context); //<---- work fine
                },
              ),
              floatingActionButtonLocation:
              FloatingActionButtonLocation.centerDocked,
              bottomNavigationBar: AppBottomNavigationBar(),
              drawer: AppDrawer(),
              body: _fragments[_currentIndex],
            ),
          ),
        );
      }),
);

HomeEvent类:

class HomeEvent extends Equatable{
  HomeEvent([List props = const []]) : super(props);
}

class OnDrawerMenuClicked extends HomeEvent {

  @override
  String toString() => 'OnDrawerMenuClicked clicked';
}

class OnDrawerMenuItemsClicked extends HomeEvent {
  var onItem = 1;

  OnDrawerMenuItemsClicked({this.onItem});

  @override
  String toString() => 'OnDrawerMenuItemsClicked clicked';
}

HomeState类:

class HomeState extends Equatable{
  HomeState([List props = const[]]):super(props);
}

class HomeInitial extends HomeState{
  @override
  String toString()=>'HomeInitial';
}
class HandleDrawerMenuClick extends HomeState{
  @override
  String toString()=>'HandleDrawerMenuClick';
}

1 个答案:

答案 0 :(得分:1)

以BLoC模式打开抽屉过于复杂。您需要使用构建器小部件来包装FloatingActionButton,该小部件将为打开抽屉提供正确的上下文,并且无需使用Bloc模式即可打开抽屉。

使用FAB打开抽屉的详细代码

 return Scaffold(
      appBar:  AppBar(title: Text('Drawer FAB'),),
      drawer: Drawer(child: Text('drawer content'),),
      floatingActionButton: Builder( builder:(context) => 
                          FloatingActionButton(child: Icon(Icons.add), 
                              onPressed: (){ 
                                  Scaffold.of(context).openDrawer();
                              },
                          )),
);