【问题标题】:[Flutter]: FAB for only one bottom tab[Flutter]:FAB 仅用于一个底部选项卡
【发布时间】:2022-08-16 01:17:17
【问题描述】:

我有一个BottomAppBar,它有一个FloatingActionButton。但是,我只希望在一个特定屏幕中看到此按钮。在最好的情况下,我希望仅在用户单击该特定屏幕时添加此按钮。

我发现您可以像这样添加FAB

return Scaffold(
      extendBodyBehindAppBar: true,
      extendBody: true,
      floatingActionButtonLocation: FloatingActionButtonLocation.endDocked,
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          ...
        },
        child:  const Icon(
          Icons.add_sharp,
          color: Color(0xFFFFFFFF),
        ),
      ),
      body: Center(
        child: _widgetOptions.elementAt(_selectedIndex),
      ),
      bottomNavigationBar: buildBottomNavigationBar(),
    );

但是,正如您所见,Scaffold 由所有可以在bottomNavigationBar 中选择的屏幕共享。如何仅为特定屏幕添加FAB

我希望将 FAB 嵌入到 bottomNavigationBar 中,因此我不想在该特定屏幕上添加普通按钮。谢谢。

    标签: flutter dart flutter-layout flutter-bottomnavigation


    【解决方案1】:

    在您的特定选项卡中使用堆栈并在底部添加 FAB:

    例子 :

        Stack(
    children[
        
        Container(height: double.infinity,
        width: double.infinity) // for full screen 
        
        Position(
        bottom : 10,
        left: 150,
        right : 150,
        child: FloatingActionButton(
                onPressed: () {
                  ...
                },
                child:  const Icon(
                  Icons.add_sharp,
                  color: Color(0xFFFFFFFF),
                ),
              )
        )
        
        ])
    

    【讨论】:

      【解决方案2】:

      再次用脚手架包裹该特定屏幕并仅在该屏幕上使用 fab 。

      【讨论】:

      • 包裹那个屏幕确实显示了一个新的工厂。但是,该工厂位于先前脚手架的现有bottomNavigationBar 下方。我需要工厂成为bottomNavigationBar 的一部分。这是因为我需要实现像这里这样的缺口效果:stackoverflow.com/questions/51251722/…
      【解决方案3】:

      原来解决方案实际上很简单,我想太多了。我有一个变量来跟踪当前打开的屏幕。所以我简单地将这个小逻辑添加到承载bottomNavigationBar 的母屏中:

      if (_selectedIndex==1){
        // Other screen that needs the FAB
        return Scaffold(
          ...,
          floatingActionButton: FloatingActionButton(
              ....
          ),
          bottomNavigationBar: buildBottomNavigationBar(),
        );
      }
      
      return Scaffold(
        ...,
        bottomNavigationBar: buildBottomNavigationBar(),
      );
      

      【讨论】:

        【解决方案4】:

        @Josip Domazet 的答案是绝对正确的,但它可以通过更短的解决方法来实现,而不是创建不同的 Scaffold,使用条件运算符作为

        floatingActionButton: _selectedIndex==1
              ? FloatingActionButton(....) : const SizedBox.shrink(),
        

        【讨论】:

          猜你喜欢
          • 2016-09-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-25
          • 1970-01-01
          • 1970-01-01
          • 2014-07-14
          • 2012-12-17
          • 1970-01-01
          相关资源
          最近更新 更多