Closing Drawer on Bottom Navigation Bar click, Flutter - flutter

I want to close my Drawer widget every time the user presses a button in the Bottom Navigation Bar, but can't quite figure this thing out. The way my setup of the BNB is set now is that the current state of all screen is remembered through out the app (using an IndexedStack), but I want to close the Drawer if it is opened in any of the screens before the BNB button press. Each of my screens have their own Drawers and AppBars, so I can't make one Drawer inside the BNB (or I can and I can dynamically change them with a switch case when a specific Screen is clicked on BUT then the Drawer will cover the Bottom Navigation Bar etc.), but I want to make it work like this for now. So here is the code with some comments inside to explain things:
Bottom Navigation Bar:
class BottomNavBar extends StatefulWidget {
static const String id = 'bottom_navbar_screen';
#override
_BottomNavBarState createState() => _BottomNavBarState();
}
class _BottomNavBarState extends State<BottomNavBar> {
int _selectedIndex = 0;
/// list of screen that will render inside the BNB
List<Navigation> _items = [
Navigation(
widget: Screen1(), navigationKey: GlobalKey<NavigatorState>()),
Navigation(
widget: Screen2(), navigationKey: GlobalKey<NavigatorState>()),
Navigation(
widget: Screen3(), navigationKey: GlobalKey<NavigatorState>()),
Navigation(
widget: Screen4(), navigationKey: GlobalKey<NavigatorState>()),
];
/// function that renders components based on selected one in the BNB
void _onItemTapped(int index) {
if (index == _selectedIndex) {
_items[index]
.navigationKey
.currentState
.popUntil((route) => route.isFirst);
} else {
setState(() {
_selectedIndex = index;
});
}
/// when the index is selected, on the button press do some actions
switch (_selectedIndex) {
case 0:
// Do some actions
break;
case 1:
// Do some actions
break;
case 2:
// Do some actions
break;
case 3:
// Do some actions
break;
}
}
/// navigation Tab widget for a list of all the screens and puts them in a Indexed Stack
Widget _navigationTab(
{GlobalKey<NavigatorState> navigationKey, Widget widget}) {
return Navigator(
key: navigationKey,
onGenerateRoute: (routeSettings) {
return MaterialPageRoute(builder: (context) => widget);
},
);
}
#override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async {
final isFirstRouteInCurrentTab =
!await _items[_selectedIndex].navigationKey.currentState.maybePop();
if (isFirstRouteInCurrentTab) {
if (_selectedIndex != 0) {
_onItemTapped(1);
return false;
}
}
/// let system handle back button if we're on the first route
return isFirstRouteInCurrentTab;
},
child: Scaffold(
body: IndexedStack(
index: _selectedIndex,
children: _items
.map((e) => _navigationTab(
navigationKey: e.navigationKey, widget: e.widget))
.toList(),
),
bottomNavigationBar: BottomNavigationBar(
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
label: 'Screen 1,
),
BottomNavigationBarItem(
label: 'Screen 2,
),
BottomNavigationBarItem(
label: 'Screen 3,
),
BottomNavigationBarItem(
label: 'Screen 4,
),
],
currentIndex: _selectedIndex,
showUnselectedLabels: true,
onTap: _onItemTapped,
),
),
);
}
}
Let's say all 4 screens are the same and they have their own AppBar and Drawer:
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
drawer: Drawer(), // so this is what I want to close on BNB button press in each of the 4 screens
appBar: AppBar( // each screen has its own app bar
title: Text('Screens 1-4'),
),
body: Text('Body of Screens 1-4'),
);
}
So because each of the screens have their own AppBars and Drawers, the Drawer doesn't render over the Bottom Navigation Bar, so my BNB buttons can be clicked. If I put one Drawer for all Screens inside the BNB, then you can't click the BNB unless you close the Drawer first, which is not something I'm looking for right now.
So, my final question is, how do I close each of the Screens Drawers (if they are previously opened that is) when you press the BottomnavigationBar? (i.e. I am on Screen 1, I open the Drawer, then I press on Screen 2 in the BNB and I want to pop()/close the Drawer in Screen 1 before I navigate to Screen 2.)
Thanks in advance for your help!

