NavigationBar class
Material 3 Navigation Bar component.
Learn more about NavigationBar on the Flutter YouTube channel.
Navigation bars offer a persistent and convenient way to switch between primary destinations in an app.
This widget does not adjust its size with the ThemeData.visualDensity.
The MediaQueryData.textScaler does not adjust the size of this widget but rather the size of the Tooltips displayed on long presses of the destinations.
The style for the icons and text are not affected by parent DefaultTextStyles or IconThemes but rather controlled by parameters or the NavigationBarThemeData.
This widget holds a collection of destinations (usually NavigationDestinations).
This example shows a NavigationBar as it is used within a Scaffold widget. The NavigationBar has three NavigationDestination widgets and the initial selectedIndex is set to index 0. The onDestinationSelected callback changes the selected item's index and displays a corresponding widget in the body of the Scaffold.
To see it in action, copy and run this code snippet on DartPad.
import 'package:material_ui/material_ui.dart';
/// Flutter code sample for [NavigationBar].
void main() => runApp(const NavigationBarApp());
class NavigationBarApp extends StatelessWidget {
const NavigationBarApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(home: NavigationExample());
}
}
class NavigationExample extends StatefulWidget {
const NavigationExample({super.key});
@override
State<NavigationExample> createState() => _NavigationExampleState();
}
class _NavigationExampleState extends State<NavigationExample> {
int currentPageIndex = 0;
@override
Widget build(BuildContext context) {
final ThemeData theme = Theme.of(context);
return Scaffold(
bottomNavigationBar: NavigationBar(
onDestinationSelected: (int index) {
setState(() {
currentPageIndex = index;
});
},
indicatorColor: Colors.amber,
selectedIndex: currentPageIndex,
destinations: const <Widget>[
NavigationDestination(
selectedIcon: Icon(Icons.home),
icon: Icon(Icons.home_outlined),
label: 'Home',
),
NavigationDestination(
icon: Badge(child: Icon(Icons.notifications_sharp)),
label: 'Notifications',
),
NavigationDestination(
icon: Badge(label: Text('2'), child: Icon(Icons.messenger_sharp)),
label: 'Messages',
),
],
),
body: <Widget>[
/// Home page
Card(
shadowColor: Colors.transparent,
margin: const .all(8.0),
child: SizedBox.expand(
child: Center(
child: Text('Home page', style: theme.textTheme.titleLarge),
),
),
),
/// Notifications page
const Padding(
padding: .all(8.0),
child: Column(
children: <Widget>[
Card(
child: ListTile(
leading: Icon(Icons.notifications_sharp),
title: Text('Notification 1'),
subtitle: Text('This is a notification'),
),
),
Card(
child: ListTile(
leading: Icon(Icons.notifications_sharp),
title: Text('Notification 2'),
subtitle: Text('This is a notification'),
),
),
],
),
),
/// Messages page
ListView.builder(
reverse: true,
itemCount: 2,
itemBuilder: (BuildContext context, int index) {
if (index == 0) {
return Align(
alignment: .centerRight,
child: Container(
margin: const .all(8.0),
padding: const .all(8.0),
decoration: BoxDecoration(
color: theme.colorScheme.primary,
borderRadius: .circular(8.0),
),
child: Text(
'Hello',
style: theme.textTheme.bodyLarge!.copyWith(
color: theme.colorScheme.onPrimary,
),
),
),
);
}
return Align(
alignment: .centerLeft,
child: Container(
margin: const .all(8.0),
padding: const .all(8.0),
decoration: BoxDecoration(
color: theme.colorScheme.primary,
borderRadius: .circular(8.0),
),
child: Text(
'Hi!',
style: theme.textTheme.bodyLarge!.copyWith(
color: theme.colorScheme.onPrimary,
),
),
),
);
},
),
][currentPageIndex],
);
}
}
This example showcases NavigationBar label behaviors. When tapping on one of the label behavior options, the labelBehavior of the NavigationBar will be updated.
To see it in action, copy and run this code snippet on DartPad.
import 'package:material_ui/material_ui.dart';
/// Flutter code sample for [NavigationBar].
void main() => runApp(const NavigationBarApp());
class NavigationBarApp extends StatelessWidget {
const NavigationBarApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(home: NavigationExample());
}
}
class NavigationExample extends StatefulWidget {
const NavigationExample({super.key});
@override
State<NavigationExample> createState() => _NavigationExampleState();
}
class _NavigationExampleState extends State<NavigationExample> {
int currentPageIndex = 0;
NavigationDestinationLabelBehavior labelBehavior = .alwaysShow;
@override
Widget build(BuildContext context) {
return Scaffold(
bottomNavigationBar: NavigationBar(
labelBehavior: labelBehavior,
selectedIndex: currentPageIndex,
onDestinationSelected: (int index) {
setState(() {
currentPageIndex = index;
});
},
destinations: const <Widget>[
NavigationDestination(icon: Icon(Icons.explore), label: 'Explore'),
NavigationDestination(icon: Icon(Icons.commute), label: 'Commute'),
NavigationDestination(
selectedIcon: Icon(Icons.bookmark),
icon: Icon(Icons.bookmark_border),
label: 'Saved',
),
],
),
body: Center(
child: Column(
mainAxisAlignment: .center,
children: <Widget>[
Text('Label behavior: ${labelBehavior.name}'),
const SizedBox(height: 10),
OverflowBar(
spacing: 10.0,
overflowAlignment: .center,
overflowSpacing: 10.0,
children: <Widget>[
ElevatedButton(
onPressed: () {
setState(() {
labelBehavior =
NavigationDestinationLabelBehavior.alwaysShow;
});
},
child: const Text('alwaysShow'),
),
ElevatedButton(
onPressed: () {
setState(() {
labelBehavior =
NavigationDestinationLabelBehavior.onlyShowSelected;
});
},
child: const Text('onlyShowSelected'),
),
ElevatedButton(
onPressed: () {
setState(() {
labelBehavior =
NavigationDestinationLabelBehavior.alwaysHide;
});
},
child: const Text('alwaysHide'),
),
],
),
],
),
),
);
}
}
This example shows a NavigationBar within a main Scaffold widget that's used to control the visibility of destination pages. Each destination has its own scaffold and a nested navigator that provides local navigation. The example's NavigationBar has four NavigationDestination widgets with different color schemes. Its onDestinationSelected callback changes the selected destination's index and displays a corresponding page with its own local navigator and scaffold - all within the body of the main scaffold. The destination pages are organized in a Stack and switching destinations fades out the current page and fades in the new one. Destinations that aren't visible or animating are kept Offstage.
To see it in action, copy and run this code snippet on DartPad.
import 'package:material_ui/material_ui.dart';
/// Flutter code sample for [NavigationBar] with nested [Navigator] destinations.
void main() {
runApp(const MaterialApp(home: Home()));
}
class Home extends StatefulWidget {
const Home({super.key});
@override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> with TickerProviderStateMixin<Home> {
static const List<Destination> allDestinations = <Destination>[
Destination(0, 'Teal', Icons.home, Colors.teal),
Destination(1, 'Cyan', Icons.business, Colors.cyan),
Destination(2, 'Orange', Icons.school, Colors.orange),
Destination(3, 'Blue', Icons.flight, Colors.blue),
];
late final List<GlobalKey<NavigatorState>> navigatorKeys;
late final List<GlobalKey> destinationKeys;
late final List<AnimationController> destinationFaders;
late final List<Widget> destinationViews;
int selectedIndex = 0;
AnimationController buildFaderController() {
return AnimationController(
vsync: this,
duration: const Duration(milliseconds: 300),
)..addStatusListener((AnimationStatus status) {
if (status.isDismissed) {
setState(() {}); // Rebuild unselected destinations offstage.
}
});
}
@override
void initState() {
super.initState();
navigatorKeys = List<GlobalKey<NavigatorState>>.generate(
allDestinations.length,
(int index) => GlobalKey(),
).toList();
destinationFaders = List<AnimationController>.generate(
allDestinations.length,
(int index) => buildFaderController(),
).toList();
destinationFaders[selectedIndex].value = 1.0;
final CurveTween tween = CurveTween(curve: Curves.fastOutSlowIn);
destinationViews = allDestinations.map<Widget>((Destination destination) {
return FadeTransition(
opacity: destinationFaders[destination.index].drive(tween),
child: DestinationView(
destination: destination,
navigatorKey: navigatorKeys[destination.index],
),
);
}).toList();
}
@override
void dispose() {
for (final AnimationController controller in destinationFaders) {
controller.dispose();
}
super.dispose();
}
@override
Widget build(BuildContext context) {
return NavigatorPopHandler(
onPopWithResult: (void result) {
final NavigatorState navigator =
navigatorKeys[selectedIndex].currentState!;
navigator.pop();
},
child: Scaffold(
body: SafeArea(
top: false,
child: Stack(
fit: .expand,
children: allDestinations.map((Destination destination) {
final int index = destination.index;
final Widget view = destinationViews[index];
if (index == selectedIndex) {
destinationFaders[index].forward();
return Offstage(offstage: false, child: view);
} else {
destinationFaders[index].reverse();
if (destinationFaders[index].isAnimating) {
return IgnorePointer(child: view);
}
return Offstage(child: view);
}
}).toList(),
),
),
bottomNavigationBar: NavigationBar(
selectedIndex: selectedIndex,
onDestinationSelected: (int index) {
setState(() {
selectedIndex = index;
});
},
destinations: allDestinations.map<NavigationDestination>((
Destination destination,
) {
return NavigationDestination(
icon: Icon(destination.icon, color: destination.color),
label: destination.title,
);
}).toList(),
),
),
);
}
}
class Destination {
const Destination(this.index, this.title, this.icon, this.color);
final int index;
final String title;
final IconData icon;
final MaterialColor color;
}
class RootPage extends StatelessWidget {
const RootPage({super.key, required this.destination});
final Destination destination;
Widget _buildDialog(BuildContext context) {
return AlertDialog(
title: Text('${destination.title} AlertDialog'),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: const Text('OK'),
),
],
);
}
@override
Widget build(BuildContext context) {
final TextStyle headlineSmall = Theme.of(context).textTheme.headlineSmall!;
final ButtonStyle buttonStyle = ElevatedButton.styleFrom(
backgroundColor: destination.color,
foregroundColor: Colors.white,
visualDensity: .comfortable,
padding: const .symmetric(vertical: 12, horizontal: 16),
textStyle: headlineSmall,
);
return Scaffold(
appBar: AppBar(
title: Text('${destination.title} RootPage - /'),
backgroundColor: destination.color,
foregroundColor: Colors.white,
),
backgroundColor: destination.color[50],
body: Center(
child: Column(
mainAxisSize: .min,
children: <Widget>[
ElevatedButton(
style: buttonStyle,
onPressed: () {
Navigator.pushNamed(context, '/list');
},
child: const Text('Push /list'),
),
const SizedBox(height: 16),
ElevatedButton(
style: buttonStyle,
onPressed: () {
showDialog<void>(
context: context,
useRootNavigator: false,
builder: _buildDialog,
);
},
child: const Text('Local Dialog'),
),
const SizedBox(height: 16),
ElevatedButton(
style: buttonStyle,
onPressed: () {
showDialog<void>(
context: context,
useRootNavigator:
true, // ignore: avoid_redundant_argument_values
builder: _buildDialog,
);
},
child: const Text('Root Dialog'),
),
const SizedBox(height: 16),
Builder(
builder: (BuildContext context) {
return ElevatedButton(
style: buttonStyle,
onPressed: () {
showBottomSheet(
context: context,
builder: (BuildContext context) {
return Container(
padding: const .all(16),
width: double.infinity,
child: Text(
'${destination.title} BottomSheet\n'
'Tap the back button to dismiss',
style: headlineSmall,
softWrap: true,
textAlign: .center,
),
);
},
);
},
child: const Text('Local BottomSheet'),
);
},
),
],
),
),
);
}
}
class ListPage extends StatelessWidget {
const ListPage({super.key, required this.destination});
final Destination destination;
@override
Widget build(BuildContext context) {
const int itemCount = 50;
final ColorScheme colorScheme = Theme.of(context).colorScheme;
final ButtonStyle buttonStyle = OutlinedButton.styleFrom(
shape: RoundedRectangleBorder(
borderRadius: .circular(8),
side: BorderSide(color: colorScheme.onSurface.withValues(alpha: 0.12)),
),
foregroundColor: destination.color,
fixedSize: const Size.fromHeight(64),
textStyle: Theme.of(context).textTheme.headlineSmall,
);
return Scaffold(
appBar: AppBar(
title: Text('${destination.title} ListPage - /list'),
backgroundColor: destination.color,
foregroundColor: Colors.white,
),
backgroundColor: destination.color[50],
body: SizedBox.expand(
child: ListView.builder(
itemCount: itemCount,
itemBuilder: (BuildContext context, int index) {
return Padding(
padding: const .symmetric(vertical: 4, horizontal: 8),
child: OutlinedButton(
style: buttonStyle.copyWith(
backgroundColor: WidgetStatePropertyAll<Color>(
Color.lerp(
destination.color[100],
Colors.white,
index / itemCount,
)!,
),
),
onPressed: () {
Navigator.pushNamed(context, '/text');
},
child: Text('Push /text [$index]'),
),
);
},
),
),
);
}
}
class TextPage extends StatefulWidget {
const TextPage({super.key, required this.destination});
final Destination destination;
@override
State<TextPage> createState() => _TextPageState();
}
class _TextPageState extends State<TextPage> {
late final TextEditingController textController;
@override
void initState() {
super.initState();
textController = TextEditingController(text: 'Sample Text');
}
@override
void dispose() {
textController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final ThemeData theme = Theme.of(context);
return Scaffold(
appBar: AppBar(
title: Text('${widget.destination.title} TextPage - /list/text'),
backgroundColor: widget.destination.color,
foregroundColor: Colors.white,
),
backgroundColor: widget.destination.color[50],
body: Container(
padding: const .all(32.0),
alignment: .center,
child: TextField(
controller: textController,
style: theme.primaryTextTheme.headlineMedium?.copyWith(
color: widget.destination.color,
),
decoration: InputDecoration(
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(
color: widget.destination.color,
width: 3.0,
),
),
),
),
),
);
}
}
class DestinationView extends StatefulWidget {
const DestinationView({
super.key,
required this.destination,
required this.navigatorKey,
});
final Destination destination;
final Key navigatorKey;
@override
State<DestinationView> createState() => _DestinationViewState();
}
class _DestinationViewState extends State<DestinationView> {
@override
Widget build(BuildContext context) {
return Navigator(
key: widget.navigatorKey,
onGenerateRoute: (RouteSettings settings) {
return MaterialPageRoute<void>(
settings: settings,
builder: (BuildContext context) {
switch (settings.name) {
case '/':
return RootPage(destination: widget.destination);
case '/list':
return ListPage(destination: widget.destination);
case '/text':
return TextPage(destination: widget.destination);
}
assert(false);
return const SizedBox();
},
);
},
);
}
}
See also:
- Inheritance
-
- Object
- DiagnosticableTree
- Widget
- StatelessWidget
- NavigationBar
Constructors
- Creates a Material 3 Navigation Bar component.
Properties
- animationDuration → Duration?
-
Determines the transition time for each destination as it goes between
selected and unselected.
final
- backgroundColor → Color?
-
The color of the NavigationBar itself.
final
-
destinations
→ List<
Widget> -
The list of destinations (usually NavigationDestinations) in this
NavigationBar.
final
- elevation → double?
-
The elevation of the NavigationBar itself.
final
- hashCode → int
-
The hash code for this object.
no setterinherited
- height → double?
-
The height of the NavigationBar itself.
final
- indicatorColor → Color?
-
The color of the indicatorShape when this destination is selected.
final
- indicatorShape → ShapeBorder?
-
The shape of the selected indicator.
final
- key → Key?
-
Controls how one widget replaces another widget in the tree.
finalinherited
- labelBehavior → NavigationDestinationLabelBehavior?
-
Defines how the destinations' labels will be laid out and when they'll
be displayed.
final
- labelPadding → EdgeInsetsGeometry?
-
The padding around the NavigationDestination.label widget.
final
-
labelTextStyle
→ WidgetStateProperty<
TextStyle?> ? -
The text style of the label.
final
- maintainBottomViewPadding → bool
-
Specifies whether the underlying SafeArea should maintain the bottom
MediaQueryData.viewPadding instead of the bottom MediaQueryData.padding.
final
-
onDestinationSelected
→ ValueChanged<
int> ? -
Called when one of the destinations is selected.
final
-
overlayColor
→ WidgetStateProperty<
Color?> ? -
The highlight color that's typically used to indicate that
the NavigationDestination is focused, hovered, or pressed.
final
- runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
- selectedIndex → int
-
Determines which one of the destinations is currently selected.
final
- shadowColor → Color?
-
The color used for the drop shadow to indicate elevation.
final
- surfaceTintColor → Color?
-
The color used as an overlay on backgroundColor to indicate elevation.
final
Methods
-
build(
BuildContext context) → Widget -
Describes the part of the user interface represented by this widget.
override
-
createElement(
) → StatelessElement -
Creates a StatelessElement to manage this widget's location in the tree.
inherited
-
debugDescribeChildren(
) → List< DiagnosticsNode> -
Returns a list of DiagnosticsNode objects describing this node's
children.
inherited
-
debugFillProperties(
DiagnosticPropertiesBuilder properties) → void -
Add additional properties associated with the node.
inherited
-
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
toDiagnosticsNode(
{String? name, DiagnosticsTreeStyle? style}) → DiagnosticsNode -
Returns a debug representation of the object that is used by debugging
tools and by DiagnosticsNode.toStringDeep.
inherited
-
toString(
{DiagnosticLevel minLevel = DiagnosticLevel.info}) → String -
A string representation of this object.
inherited
-
toStringDeep(
{String prefixLineOne = '', String? prefixOtherLines, DiagnosticLevel minLevel = DiagnosticLevel.debug, int wrapWidth = 65}) → String -
Returns a string representation of this node and its descendants.
inherited
-
toStringShallow(
{String joiner = ', ', DiagnosticLevel minLevel = DiagnosticLevel.debug}) → String -
Returns a one-line detailed description of the object.
inherited
-
toStringShort(
) → String -
A short, textual description of this widget.
inherited
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited