Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
If you need a modal (showModalBottomSheet) but you have a bottomnavigationbar and the modal needs to be on top of the bottomnavigationbar, use the userootnavigator = true property of showModalBottomSheet.
// This example on Dartpad:
// https://dartpad.dev/cbbfed060a664b6fdaf4229b02cd1add
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: AppScaffold(title: 'showModalBottomSheet with BottomNavigationBar'),
);
}
}
class AppScaffold extends StatefulWidget {
AppScaffold({Key key, this.title}) : super(key: key);
final String title;
@override
_AppScaffoldState createState() => _AppScaffoldState();
}
class _AppScaffoldState extends State<AppScaffold> {
int _currentPage = 0;
void _selectPage(int newPage) {
setState(() {
_currentPage = newPage;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title, style: TextStyle(fontFamily: 'ProductSans')),
),
body: Stack(children: [_offstageNav(0), _offstageNav(1)]),
bottomNavigationBar: _navBar(),
);
}
Widget _navBar() => BottomNavigationBar(
items: [_navBarItem(0), _navBarItem(1)],
currentIndex: _currentPage,
onTap: (i) => _selectPage(i),
);
BottomNavigationBarItem _navBarItem(int i) => BottomNavigationBarItem(
icon: Icon(Icons.stars),
label: ['useRootNavigator = false', 'useRootNavigator = true'][i],
);
Widget _offstageNav(int i) => Offstage(
offstage: _currentPage != i,
child: Navigator(
onGenerateRoute: (routeSettings) => MaterialPageRoute(
builder: (_) {
if (_currentPage == 0) {
return ButtomSheetPageWithoutUseRootNavigator();
} else {
return ButtomSheetPageWithUseRootNavigator();
}
},
),
),
);
}
class ButtomSheetPageWithoutUseRootNavigator extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: FlatButton(
color: Colors.blue,
child: Text('Show bottom sheet witht useRootNavigator = false'),
onPressed: () => showModalBottomSheet(
context: context,
builder: (_) => Container(
height: 200,
child: Text(
'Modal bottom sheet',
style: TextStyle(fontSize: 30),
),
),
),
),
);
}
}
class ButtomSheetPageWithUseRootNavigator extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: FlatButton(
color: Colors.blue,
child: Text('Show bottom sheet witht useRootNavigator = true'),
onPressed: () => showModalBottomSheet(
useRootNavigator:
true, //uncomment this to showModalBottomSheet ahead bottomnavigationbar
context: context,
builder: (_) => Container(
height: 200,
child: Text(
'Modal bottom sheet',
style: TextStyle(fontSize: 30),
),
),
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment