1

I am running into a problem which I find difficult to describe.

I have a class with two variables. On page 1, I would like to show variable 1. Then, if the user progresses to page 2, I would like to display a widget with variable 1 and 2. I understood how to pass data from one screen to another, but how would I progress if I had to get more data one the second page.

This is the class:

class Dog {
  String name;
  String age;
  Dog({ this.name, this.age });
}

On the first page, I only define the String name, but not the age. Hence, when the user progresses to the second page, I pass the name data as follows (from a list of dogs):

Navigator.push(context,
  MaterialPageRoute(
    builder: (context) => Screen2(dog: dogs[index]),
  ),
);

On the second screen, I would like to show a statelesswidget with both class variables, but I only passed one:

final Dog dog;
Screen2({Key key, @required this.dog}) : super(key: key);

In the last code, "this.dog" only includes the name String.

How could I now add the age String as well? Do I have to add it to Navigator.push, or is there a way to add it in the statelesswidget?

Thanks so much in advance for any guidance you can give me!

Nicolas O
  • 143
  • 2
  • 12
  • The answer to this will depend on where the list of dog names and ages comes from. How do you populate `dogs` in the first widget? – emerssso Feb 24 '20 at 23:09
  • Thanks for your answer! In the first screen, I have a stateful widget in which I declared a list of dogs. However, I only declared the list of dogs with the name string and did not define the second variable yet. I only want to define the second variable once the second screen is on. The reason I thought this is necessary, is because later on, I dont want to load unnecessary data (age string) in the first screen, as it will not be required to render the screen 1. – Nicolas O Feb 24 '20 at 23:20
  • I think it may be useful to add that stateful widget to the question. – emerssso Feb 24 '20 at 23:48
  • As far as I can understand, even if you do not want to use the `age` data on the first screen, you can still define a `Map` that points to a dog's name and its age. You can then only use the dog names in the Map in your first screen and pass the map to your second screen to show both name and the age – Harsh Mehta Feb 25 '20 at 05:15
  • Thanks for your answers! Regarding the map method, I would still need to declare the whole class initially even if I only point to one attribute via the map method. Maybe an other example - imagine you have a screen which shows a list of titles for movies. When the user clicks on one title, the screen changes and opens a new screen which then displays the title and the description of this movie. For the first screen, I would not already want to load all data incl. the descirptions, but only do this once the second screen opens for this particular movie. This would make the app faster. – Nicolas O Feb 25 '20 at 19:23

0 Answers0