【问题标题】:How can access Flutter specific list item from model class?如何从模型类访问 Flutter 特定的列表项?
【发布时间】:2022-01-05 20:08:53
【问题描述】:

我有一个名为 Place 的模型类,并有一个基于模型类的 place 列表。我使用 Navigator.push 并从那里传递 int 数据。现在如何访问 id 与给定 id 号相同的特定地点列表?

这是我的模型类和列表:

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"
         ),

【问题讨论】:

    标签: flutter dart flutter-layout flutter-listview


    【解决方案1】:

    假设places 列表在您导航的屏幕中,id 是您传递给屏幕的 id,您可以通过这种方式获取具有该 id 的位置:

      try {
        var foundPlace = places.firstWhere((p) => p.id == widget.id);
      } catch (e) {
        print('place not found');
      }
    

    需要在 try-catch 中,因为如果找不到该位置,它会抛出 StateError。或者您可以添加一个orElse,它将返回一个带有null 值的Place,这需要更改Place 类并从参数中删除required。在这种情况下,您不需要 try-catch :

    var foundPlace = place.firstWhere((p) => p.id == widget.id, orElse:()=>Place());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-07
      • 1970-01-01
      • 2017-04-09
      • 2021-03-14
      • 2021-02-11
      • 2019-01-27
      相关资源
      最近更新 更多