A good way to do this is to use a GlobalKey for your scaffold.
So, for all your scaffolds, you define them using:
class SomeClass extends StatelessWidget {
final scaffoldKey = GlobalKey<ScaffoldState>()
Widget build(BuildContext context) {
Scaffold(
backgroundColor: Colors.white,
drawer: Drawer(), // so this is what I want to close on BNB button press in each of the 4 screens
appBar: AppBar( // each screen has its own app bar
title: Text('Screens 1-4),
),
body: Text('Body of Screens 1-4),
key: scaffoldKey,
),
);
}
}
And then, you can pass this key to your BottomNavigationBar.
In your BottomNavigationBar, you can have all the scaffoldKeys, and in the onItemTap function:
void _onItemTapped(int index) {
for (scaffoldKey in scaffoldKeys) {
// If the drawer is open
if (scaffoldKey.currentState.isDrawerOpen) {
// Closes the drawer
scaffoldKey.currentState?.openEndDrawer();
}
}
if (index == _selectedIndex) {
_items[index]
.navigationKey
.currentState
.popUntil((route) => route.isFirst);
} else {
setState(() {
_selectedIndex = index;
});
}
/// when the index is selected, on the button press do some actions
switch (_selectedIndex) {
case 0:
// Do some actions
break;
case 1:
// Do some actions
break;
case 2:
// Do some actions
break;
case 3:
// Do some actions
break;
}
}
It's up to you to find the best way of passing around the keys. You could for example define them in a Widgets that contains both the bottom navigation bar and the different scaffolds, and pass it down as parameters. You could use State Management... whatever fits your use case.
Here is what your code could look like:
class BottomNavBar extends StatefulWidget {
static const String id = 'bottom_navbar_screen';
#override
_BottomNavBarState createState() => _BottomNavBarState();
}
class _BottomNavBarState extends State<BottomNavBar> {
int _selectedIndex = 0;
late final List<GlobalKey<ScaffoldState>> scaffoldKeys;
/// list of screen that will render inside the BNB
late final List<Navigation> _items;
#override
initState() {
super.initState()
scaffoldKeys = [GlobalKey<ScaffoldState>(), GlobalKey<ScaffoldState>(), GlobalKey<ScaffoldState>(), GlobalKey<ScaffoldState>()];
_items = [
Navigation(
widget: Screen1(scaffoldKey: scaffoldKeys[0]), navigationKey: GlobalKey<NavigatorState>()),
Navigation(
widget: Screen2(scaffoldKey: scaffoldKeys[1]), navigationKey: GlobalKey<NavigatorState>()),
Navigation(
widget: Screen3(scaffoldKey: scaffoldKeys[2]), navigationKey: GlobalKey<NavigatorState>()),
Navigation(
widget: Screen4(scaffoldKey: scaffoldKeys[3]), navigationKey: GlobalKey<NavigatorState>()),
];
}
/// function that renders components based on selected one in the BNB
void _onItemTapped(int index) {
for (scaffoldKey in scaffoldKeys) {
// If the drawer is open
if (scaffoldKey.currentState.isDrawerOpen) {
// Closes the drawer
scaffoldKey.currentState?.openEndDrawer();
}
}
if (index == _selectedIndex) {
_items[index]
.navigationKey
.currentState
.popUntil((route) => route.isFirst);
} else {
setState(() {
_selectedIndex = index;
});
}
/// when the index is selected, on the button press do some actions
switch (_selectedIndex) {
case 0:
// Do some actions
break;
case 1:
// Do some actions
break;
case 2:
// Do some actions
break;
case 3:
// Do some actions
break;
}
}
/// navigation Tab widget for a list of all the screens and puts them in a Indexed Stack
Widget _navigationTab(
{GlobalKey<NavigatorState> navigationKey, Widget widget, GlobalKey<ScaffoldState> scaffoldKey}) {
return Navigator(
key: navigationKey,
onGenerateRoute: (routeSettings) {
return MaterialPageRoute(builder: (context) => widget);
},
);
}
#override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async {
final isFirstRouteInCurrentTab =
!await _items[_selectedIndex].navigationKey.currentState.maybePop();
if (isFirstRouteInCurrentTab) {
if (_selectedIndex != 0) {
_onItemTapped(1);
return false;
}
}
/// let system handle back button if we're on the first route
return isFirstRouteInCurrentTab;
},
child: Scaffold(
body: IndexedStack(
index: _selectedIndex,
children: _items
.map((e) => _navigationTab(
navigationKey: e.navigationKey, widget: e.widget))
.toList(),
),
bottomNavigationBar: BottomNavigationBar(
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
label: 'Screen 1,
),
BottomNavigationBarItem(
label: 'Screen 2,
),
BottomNavigationBarItem(
label: 'Screen 3,
),
BottomNavigationBarItem(
label: 'Screen 4,
),
],
currentIndex: _selectedIndex,
showUnselectedLabels: true,
onTap: _onItemTapped,
),
),
);
}
}
And you screens:
class Screen1 extends StatelessWidget {
final GlobalKey<ScaffoldState> scaffoldKey;
Screen1({required this.scaffoldKey});
#override
Widget build(BuildContext context) {
return Scaffold(
key: scaffoldKey,
backgroundColor: Colors.white,
drawer: Drawer(), // so this is what I want to close on BNB button press in each of the 4 screens
appBar: AppBar( // each screen has its own app bar
title: Text('Screens 1-4'),
),
body: Text('Body of Screens 1-4'),
);
}
}
I changed the list of screens _items to a late variables so you can pass the scaffoldKeys to them when declaring them.

