【问题标题】:Return a value from a list of Objects in Dart based on a condition根据条件从 Dart 中的对象列表中返回一个值
【发布时间】:2020-09-07 07:29:40
【问题描述】:

我有一个 Country 对象列表:countryName、countryCode、currencyName、currencyCode、countryCapitalCity、countryLatitude、countryLongitude。对象存储如下:

    Country('Ghana', '+233', 'Ghanaian Cedi', 'GHS', 'Accra', 5.603717,
        -0.186964, 22),
    Country('Guinea', '+224', 'Guinean Franc', 'GNF', 'Conakry', 9.641185,
        -13.578401, 23),
    Country('Guinea-Bissau', '+245', 'West African CFA Franc', 'XOF', 'Bissau',
        11.881655, -15.617794, 24),
    Country('Ivory Coast', '+225', 'West African CFA Franc', 'XOF',
        'Yamoussoukro', 6.827623, -5.289343, 25),

我已将列表实例化如下:

    List<Country> _countries = Country.countries;

我有一个变量:userCountryCode 将被提供 - 例如以 +245 为例。我想遍历 _countries 列表并返回值 11.881655、-15.617794,它们映射到对象的 countryLatitude, countryLongitude 属性。

以下操作无效:

    List<Country> dumy =
       _countries.where((element) => element.countryCode == result).toList();

【问题讨论】:

    标签: list flutter dart


    【解决方案1】:

    另一种方法是使用Map。在您的情况下,您可以创建 Map&lt;String, List&lt;Country&gt;&gt; 作为 countryCode 的键(我理解这不是唯一的,因为您可以检索多个 Country)。

    然后,您只需搜索 mapName[countryCodeKey] 之类的键,这将返回一个 List&lt;Country&gt;,这将是所有具有该键的国家。

    这比遍历所有列表项要快得多。如果你知道大 O 表示法,你的解决方案是 O(n),而使用地图是 O(1)。您只需遍历列表一次即可创建地图。

    要创建地图,您可以使用:

    Map<String, Country> = {
      for (Country c in _countries)
        c.countryCode: c
    };
    

    一个例子是:

    void main() {
      List<Country> _countries = [
        Country(
          'Ghana',
          '+233',
          'Ghanaian Cedi',
          'GHS',
          'Accra',
          5.603717,
          -0.186964,
        ),
        Country(
          'Guinea',
          '+224',
          'Guinean Franc',
          'GNF',
          'Conakry',
          9.641185,
          -13.578401,
        ),
        Country(
          'Guinea-Bissau',
          '+245',
          'West African CFA Franc',
          'XOF',
          'Bissau',
          11.881655,
          -15.617794,
        ),
        Country(
          'Ivory Coast',
          '+225',
          'West African CFA Franc',
          'XOF',
          'Yamoussoukro',
          6.827623,
          -5.289343,
        ),
        Country(
          'Another Country',
          '+225',
          'Atlantida',
          'BTC',
          'Bitcoin',
          12.827623,
          -155.289343,
        ),
      ];
    
      Map<String, List<Country>> countryMap = {};
      for (Country country in _countries) {
        countryMap.putIfAbsent(country.countryCode, () => []).add(country);
      }
    
      // Let's say you are looking for the +233 code
      countryMap['+233'].forEach((item) {
        print(item.countryLongitude);
        print(item.countryLatitude);
      });
    
      // If you want it null-aware
      countryMap['+234']?.forEach((item) {
        print(item.countryLongitude);
        print(item.countryLatitude);
      });
      // By using ?. the property or method will only be called if
      // the item is not null
    
      // If you want to check if a code exists
      if (countryMap.containsKey('+312')) {
        print('Existing code!');
      } else {
        print('This code does not exist!');
      }
    
      // If you want to keep the list of contries with a code
      List<Country> countriesWithId = countryMap['+225'];
      print(countriesWithId.length);
      // Prints 2 since there are two items with the id of +255
    }
    

    【讨论】:

    • 试过了 - 不工作给出错误;缺少选择器,例如“.identifier”或“[0]”。你能分享给定国家代码(已经给出)返回国家纬度和经度的工作代码吗?谢谢。
    • 让我试试。既然您已经使用了 foreach - 这对于每个都让我在遍历来自 firebase 的文档列表时遇到了麻烦,并且它复制了每个计算,请您看看这个,如果您能指导一下吗?我会很感激:stackoverflow.com/questions/63773761/…
    • 成功了。我会赞成它。与我之前的方法相比,我不确定它的速度有多快。尽管如此,我会在我的代码中采用你的风格。我正在尝试将其映射到我的查询快照列表,这让我很头疼,但它没有加起来。有什么线索吗?
    • 将其标记为答案 ;)。我看到了这个问题,如果我有什么我会告诉你的。
    • 对于另一个问题,我实际上想通了。我将发布最终答案。它真的让我陷入了三天的困境 - 解决方案非常简单......使用for循环以及删除重复的QueryDocumentSnapshot,也改变了清除列表的位置。吸取了一生的教训。
    【解决方案2】:

    我在创建问题时发现了这一点,而不是放弃解决方案,认为分享是明智的 - 我/我们将来可能需要它:

        List<Country> dumy =
            _countries.where((element) => element.countryCode == result).toList();
         for (var d in dumy) {
          var clat = d.countryLatitude;
          var clong = d.countryLongitude;
        } 
    

    【讨论】:

      猜你喜欢
      • 2021-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-03
      • 2016-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多