skip to Main Content

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?

2

Answers


  1. 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,
      ),
    ),
    
    Login or Signup to reply.
  2. 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((){}));

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search