Related

How can I prevent android back button from closing the app only when you are at the base last window in a navigation stack in flutter?

I'm trying to build a custom bottom navigation system using the CupertinoTabBar and its working decently well, but I've come across a problem with the backbitten on Android.
When I have windows open, back button properly closes my screens (navigates to the previous screen) but when I'm at the very last screen, if you press back the whole app will close.
I'd like to try to prevent this
Is there a good way for me to detect when I am at my base window and prevent this in the WillPopScope area?
Heres my bottom navigation bar code as it stands
class MarkBottomNav2 extends StatefulWidget {
#override
State<MarkBottomNav2> createState() => _MarkBottomNavState2();
}
class _MarkBottomNavState2 extends State<MarkBottomNav2> {
final GlobalKey<NavigatorState> firstTabNavKey = GlobalKey<NavigatorState>();
final GlobalKey<NavigatorState> secondTabNavKey = GlobalKey<NavigatorState>();
final GlobalKey<NavigatorState> thirdTabNavKey = GlobalKey<NavigatorState>();
final GlobalKey<NavigatorState> fourthTabNavKey = GlobalKey<NavigatorState>();
final GlobalKey<NavigatorState> fifthTabNavKey = GlobalKey<NavigatorState>();
late CupertinoTabController tabController;
int index = 0;
#override
void initState() {
// TODO: implement initState
super.initState();
tabController = CupertinoTabController(initialIndex: 0);
}
#override
Widget build(BuildContext context) {
//making a list of the keys
final listOfKeys = [
firstTabNavKey,
secondTabNavKey,
thirdTabNavKey,
fourthTabNavKey,
fifthTabNavKey,
];
List homeScreenList = [
NewsArea(),
Area2(),
Area3(),
Area4(),
Area5()
];
return WillPopScope(
onWillPop: () async {
return !await listOfKeys[tabController.index].currentState!.maybePop();
},
child: CupertinoTabScaffold(
controller: tabController, //set tabController here
tabBar: CupertinoTabBar(
items: [
///this is where we are setting aur bottom ICONS
BottomNavigationBarItem(
icon: Icon(FontAwesome5.newspaper),
label: 'News',
),
BottomNavigationBarItem(icon: Icon(Icons.format_list_bulleted), label: 'Area 2'),
BottomNavigationBarItem(icon: Icon(Icons.mail_outline_outlined), label: 'Area 3'),
BottomNavigationBarItem(icon: Icon(Icons.alternate_email), label: 'Area 4'),
BottomNavigationBarItem(icon: Icon(Icons.more_horiz), label: 'Area 5'),
],
activeColor: Color.fromRGBO(26, 70, 128, 1),
inactiveColor: Color.fromRGBO(26, 70, 128, 0.3),
iconSize:20,
// currentIndex: pageIndex,
),
tabBuilder: (
context,
index,
) {
return CupertinoTabView(
navigatorKey: listOfKeys[
index], //set navigatorKey here which was initialized before
builder: (context) {
return homeScreenList[index];
},
);
},
),
);
}
}
You can try with the below code and use this first page where from page exit
DateTime currentBackPressTime;
#override
Widget build(BuildContext context) {
return Scaffold(
...
body: WillPopScope(child: getBody(), onWillPop: onWillPop),
);
}
Future<bool> onWillPop() {
DateTime now = DateTime.now();
if (currentBackPressTime == null ||
now.difference(currentBackPressTime) > Duration(seconds: 2)) {
currentBackPressTime = now;
Fluttertoast.showToast(msg: exit_warning);
return Future.value(false);
}
return Future.value(true);
}

