0

With the current code, on click of back button, the app exits instead of moving to the previous page.

import 'package:curved_navigation_bar/curved_navigation_bar.dart';

class homeNav extends StatefulWidget {
  const homeNav({super.key});

  @override
  State<homeNav> createState() => _homeNavState();
}

class _homeNavState extends State<homeNav> {
  int currindex = 2;
  final screens = const [
    cart(),
    HomeScreen(),
    HomeScreen(),
    searchPage(),
    MyProfile(),
  ];

  @override
  Widget build(BuildContext context) {
    const items = <Widget>[
      Icon(Icons.shopping_cart,size: 30,color: Colors.white,),
      Icon(Icons.favorite,size: 30,color: Colors.white,),
      Icon(Icons.home,size: 30,color: Color.fromARGB(255, 255, 255, 255),),
      Icon(Icons.search,size: 30, color: Colors.white,),
      Icon(Icons.person,size: 30,color: Colors.white,),
    ];
    return Scaffold(
      extendBody: true,
      backgroundColor: Colors.transparent,
      bottomNavigationBar: currindex == 0
          ? null
          : CurvedNavigationBar(
              color: Color.fromARGB(234, 7, 123, 255),
              buttonBackgroundColor: Color.fromARGB(255, 11, 43, 99),

              backgroundColor: Colors.transparent,
              index: currindex,
              height: 60,
              items: items,
              onTap: (index) => setState(() => this.currindex = index),
            ),
      body: screens[currindex],
    );
  }
}

Dependency used: curved_navigation_bar

I have marked the bottomNavigationBar to be invisible for currindex==1 (Cart()) page.

I want the app to redirect to previous page on tap of back button.



Tried this answer from How to use BottomNavigationBar with Navigator?

But didnt work


import 'package:curved_navigation_bar/curved_navigation_bar.dart';


class homeNav extends StatefulWidget {
  const homeNav({super.key});

  @override
  State<homeNav> createState() => _homeNavState();
}

class _homeNavState extends State<homeNav> {
  int currindex = 2;
  final screens = const [
    cart(),
    HomeScreen(),
    HomeScreen(),
    searchPage(),
    MyProfile(),
  ];

  final GlobalKey<NavigatorState> _navigatorKey = GlobalKey<NavigatorState>();

  @override
  Widget build(BuildContext context) {
    const items = <Widget>[
      Icon(
        Icons.shopping_cart,
        size: 30,
        color: Colors.white,
      ),
      Icon(
        Icons.favorite,
        size: 30,
        color: Colors.white,
      ),
      Icon(
        Icons.home,
        size: 30,
        color: Color.fromARGB(255, 255, 255, 255),
      ),
      Icon(
        Icons.search,
        size: 30,
        color: Colors.white,
      ),
      Icon(
        Icons.person,
        size: 30,
        color: Colors.white,
      ),
    ];
    return SafeArea(
      child: Scaffold(
        extendBody: true,
        backgroundColor: Colors.transparent,
        bottomNavigationBar: currindex == 0
            ? null
            : CurvedNavigationBar(
                color: Color.fromARGB(234, 7, 123, 255),
                buttonBackgroundColor: Color.fromARGB(255, 11, 43, 99),
                backgroundColor: Colors.transparent,
                index: currindex,
                height: 60,
                items: items,
                // onTap: (index) => setState(() => this.currindex = index),
                onTap: _onTap,
              ),
        body: Navigator(key: _navigatorKey, onGenerateRoute: generateRoute),
        // bottomNavigationBar: _bottomNavigationBar(),
      ),
    );
  }

  _onTap(int tabIndex) {
    switch (tabIndex) {
      case 0:
        _navigatorKey.currentState?.pushReplacementNamed("cart");
        break;
      case 1:
        _navigatorKey.currentState?.pushReplacementNamed("home");
        break;
      case 2:
        _navigatorKey.currentState?.pushReplacementNamed("home");
        break;
      case 3:
        _navigatorKey.currentState?.pushReplacementNamed("search");
        break;
      case 4:
        _navigatorKey.currentState?.pushReplacementNamed("profile");
        break;
    }
    setState(
      () {
        currindex = tabIndex;
      },
    );
  }

