我正在尝试制作一个小部件,以使用流更新列表,但初始数据将存储在将来。
在无状态窗口小部件中使用Future生成器不起作用,因为它会以setState更新,但我还需要使它能够在没有setState的情况下进行更新
将类型作为参数传递可用于大多数情况,但对于转换器而言,类型将变为动态
铸造转换器不起作用
class ListDisplay<T> extends StatefulWidget {
final Future<List<T>> initialData;
final Stream<T> stream;
final Widget Function(BuildContext, T) converter;
final BoxConstraints constraints;
final PageController controller;
ListDisplay({
@required this.converter,
@required this.stream,
this.initialData,
this.constraints,
this.controller
});
@override
_ListDisplayState createState() => _ListDisplayState<T>();
}
class _ListDisplayState<T> extends State<ListDisplay> {
List<T> list = [];
bool loaded = false;
_load() async {
list.addAll((await widget.initialData).cast<T>());
setState((){
loaded = true;
});
}
@override
void initState() {
super.initState();
_load();
}
@override
Widget build(BuildContext context) {
return Container(
constraints: widget.constraints ?? BoxConstraints(maxHeight: 50.0, maxWidth: 100.0),
child: StreamBuilder<T>(
stream: widget.stream,
builder: (context, snapshot){
list.add(snapshot.data);
return PageView.builder(
scrollDirection: Axis.vertical,
itemCount: list.length,
controller: widget.controller,
itemBuilder: (context, index){
return Container(
constraints: widget.constraints ?? BoxConstraints(maxHeight: 50.0, maxWidth: 100.0),
alignment: Alignment.center,
child: widget.converter(context, list[index]),
);
},
);
},
),
);
}
}