Flutter - how to hide global bottom navigation bar?

On one of the pages, nested inside one of bottom navigation bar pages I want to hide the bottom navigation bar, which is set as global. To be clear, I'm talking about this bar:
I can't just use Navigator.pushNamed because I'm creating viewModel and passing arguments in this way:
openConversation(BuildContext context) async {
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => ChangeNotifierProvider(
create: (context) => ConversationVM(...),
child: ConversationScreen(
(...)
),
),
));
}
I've tried to set the Scaffold parameter bottomNavigationBar to null, but without effect, I need to resolve that problem somewhere higher.
Nav bar snippet:
class NavigationBar extends StatefulWidget {
static String id = 'navigation_screen';
#override
State<StatefulWidget> createState() {
return _NavigationBarState();
}
}
class _NavigationBarState extends State<NavigationBar> {
//track the index of our currently selected tab
int _currentIndex = 0;
//st of widgets that we want to render
final List<Object> _children = [
PostedQueries(),
];
#override
Widget build(BuildContext context) {
return Scaffold(
//body of our scaffold which is the widget that gets displayed between our app bar and bottom navigation bar.
body: _children[_currentIndex], // new
bottomNavigationBar: BottomNavigationBar(
onTap: onTabTapped,
// new
currentIndex: _currentIndex,
// new
unselectedItemColor: Colors.grey,
selectedItemColor: Colors.deepOrange,
items: [
BottomNavigationBarItem(
icon: new Icon(Icons.home),
label: ('Home'),
),
],
),
);
}
void onTabTapped(int index) {
setState(() {
_currentIndex = index;
});
}
}

How to navigate to one of the pages of BottomNavigationBar by clicking on a button present in the page in Flutter?

