Home > Software engineering >  How to handle flutter bottom navigation bar when back button is pressed to go to the HomeScreen
How to handle flutter bottom navigation bar when back button is pressed to go to the HomeScreen

Time:11-28

I am working on a bottom navigation bar, but I am not getting perfectly on back press to home screen.

if i select more then two navigation button from bottom navigationbar view items then when i press back button it'll close the app.

i want to return back to home when pressed on the back button.

This is my code.

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());


class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  static const String _title = 'Flutter Code Sample';

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: _title,
      home: MyStatefulWidget(),
    );
  }
}


class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({Key? key}) : super(key: key);

  @override
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}


class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  int _selectedIndex = 0;
  static const TextStyle optionStyle =
      TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
  static const List<Widget> _widgetOptions = <Widget>[
    Text(
      'Index 0: Home',
      style: optionStyle,
    ),
    Text(
      'Index 1: Business',
      style: optionStyle,
    ),
    Text(
      'Index 2: School',
      style: optionStyle,
    ),
  ];

  void _onItemTapped(int index) {
    setState(() {
      _selectedIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('BottomNavigationBar Sample'),
      ),
      body: Center(
        child: _widgetOptions.elementAt(_selectedIndex),
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: 'Home',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.business),
            label: 'Business',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.school),
            label: 'School',
          ),
        ],
        currentIndex: _selectedIndex,
        selectedItemColor: Colors.amber[800],
        onTap: _onItemTapped,
      ),
    );
  }
}

CodePudding user response:

The default behavior of the back button is to close the route that you have popped on top. In this case you have not popped a new route. You just showed a widget at the new index. So there is nothing to close.

You have the following options to go back on the back button:

  1. On BottomNavigationBar tap, show a new route with Navigator.of(context).push(...). Then the back button will close it. But with this approach you will clutter your app with new screens on each bottom navigation, and those screens would not preserve state.

  2. Use WillPopScope widget to intercept the back button event and do your custom action as shown here: https://stackoverflow.com/a/44637374/11382675 But with this approach you must manually keep the navigation stack somewhere. This will get unscaleable as you add new screens.

But I think that the real problem is the navigation design itself. It is now a habit that each tab keeps its own history of navigation. So when you switch tabs back and forth, each tab will still allow you to go back in its own history independently of other tabs' history.

To achieve this, the first step is to decide that switching tabs should not be undoable by the back button. And the letter steps can be found here: https://medium.com/flutter-community/flutter-navigation-maintaining-tab-state-while-navigating-bottomnavigationbar-6009fbceb59c

  • Related