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
的最佳方法是什么
答案 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;
}
}