I have a bottom navigation bar in my flutter app which is used to show different pages. I need to click on a button in one of the pages to navigate to another which can also be navigated through the bottom navigation bar. To keep the state of the page i have used IndexedStack widget. also i highlight which page i am currently at.
How to do so.
Here is the code.
class IndexPage extends StatefulWidget {
#override
_IndexPageState createState() => _IndexPageState();
}
class _IndexPageState extends State<IndexPage>
with SingleTickerProviderStateMixin {
final ValueNotifier<int> pageNumberNotifier = ValueNotifier<int>(0);
final List<Widget> _widgets = <Widget>[
Page1(),
Page2(),
Page3(),
];
#override
void dispose() {
super.dispose();
pageNumberNotifier.dispose();
}
#override
Widget build(BuildContext context) {
return ValueListenableBuilder(
valueListenable: pageNumberNotifier,
builder: (BuildContext context, int pageNumber, Widget child) {
return SafeArea(
child: Scaffold(
body: IndexedStack(
index: pageNumberNotifier.value,
children: _widgets,
),
bottomNavigationBar: BottomNavigationBar(
showUnselectedLabels: true,
currentIndex: pageNumber,
onTap: (index) => pageNumberNotifier.value = index,
items: <BottomNavigationBarItem>[
bottomNavigationBarItem(
iconString: 'page1', index: 0, title: 'Page1'),
bottomNavigationBarItem(
iconString: 'page2', index: 1, title: 'Page2'),
bottomNavigationBarItem(
iconString: 'page3', index: 2, title: 'Page3'),
],
),
),
);
});
}
BottomNavigationBarItem bottomNavigationBarItem(
{String iconString, int index, String title}) {
//shows the icons and also highlights the icon of the current page based on the current index.
}
}
Here is the page that contains the button
class Page1 extends StatelessWidget {
#override
Widget build(BuildContext context) {
...
onTap(){
// go to Page3 and also highlight Page3 icon in the bottom navigation bar
}
...
}
}
Use a GlobalKey
GlobalKey<_IndexPageState> key = GlobalKey();
make a function inside _IndexPageState:
void setPage(int page) {
pageNumberNotifier.value = page;
}
call this method from anywhere with:
key.currentState.setPage(0);

Change tab controller index, and wait for the TabView in Flutter

I am making a simple tab bar based app with Flutter. It uses CupertinoTabScaffold and CupertinoTabBar. Each CupertinoTabView has its own WebView.
In the first TabView, a button is placed that if clicked the selected tab will be changed to the next one to load a CupertinoTabView containing a WebView widget, then navigate to the certain website URL (note that the URL is not written on WebView:initialURL, but retrieved from the first tab).
The problem is that when clicking the button, while the selected tab is changed, WebView does not load a specific URL because the WebView controller is not assigned.
How to make the app 'wait' for the new CupertinoTabView widget to be fully loaded?
If I run the app, the error is the following:
Unhandled Exception: NoSuchMethodError: The method 'navigateTo' was called on null.
This seems because when clicking the button to execute the following code, before the line tabController.index = tabIndex will take effect, keyWebPage.curentState.navigateTo (which is null yet) is called.
tabController.index = tabIndex;
keyWebPage.currentState.navigateTo(url); //executed 'before' the new TabView initialization
I suspect the reason for this problem, but couldn't figure out how to solve it.
main.dart
final GlobalKey<PageWebState> keyWebPage = GlobalKey();
class _MyHomePageState extends State<MyHomePage> {
final CupertinoTabController tabController = CupertinoTabController();
int _currentTabIndex = 0;
WebPage pageWeb;
#override
void initState() {
super.initState();
pageWeb = new PageWeb(
this,
key: keyWebPage,
);
}
void navigateTab(int tabIndex, String url) {
setState(() {
_currentTabIndex = tabIndex;
tabController.index = tabIndex;
// HERE is the error occurring part
keyWebPage.currentState.navigateTo(url);
});
}
#override
Widget build(BuildContext context) {
final Widget scaffold = CupertinoTabScaffold(
controller: tabController,
tabBar: CupertinoTabBar(
currentIndex: _currentTabIndex,
onTap: (index) {
setState(() {
_currentTabIndex = index;
});
},
items: const <BottomNavigationBarItem>[
const BottomNavigationBarItem(icon: const Icon(Icons.home), title: Text('Start')),
const BottomNavigationBarItem(icon: const Icon(Icons.web), title: Text('Webpage')),
],
),
tabBuilder: (context, index) {
CupertinoTabView _viewWidget;
switch (index) {
case 0:
_viewWidget = CupertinoTabView(
builder: (context) {
return Center(
child: CupertinoButton(
child: Text('Navigate'),
onPressed: () {
navigateTab(1, 'https://stackoverflow.com/');
},
),
);
},
);
break;
case 1:
_viewWidget = CupertinoTabView(
builder: (context) {
return pageWeb;
},
);
break;
}
return _viewWidget;
},
);
return scaffold;
}
}
WebPage.dart
final Completer<WebViewController> _controller = Completer<WebViewController>();
class PageWeb extends StatefulWidget {
final delegate;
final ObjectKey key;
PageWeb(this.delegate, this.key);
#override
PageWebState createState() {
return PageWebState();
}
}
void navigateTo(String url) { //Function that will be called on main.dart
controller.future.then((controller) => controller.loadUrl(url));
}
class PageWebState extends State<PageWeb> {
#override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: Text("Test"),
),
child: SafeArea(
child: Container(
child: new WebView(
key: widget.key,
initialUrl: "https://www.google.com/",
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (WebViewController webViewController) {
_controller.complete(webViewController);
},
))));
}
}
Please note that using constructor to passing variables is not in consideration because the URL will be changed and the clicking the button can be more than once.

