2

I have two pages I am navigating between. When navigating back, I want the first page to reload the data/rebuild itself, but it doesn't seem to be working. I read through the replied here but I still cannot get it to work. Here is what I have:

Navigation from first page to second page

InkWell(
 onTap: () async {
  await Navigator.push(
  context,
   MaterialPageRoute(
   builder: (context) =>
   AddChallengeUnitsPageWidget(),
   ),
  ).then((_) => setState(() {}));
 },
child: Icon(
Icons.add_circle,
 ),
),

Then coming back from the second page after a function runs (I need the update from this function to update the previous page)

onPressed: () async {
//I need the updated information from this function to display on the previous page
 await updateChallenge();
 Navigator.pop(context);
//I have tried removing this setState call and it did not fix the proplem.
 setState(() {});
},

Any idea why the state of the page is not being updated properly?

Dennis Ashford
  • 872
  • 2
  • 7
  • 21

2 Answers2

1

to return result from second page use Navigator.pop(context, result);

on first page make sure to add await and use WidgetsBinding.instance.addPostFrameCallback if setState does not work

var result = await Navigator.push( context, MaterialPageRoute( builder: (context) => AddChallengeUnitsPageWidget(), ), );

WidgetsBinding.instance.addPostFrameCallback((_) => setState((){}));

Punit
  • 11
  • 2
0

You should do it on the first screen, like so:

InkWell(
  onTap: () {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) =>
          AddChallengeUnitsPageWidget(),
      ),
    ).then((_) () async {
      final data = await fetchMyData();
      // since it's an async function,
      // you probably want to make sure
      // the state is mounted before running
      // setState
      setState(() {
        // update your state with data.
      });
    });
  },
  child: Icon(
    Icons.add_circle,
  ),
),
HTMHell
  • 5,761
  • 5
  • 37
  • 79
  • Unfortunately, I need inputted data on the second screen for the function. So running the function on the first screen isn't possible. – Dennis Ashford Mar 17 '23 at 18:43
  • 1
    You can pass the data using `Navigator.of(context).pop(dataToPass);`, and in your function on the first page: `then((dataToPass) () async { ` – HTMHell Mar 17 '23 at 19:00