Flutter — Keep bottom navigation bar visible when navigating to another page
Case study
Sometimes keeping the bottom navigation always visible is crucial for a good user experience; a great example is the Facebook app!
So we’re going to implement the same effect with as little as 20 lines of code in Dart & Flutter.
Requirements
- Basic knowledge of mobile app development with Flutter
- That’s it!
I made a small Flutter package that can handle the whole process with ease.
Let’s get into it
After you create the project you need to add the package to it.
Depend on it
Add the following to your pubspec.yaml. Make sure to check for the latest version here
dependencies:
custom_navigator: ^0.2.0
Install it
$ flutter pub get
Import it
import ‘package:custom_navigator/custom_navigator.dart’;
The actual code
The case we’re building is pretty simple:
- Main screen
- Tab screen
- Details screen
Introducing CustomScaffold
It’s a stateful widget that uses the CustomNavigator to handle item transition of BottomNavigationBar with nested navigation while keeping the BottomNavigationBar visible!
How it works
The CustomScaffold widget automatically handles the transition to another page when you click on a tab. You should know that:
- Scaffold can’t be null
- BottomNavigationBar can’t be null
- Children can’t be null
- Number of BottomNavigationBar items == number of children (pages) in your CustomScaffold.
- The first page in children list will be taken in consideration while ignoring the body attribute in Scaffold.
- Children will be mapped to items in order such as: item1 => page1, item2 => page2
// Here’s the custom scaffold widget
// It takes a normal scaffold with mandatory bottom navigation bar
// and children who are your pages
return CustomScaffold(
scaffold: Scaffold(
bottomNavigationBar: BottomNavigationBar(
items: _items,
),
), // Children are the pages that will be shown by every click
// They should placed in order such as
// `page 0` will be presented when `item 0` in the
// [BottomNavigationBar] clicked.
children: <Widget>[
Page(‘0’),
Page(‘1’),
Page(‘2’),
], // Called when one of the [items] is tapped.
onItemTap: (index) {},
);
Let’s code!
Tab Page
This is the page of each tab in the bottom navigation.
Details screen
The screen we navigate to
Home screen
Let’s put it all together
Final result
The package’s still missing a great deal of features since it’s new, and may have some errors that I’m not aware of, so feel free to raise an issue on the github repo.
With ♥️