Josip Domazet
Josip Domazet

Reputation: 2880

[Flutter]: FAB for only one bottom tab

I have a BottomAppBar that has a FloatingActionButton. However, I only want this button to be seen in one particular screen. In the best case, I'd like to add this button only when the user clicks on that particular screen.

I've found that you can add a FAB like this:

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(),
    );

However, as you can see this Scaffold is shared by all the screens that can be selected in the bottomNavigationBar. How do I add a FAB only for a particular screen?

I'd like the FAB to be embedded into the bottomNavigationBar so I do not want to add a plain button to that particular screen. Thanks.

Upvotes: 0

Views: 334

Answers (4)

om_prakash
om_prakash

Reputation: 70

The answer by @Josip Domazet is absolutely right, but it can be achieved with shorter workaround instead of creating different Scaffold, using conditional operator as

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

Upvotes: 1

Josip Domazet
Josip Domazet

Reputation: 2880

Turns out the solution was actually quite simple and I was overthinking stuff. I have a variable that keeps track of the currently open screen. So I simply added this little logic to the mother screen that hosts the bottomNavigationBar:

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

return Scaffold(
  ...,
  bottomNavigationBar: buildBottomNavigationBar(),
);

Upvotes: 0

Nazmul Hasan
Nazmul Hasan

Reputation: 265

Wrap that specific screen with scaffold again and use fab on that screen only.

Upvotes: 0

Tasnuva Tavasum oshin
Tasnuva Tavasum oshin

Reputation: 4750

Use Stack In your Specific Tab and Add FAB at the bottom :

Example :

    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),
            ),
          )
    )
    
    ])

Upvotes: 0

Related Questions