Home > Software design >  How to handle *CUSTOM* back button on Flutter with *BOTTOM NAVIGATION BAR*?
How to handle *CUSTOM* back button on Flutter with *BOTTOM NAVIGATION BAR*?

Time:05-04

I have a bottom navigation bar in flutter:

class _HomeState extends State<Home> {
 int index = 1;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      bottomNavigationBar: CurvedNavigationBar(
        index: index,
        items: barItems,
        onTap: (index) {
          setState(() {
          this.index = index;
        });
...
...
 );
  }
}

where barItems is a list of widgets.

One of the screens of the navigation bar is routing to a different screen, which a would like to make a custom back button to the previous screen:

 GridView.count(
        shrinkWrap: true,
          crossAxisCount: 2,
          mainAxisSpacing: 10,
          crossAxisSpacing: 10,
          padding: const EdgeInsets.all(5),
          children: _allSongs.map((currentSong) {
            return InkWell(
              onTap: ()=> Navigator.pushReplacementNamed(context, '/singleSong', arguments: currentSong),
              ...
              ...)

On that new screen I have a cutom back button:

child: Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
            margin: const EdgeInsets.only(left: 10),
            child: IconButton(
                onPressed: () {
                  **Navigator.of(context).pop();**
                  
                },
                icon: const Icon(Icons.arrow_back_ios))),
        

I added all the necassary routes as well, but when that button is clicked all I get is a blank black screen.

Any help? Thanks

CodePudding user response:

In the new page, you are using Navigator.pushReplacementNamed(context, '/singleSong', arguments: currentSong) to go to new page. At the same time, it also replaces the main route ("/") with the new route ("/singleSong").

If you try to go back from there, there would not be any route available for you as you have made "/singleSong" as the main route.

so, instead of

Navigator.pushReplacementNamed(context, '/singleSong', arguments: currentSong)

you should use

Navigator.pushNamed(context, '/singleSong', arguments: currentSong)
  • Related