Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reload or call some function initState() in flutter while using pop

I am trying to run some method when user click back or I use Navigator.pop() in second screen.

I have two screens.

  1. Setting screen
  2. Edit screen

After editing I pop user to first second. Now in first screen I use SharedPreference. But I need to re run a method when user comes back to 1st screen. How can I do this?

like image 692
Hkm Sadek Avatar asked Oct 14 '19 14:10

Hkm Sadek


People also ask

How do you call a function again and again in flutter?

In flutter we can make our own recurring method using Timer. periodic() method. The Timer. periodic() methods enable us to call a function or statement after a particular given time again and again.

What does initState do in flutter?

The initState() is a method that is called when an object for your stateful widget is created and inserted inside the widget tree. It is basically the entry point for the Stateful Widgets.

How do I go back and refresh the previous page in flutter?

pushNamed(context, '/page2'). then((_) { // This block runs when you have returned back to the 1st Page from 2nd. setState(() { // Call setState to refresh the page. }); }); (In your 2nd page): Use this code to return back to the 1st page.


1 Answers

While navigating to Edit screen from Settings screen, use this (inside your Settings screen)

Navigator.pushNamed(context, "/editScreen").then((_) {
  // you have come back to your Settings screen 
  yourSharedPreferenceCode();
});

If you only want to run this code on some event that happened on your Edit screen, you can make use of pop method inside Edit screen like

Navigator.pop(context, true); // pass true value

And above code should be:

Navigator.pushNamed(context, "/editScreen").then((value) {
  if (value) // if true and you have come back to your Settings screen 
    yourSharedPreferenceCode();
});

Edit:

async-await would look something like:

bool value = await Navigator.pushNamed(context, "/editScreen");
if (value) // if true and you have come back to your Settings screen 
  yourSharedPreferenceCode();
like image 57
CopsOnRoad Avatar answered Sep 21 '22 21:09

CopsOnRoad