How to reset the navigator when switching between cupertino tabs

I'm trying to setup a multipage app in Flutter, where the bottom tabbar contains the four most used pages, including a "More" button. The more button shows a page with links to other pages. When clicking on a page, I want this page to replace the "More" page, so a new navigation stack is created. However, when switching to another tab and then back to the "more" tab, the navigation state is remembered. This means I'm not seeing the "More" page, but the page I left when switching tabs. I want to show the "More" page everytime the user clicks on the "More" tab.
I've tried using the pushReplacement method of the Navigator, so when the user clicks on a more-page, he can't navigate back to the list of more pages. However, when switching tabs, the more page is now never shown, because it's replaced.
I've also tried adjusting the tab callback method, to pop all views and return the navigator to the MoreScreen. However, this left me with an error in the console: setState() or markNeedsBuild() called during build..
The tab screen:
class TabScreen extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return TabScreenState();
}
}
class TabScreenState extends State<TabScreen> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: WillPopScope(
// Prevent swipe popping of this page. Use explicit exit buttons only.
onWillPop: () => Future<bool>.value(true),
child: CupertinoTabScaffold(
tabBar: CupertinoTabBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
title: Text('Artikelen'),
),
BottomNavigationBarItem(
icon: Icon(Icons.message),
title: Text('Activiteiten'),
),
BottomNavigationBarItem(
icon: Icon(Icons.speaker_group),
title: Text('Training'),
),
BottomNavigationBarItem(
icon: Icon(Icons.more),
title: Text('Meer'),
),
],
),
tabBuilder: (BuildContext context, int index) {
assert(index >= 0 && index <= 3);
switch (index) {
case 0:
return CupertinoTabView(
builder: (BuildContext context) {
Navigator.of(context).popUntil((route) => route.isFirst);
return ArticleListScreen();
},
defaultTitle: 'Artikelen',
);
break;
case 1:
return CupertinoTabView(
builder: (BuildContext context) => ActivityListScreen(),
defaultTitle: 'Activiteiten',
);
break;
case 2:
return CupertinoTabView(
builder: (BuildContext context) => ArticleListScreen(),
defaultTitle: 'Training',
);
break;
case 3:
return CupertinoTabView(
builder: (BuildContext context) {
Navigator.of(context).popUntil((route) => route.isFirst);
return MoreScreen();
},
defaultTitle: 'Meer',
);
break;
}
return null;
},
),
),
);
}
}
And the MoreScreen which holds a button to go to another page:
class MoreScreen extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return MoreScreenState();
}
}
class MoreScreenState extends State<MoreScreen> {
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
color: ThemeData.dark().accentColor,
alignment: AlignmentDirectional(0.0, 0.0),
child: MaterialButton(
child: Text('PUSH page'),
onPressed: () => {
Navigator.of(context).push(MaterialPageRoute(builder: (context) => ArticleListScreen()))
},
)
),
);
}
}
I expect the navigation stack to reset everytime I switch tabs, but now I have to do that manually using:
Navigator.of(context).popUntil((route) => route.isFirst);
This leads to the error message: setState() or markNeedsBuild() called during build. after pushing a new page in a tab and then switching tabs.