【问题标题】:How to add elements dynamically in a 2d list from another list in Flutter?如何从 Flutter 中的另一个列表动态添加元素到二维列表中?
【发布时间】:2021-06-14 14:40:07
【问题描述】:

我有一个模型类对象列表。比如——

List<ModelChannel> allChannels = [];

我在这个列表中添加了来自 json 的元素。模型类变量是-

final String channelid;
final String channelname;
final String channeltype;
final String categoryname;
final String channelimage;
final String channelurl;

这里的 categorytype 包含国家信息。我想动态地划分列表国家。我打算使用 2d 列表,其中每一行将包含特定国家的所有频道。这是正确的方法吗?如果是,如何实施,如果不是,那么什么是正确的?

【问题讨论】:

    标签: list flutter dart 2d


    【解决方案1】:

    如果我理解正确,您正在从collection 包中寻找groupBy 函数。

    将此包添加到您的 pubspec.yaml:

    dependencies:
      collection: any
    

    并使用groupBy

    import 'package:collection/collection.dart';
    
    ...
    
    final groupByCountry = groupBy(allChannels, (ModelChannel e) => e.categoryname);
    

    【讨论】:

    • 您提供的软件包可能会起作用。但我是按照自己的逻辑做到的。
    【解决方案2】:
    List<List<ModelChannel>> countryList = [];
    List<String> channelType = [];
    
    allChannels.forEach((element) {
    
        if (channelType.isEmpty) {
          channelType.add(element.channeltype);
        } else {
          if (channelType.contains(element.channeltype)) {
          } else {
            channelType.add(element.channeltype);
          }
        }
      });
    
      channelType.forEach((countryCode) {
        List<ModelChannel> t = [];
        allChannels.forEach((element) {
          if (element.channeltype == countryCode) {
            t.add(element);
          }
        });
        countryList.add(t);
      });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-13
      • 1970-01-01
      • 2013-06-08
      • 1970-01-01
      相关资源
      最近更新 更多