Home > OS >  How to run InitState() upon back button in flutter?
How to run InitState() upon back button in flutter?

Time:12-05

I have a two pages, in one page, i open Hive box but when I navigate to second page, the dispose() method runs and closes the Hive box. but the problem is, when i click on 'Back' button, the initState doesnt rerun on the first page, so I couldn't open the box again through initState.

here is the code on First page,

@override
  initState() {
    super.initState();
    Hive.openBox<boxModel>('customTable');
  }
  @override
  void dispose() {
    Hive.close();
    super.dispose();
  }

Here is the back in appbar in second page,

AppBar(
      leadingWidth: 100,
       leading: IconButton(
        onPressed: () => Navigator.of(context).pop(),
        icon: Icon(
          Icons.arrow_back,
          color: AppTheme.colors.greyFontColor,
        ),
        ),
       backgroundColor: AppTheme.colors.appBarColor,
       elevation: 0,
       iconTheme: IconThemeData(color: AppTheme.colors.greyFontColor),)

so is there a way to re run to the initState upon the back button pressed on second page.

Thanks for any help..

CodePudding user response:

# To run an InitState() method when the back button is pressed in Flutter, you can use the WillPopScope widget. This widget provides a callback that is called when the user presses the back button. You can use this callback to run the InitState() method.

# Here's an example of how you can use the WillPopScope widget 
# to run the InitState() method when the back button is pressed:


Copy code
WillPopScope(
  onWillPop: () async {
    // Run your InitState() method here
    return true;
  },
  child: Scaffold(
    // Your app's content goes here
  ),
);

# In this example, the WillPopScope widget is a parent to the Scaffold widget, which is the root widget for the screen. The onWillPop callback is called when the user presses the back button, and it returns true to indicate that the back button press should be handled by the app.

# You can use this approach to run the InitState() method when the back button is pressed, and to prevent the app from closing or navigating back to the previous screen.

CodePudding user response:

try (context as Element).reassemble(); try this snippet refresh and build widgets again in current screen flutter.

Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) =>PreviousPage() ,)); for previous using navigator.

CodePudding user response:

I don't think that dispose runs when you push a new route, at least not as long as there is a back button to go back, but anyways if you just want to open the box again you can add this to your Navigator.push

Navigator.of(context)
.push(MaterialPageRoute(
  builder: (context) =>  SecondPage(),
)).then((_) {
  Hive.openBox<boxModel>('customTable');
});
  • Related