[Flutter/dart]onWillPop of willPopScope doesn't work
- M.R
- 2021年8月15日
- 読了時間: 1分
Overview
In flutter, if you don't want users to return to the previous page, you can wrap the widget with willPopScope and write a process that prevents users from returning at onWillPop. (See here for how to use it.)
However, even with this implementation, I can return normally. When I debug it, it seems that the method passed to onWillPop is not called in the first place.
Here describes how to deal with this case.
Cause
The cause seems to be that willPopScope was not at the root of the stack (that is, the source). In my app, I jumped from the login page to the main page with Navigator.push and put onWillPopScope there, so it seems that onWillPop was not called (reference)
Solution
In the case of a one-way transition like a login page, use pushReplacement or pushAndRemoveUntill so that the page is not left in the stack. (reference)
Navigator.of(context).pushReplacement(
MaterialPageRoute(builder: (BuildContext context) => MyHomePage())
)