I have a model class called Place and have a list of place based on the model class. I use Navigator.push and pass int data from there. Now how can I access a specific list of place where the id is the same as the given id number?
Here is my model class and list:
class Place {
int id;
String cardImage;
String placeName;
String location;
String country;
String details;
Place({
required this.id,
required this.cardImage,
required this.placeName,
required this.location,
required this.country,
required this.details,
});
}
final List<Place> place = [
Place(
id: 1,
cardImage:
"https://image1_url.jpg",
placeName: "Essence Of Japan",
location: "Tokyo",
country: "Japan",
details: "long text"),
Place(
id: 2,
cardImage:
"https://image2_url.jpg",
placeName: "Essence Of Japan",
location: "Tokyo",
country: "Japan",
details: "long text"),
];
This is my Navigator where is pass id as 1:
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DetailsPage(1),
),
);
Now I want to access bellow item where id:1
Place(
id: 1,
cardImage:
"https://image1_url.jpg",
placeName: "Essence Of Japan",
location: "Tokyo",
country: "Japan",
details: "long text"
),
CodePudding user response:
Assuming the places
list is in the screen where you navigate, and the id
is the id you pass to the screen, you can get the place with that id this way :
try {
var foundPlace = places.firstWhere((p) => p.id == widget.id);
} catch (e) {
print('place not found');
}
Needs to be in a try-catch because if the place is not found it throws a StateError
. Or you can add an orElse
that will return a Place
with null
values, that requires to change the Place
class and remove the required
from the parameters. In this case you won't need a try-catch :
var foundPlace = place.firstWhere((p) => p.id == widget.id, orElse:()=>Place());