Navigation to a different instance of an existing page

425 Views Asked by At

I'm dealing with a scenario where I have an Apartment page (StatefulWidget) and on this page, I also have a list of "similar apartments".

When the user clicks on any of the similar apartments, they are Navigateed to a different instance of Apartment class, but with new content.

However, I realized with logs that each time I Navigate to the new Apartment page, all the existing instances of the Apartment class on the Stack, are also getting recreated and it's causing issues.

Here is the code I use to Navigate to a new instance:

  Navigator.push(
    context,
    CupertinoPageRoute(
      builder: (context) => AptPage(
          key: ObjectKey("$buildingId$unitNum"),
          unitNumber: unitNum,
          buildingId: buildingId,
          cubit: BlocProvider.of<BuildingInfoCubit>(context)),
    ),
  );

What I wish is that previously created Apartment pages, do not get recreated again, and also I still want to be able to go back to previous Apartment pages on the Stack.

(Am I using ObjectKey wrong? )

2

There are 2 best solutions below

1
On

on this situation , and in the short answer you need to change the whole process when dealing with variables gotten from api or what ever, you need to use this MVC plugin to save information and variables to the Controller class and implement the controller by the widgets so you can get the variables as you wish in an infinity number of widgets , or if you found the change to MVC pattern is difficult you can use the notifiable variables and assign it as public through the app when you use the variables, so get the data from the variable it self and notify when it is updated, so not to reload it on every widget call ,i do not recommend sending data between widgets as route arguments

0
On

I'm not sure if I got your question correctly, but if you want to check something is the same as the previous object for not creating new one then "equatable" may help. you'r objects will extend from "equatable".

but in your case when you will navigate to new widget even if it's the same one that you are in it's normal to create new instance of it.

if you can give me the big picture that would be great...