No N
No N

Reputation: 159

Flutter app crashes when back button is pressed

My app's homepage has a search bar. When the search bar is tapped, the user is redirected to the search page as follow:

class _HomeAppBarState extends State<HomeAppBar> {
  @override
  Widget build(BuildContext context) {
    return AppBar(
        backgroundColor: Colors.white,

        leading: IconButton(
            icon: Icon(Icons.account_circle, color: Colors.black) , onPressed: () => Scaffold.of(context).openDrawer()
        ),

        title: TextField(
          onTap: () {Navigator.push(context, MaterialPageRoute(builder: (context) => Search()));},
          decoration: InputDecoration(
            prefixIcon: Icon(Icons.search, color: Colors.black),
            hintText: "Search...",
          ),
        )
    );
  }
}

In the search page. The appbar has a back button and then the back button is pressed I want the user is taken back to the homepage. I tried to do by using Navigator.pop as follows:


class _SearchAppBarState extends State<SearchAppBar> {
  @override
  Widget build(BuildContext context) {
    return AppBar(
        backgroundColor: Colors.white,

        leading: IconButton(
            icon: Icon(Icons.arrow_back, color: Colors.black) , onPressed: () => Navigator.pop(context)
        ),

        title: TextField(
          autofocus: true,
          //onChanged: Do Stuff here.
          decoration: InputDecoration(
            prefixIcon: Icon(Icons.search, color: Colors.black),
            hintText: "Search App Bar...",
          ),
        )
    );
  }
}

But I got very weird results when the back button is pressed.

When the back button pressed at search page.

The screen stays like this, when I click back button once more it stays at search page.

Upvotes: 2

Views: 3271

Answers (1)

Harshvardhan Joshi
Harshvardhan Joshi

Reputation: 3193

  • try using automaticallyImplyLeading: true, only on the search bar widget. instead of providing the back button and handling the navigation stack manually.

  • Remove manual or automatic Back Button from root widget.

Also, Wrap the root widget with WillPopScope :

build(BuildContext context) {
  return WillPopScope(
    onWillPop: () async => false,
     child: //you root widget,
    ); 
}

WillPopScope widget will ignore any back press events to pop out the 'root' widget, Hence no issues like the ones you are having.

For more details on WillPopScope visit this article: https://codingwithjoe.com/flutter-navigation-how-to-prevent-navigation/

Regarding the problem of screen view,

If the HomePage is the parent/root widget of the app, when popping the HomeWidget it should lead to a black screen. But it seems the distorted screen view is a bug of the emulator.

Upvotes: 4

Related Questions