如何从模型 class 访问 Flutter 特定列表项?
How can access Flutter specific list item from model class?
我有一个名为 Place 的模型 class 并且有一个基于模型 class 的 place 列表].我使用 Navigator.push 并从那里传递 int 数据。现在,我如何访问 ID 与给定 ID 号相同的特定地点列表?
这是我的模型 class 和列表:
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"),
];
这是我的导航器,其中 pass id 为 1:
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DetailsPage(1),
),
);
现在我想访问以下项目 id:1
Place(
id: 1,
cardImage:
"https://image1_url.jpg",
placeName: "Essence Of Japan",
location: "Tokyo",
country: "Japan",
details: "long text"
),
假设 places
列表在您导航的屏幕中,并且 id
是您传递给屏幕的 ID,您可以通过这种方式获取具有该 ID 的地点:
try {
var foundPlace = places.firstWhere((p) => p.id == widget.id);
} catch (e) {
print('place not found');
}
需要在 try-catch 中,因为如果找不到该位置,它会抛出 StateError
。或者您可以添加一个 orElse
,它将 return 一个具有 null
值的 Place
,这需要更改 Place
class 并删除 required
从参数。在这种情况下,您不需要 try-catch :
var foundPlace = place.firstWhere((p) => p.id == widget.id, orElse:()=>Place());
我有一个名为 Place 的模型 class 并且有一个基于模型 class 的 place 列表].我使用 Navigator.push 并从那里传递 int 数据。现在,我如何访问 ID 与给定 ID 号相同的特定地点列表?
这是我的模型 class 和列表:
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"),
];
这是我的导航器,其中 pass id 为 1:
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DetailsPage(1),
),
);
现在我想访问以下项目 id:1
Place(
id: 1,
cardImage:
"https://image1_url.jpg",
placeName: "Essence Of Japan",
location: "Tokyo",
country: "Japan",
details: "long text"
),
假设 places
列表在您导航的屏幕中,并且 id
是您传递给屏幕的 ID,您可以通过这种方式获取具有该 ID 的地点:
try {
var foundPlace = places.firstWhere((p) => p.id == widget.id);
} catch (e) {
print('place not found');
}
需要在 try-catch 中,因为如果找不到该位置,它会抛出 StateError
。或者您可以添加一个 orElse
,它将 return 一个具有 null
值的 Place
,这需要更改 Place
class 并删除 required
从参数。在这种情况下,您不需要 try-catch :
var foundPlace = place.firstWhere((p) => p.id == widget.id, orElse:()=>Place());