Skip to main content

Installation

Add the package

flutter pub add navbar_router

Import the package

import 'package:flutter/material.dart';
import 'package:navbar_router/navbar_router.dart';

Using navbar_router

  1. Declare your routes
  final Map<int, Map<String, Widget>> _routes = const {
0: {
'/': HomeFeeds(),
FeedDetail.route: FeedDetail(),
},
1: {
'/': ProductList(),
ProductDetail.route: ProductDetail(),
ProductComments.route: ProductComments(),
},
2: {
'/': UserProfile(),
ProfileEdit.route: ProfileEdit(),
},
3: {
'/': Settings(),
},
};
  1. Declare NavbarItems
  List<NavbarItem> items = [
NavbarItem(Icons.home_outlined, 'Home',
backgroundColor: mediumPurple,
selectedIcon: Icon(
Icons.home,
size: 26,
)),
NavbarItem(Icons.shopping_bag_outlined, 'Products',
backgroundColor: Colors.orange,
selectedIcon: Icon(
Icons.shopping_bag,
size: 26,
)),
NavbarItem(Icons.person_outline, 'Me',
backgroundColor: Colors.teal,
selectedIcon: Icon(
Icons.person,
size: 26,
)),
];
  1. Add NavbarRouter Widget to your app

The widget requires List<DestinationRouter> destinations, List<NavbarItem> destinations and Widget Function(BuildContext) errorBuilder as required parameters. And each DestinationRouter has multiple destinations and is associated with a NavbarItem And since we are aiming for handling complex nested routes and destinations, the possibility of error is high. So we need to also specify an errorBuilder to gracefully handle an invalid route.

NavbarRouter(
errorBuilder: (context) {
return const Center(child: Text('Error 404 Page Not Found'));
},
onBackButtonPressed: (isExiting) {
return isExiting;
},
destinationAnimationCurve: Curves.fastOutSlowIn,
destinationAnimationDuration: 600,
decoration:
NavbarDecoration(navbarType: BottomNavigationBarType.shifting),
destinations: [
for (int i = 0; i < items.length; i++)
DestinationRouter(
navbarItem: items[i],
destinations: [
for (int j = 0; j < _routes[i]!.keys.length; j++)
Destination(
route: _routes[i]!.keys.elementAt(j),
widget: _routes[i]!.values.elementAt(j),
),
],
initialRoute: _routes[i]!.keys.first,
),
],
);

And that is all with this setup your NavbarRouter should be up and running.

class MyApp extends StatelessWidget {

Widget build(BuildContext context) {
return MaterialApp(
title: 'NavbarRouter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: NavbarRouter(
errorBuilder: (context) {
return const Center(child: Text('Error 404 Page Not Found'));
},
destinations: [
for (int i = 0; i < items.length; i++)
DestinationRouter(
navbarItem: items[i],
destinations: [
for (int j = 0; j < _routes[i]!.keys.length; j++)
Destination(
route: _routes[i]!.keys.elementAt(j),
widget: _routes[i]!.values.elementAt(j),
),
],
initialRoute: _routes[i]!.keys.first,
),
],
),
);
}
}

Heres how the output of the above code sample will look.

demo