StreamBuilder
小部件对于此类情况确实很有用,您可以检查文档
Herey。 首先,什么是流?想象一下,它就像管子一样,在管的一侧传递,异步(这意味着并非所有项目都同时传递);而且,在未来的某个时候,这些物品再次到达管子的另一端,异步。 现在,知道什么是
Stream
,我们必须意识到我们不知道我们的要求何时结束,它可能永远不会结束!因此,Flutter为我们提供了StreamBuilder
Stream<List<Item>>
。使用
getListOfItems
,您可以做:
StreamBuilder
对于任何基本实施
//... As a child of any of your widgets
StreamBuilder(
stream: instance.getListOfItems(), // <-- We simply pass the function that returns the stream, Flutter will manage the rest!
builder: (ctx, snapshot) {
// The snapshot contains the data that is being recieved if any
// you can check the docs:
// https://api.flutter.dev/flutter/widgets/AsyncSnapshot-class.html
// And for the ConnectionState enum
// https://api.flutter.dev/flutter/widgets/ConnectionState-class.html
if (snapshot.connectionState == ConnectionState.waiting) {
// What should be rendered when loading or waiting for a response?
return Loading();
}
if (snapshot.hasData) {
// What should be rendered when there's data?
// Remember, data may keep arriving
return MyList(snapshot.data);
}
if (snapshot.hasError) {
// Wow, the stream failed, what should be rendered when there's an error?
return Error();
}
}
)
都应该做。您可以从这里构建动态列表,分页等!将此代码引用bloc
中的流
https://github.com/tejasthonge/flutter-bloc-state-mangement/blob/main/4_streams/_1streas/_1streas/lib/stream1/bloc/bloc/streams_bloc.dart