Search code examples
flutterdartflutter-layoutflutter-bottomnavigation

Bottom Navigation bar with back feature


I want to use the Bottom Navigation bar to move between pages the Bottom Navigation bar is exist on every page, and clicking the back button directs me to the home page

My main

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int selectedPage = 2;
  final _pageOptions = [const PageOne(),const  PageTwo(),const PageThree()];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _pageOptions[selectedPage],
      bottomNavigationBar: BottomNavigationBar(
        items:const  [
          BottomNavigationBarItem(icon: Icon(Icons.add), label: ""),
          BottomNavigationBarItem(icon: Icon(Icons.abc), label: ""),
          BottomNavigationBarItem(icon: Icon(Icons.access_alarm), label: ""),
        ],
        onTap: (int index) {
          setState(() {
            selectedPage = index;
          });
        },
      ),
    );
  }
}

by using This code I can move between pages but when clicking The back button I get out of the program.

Thanks in advance.


Solution

  • Wrap your Scaffold with a WillPopScope as shown below;

    class _MyHomePageState extends State<MyHomePage> {
      int selectedPage = 2;
      final _pageOptions = [const PageOne(),const  PageTwo(),const PageThree()];
    
      @override
      Widget build(BuildContext context) {
        return WillPopScope(
          onWillPop: () async {
                 setState(() {
                  selectedPage = 0;
                });
            return false;
          },
          child: Scaffold(
            body: _pageOptions[selectedPage],
            bottomNavigationBar: BottomNavigationBar(
              items: const [
                BottomNavigationBarItem(icon: Icon(Icons.add), label: ""),
                BottomNavigationBarItem(icon: Icon(Icons.abc), label: ""),
                BottomNavigationBarItem(icon: Icon(Icons.access_alarm), label: ""),
              ],
              onTap: (int index) {
                setState(() {
                  selectedPage = index;
                });
              },
            ),
          ),
        );
      }
    }