  Route<dynamic> generateRoute(RouteSettings settings) {
    switch (settings.name) {
      case "home":
        return MaterialPageRoute(builder: (context) => HomeScreen());
      case "cart":
        return MaterialPageRoute(builder: (context) => cart());
      case "search":
        return MaterialPageRoute(builder: (context) => searchPage());
      case "profile":
        return MaterialPageRoute(builder: (context) => MyProfile());
      default:
        return MaterialPageRoute(builder: (context) => HomeScreen());
    }
  }
}

3 Answers3

0

Kartik

The pushReplacementNamed method basically clear the previous screen from stack and place new screen. Hence it become empty stack for screens. When back button hit you are out of app.

Try other push option and based on back navigate to those screen.

Here is official document on it.

https://api.flutter.dev/flutter/widgets/Navigator/pushReplacementNamed.html

Ankit Tale
  • 1,924
  • 4
  • 17
  • 30
0
    class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final list = [const Home(), const PayScreen()];
  int _selectedIndex = 0;

  void onTap(int index) {
    if (_selectedIndex != index) {
      setState(() {
        _selectedIndex = index;
      });
    }
  }

  final bottomNavigationBarItems = const [
    BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
    BottomNavigationBarItem(
        icon: Icon(Icons.account_balance_wallet), label: 'Pay Screen')
  ];

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: list[_selectedIndex],
        bottomNavigationBar: BottomNavigationBar(
            currentIndex: _selectedIndex,
            onTap: onTap,
            items: bottomNavigationBarItems
        ),
      ),
    );
  }
}

Then at home page

    class _HomePageState extends State<HomePage> {
....
 @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: IndexedStack(index: _selectedIndex, children: list),
        bottomNavigationBar: BottomNavigationBar(
          currentIndex: _selectedIndex,
          onTap: onTap,
          items: bottomNavigationBarItems,
        ),
      ),
    );
  }
}
Ankit Tale
  • 1,924
  • 4
  • 17
  • 30
0

Note: I don't encourage this approach. I recommend using go_router. Here is a link to a much suitable approach
You can also look for some simple approach that gives you basic understanding of go_router before using the "Suitable approach" i recommended

However, here's a solution for your situation. You can wrap your scaffold with a WillPopScope widget.

This will allow you to handle back button behavior. You can also make sure to use pushNamed if the current index is 2 (Home Page).

// Wrap your scaffold with a WillPopScope
WillPopScope(
  // Your SafeArea and Scaffold content here
  child: SafeArea(
    child: Scaffold(
      // ... your scaffold content ...
    ),
  ),
  // Define a callback to control back button usage
  onWillPop: () async {
    // You can define custom conditions to determine whether to allow the page to pop or perform a different action.
    return currindex == 2;
  },
);

 // modify your onTap method
_onTap(int tabIndex) {
  if (tabIndex == currindex) return;

  switch (tabIndex) {
    case 0:
      currindex == 2
          ? _navigatorKey.currentState?.pushNamed("cart")
          : _navigatorKey.currentState?.pushReplacementNamed("cart");
      break;
    case 1:
      currindex == 2
          ? _navigatorKey.currentState?.pushNamed("home")
          : _navigatorKey.currentState?.pushReplacementNamed("home");
      break;
    case 2:
      currindex == 2
          ? _navigatorKey.currentState?.pushNamed("home")
          : _navigatorKey.currentState?.pushReplacementNamed("home");
      break;
    case 3:
      currindex == 2
          ? _navigatorKey.currentState?.pushNamed("search")
          : _navigatorKey.currentState?.pushReplacementNamed("search");
      break;
    case 4:
      currindex == 2
          ? _navigatorKey.currentState?.pushNamed("profile")
          : _navigatorKey.currentState?.pushReplacementNamed("profile");
      break;
  }

  setState(() {
    currindex = tabIndex;
  });
}
THEODORE
  • 917
  • 10
  • 12