遍历多个列表,并将它们显示在列表块中

时间:2020-09-30 19:57:48

标签: flutter

class A {
  String name;
  String pic;
}
    
class B {
  String name;
  String pic;
}
    
class C{
  String name;
  String pic;
}
        
class D {
  List<A> as;
  List<B> bs;
  List<C> cs;
}
    
    
D callApi() async{
  final response = repo.getData();
  D d = response.data;
  return d;
}

我想将as,bs和cs放在单独的ListTiles中。 (首先是所有as列表块,而不是所有bs等等。)迭代d中的列表并将其作为ListTiles的最佳方法是什么

2 个答案:

答案 0 :(得分:1)

您可以创建一个List,然后在ListView.builder中使用它。

final List<dynamic> items = [...d.as,...d.bs,...d.cs];

ListView.builder(
  itemCount: items.length,
  itemBuilder: (_, index) {
    return ListTile(
      title: Text(items[index].name),
    );
  },
);

但是,我建议定义一个通用接口,并让类实现该接口。这样,您就可以具有类型安全性,而不必使用dynamic

答案 1 :(得分:1)

componentDidMout(){ if(this.props.navigation.state.params.paramFromB){ this.handler() } } 起,就使用了散布运算符(Dart 2.3),因此您可以使用它来遍历列表。最好的选择是创建一个包含...name字段的模板类,以及创建pic的方法。

ListTile

您甚至可以寻求更优雅的解决方案,并在import 'package:flutter/material.dart'; abstract class ABC { final String name; final String pic; ABC(this.name, this.pic); ListTile createListTile() => ListTile( title: Text(name), // TODO: configure as you need ); } class A extends ABC { A(String name, String pic) : super(name, pic); } class B extends ABC { B(String name, String pic) : super(name, pic); } class C extends ABC { C(String name, String pic) : super(name, pic); } class D { List<A> as; List<B> bs; List<C> cs; } Future<D> callApi() async { final response = repo.getData(); D d = response.data; return d; } Future<void> main() async { final d = await callApi(); final listTiles = <ListTile>[ for (var as in d.as) ...{ as.createListTile(), }, for (var bs in d.bs) ...{ bs.createListTile(), }, for (var cs in d.bs) ...{ cs.createListTile(), }, ]; //TODO: do something with `listTiles` } 上使用extension(自List<ABC>起可用)。然后,Dart 2.7类应该看起来像

ABC

扩展名:

abstract class ABC {
  final String name;
  final String pic;

  ABC(this.name, this.pic);
}

您可以这样使用它:

extension ListABC on List<ABC> {
  List<ListTile> convertToListTiles() {
    var items = <ListTile>[];
    for (var item in this) {
      items.add(ListTile(
        title: Text(item.name),
        // TODO: configure as you need
      ));
    }

    return items;
  }
}