关于Flutter的Google I / O 2018 video解释了如何使用Dart流来管理Flutter应用程序中的状态。发言者谈到使用Sink
作为输入流和Stream
作为输出流。 Sink
和Stream
之间有什么区别?我搜索了文档,但没有说太多的谢谢。
答案 0 :(得分:21)
我将尝试用一个简单的示例进行解释,因为从这一点上,它很容易理解。
Sink
和Streams
都是流控制器的一部分。您可以使用sink
将数据添加到流控制器中,可以通过stream
示例:
final _user = StreamController<User>();
Sink get updateUser => _user.sink;
Stream<User> get user => _user.stream;
用法:
updateUser.add(yourUserObject); // This will add data to the stream.
user.listen((user) => print(user)); // Whenever a data is added to the stream via sink, it will be emitted which can be listened using the listen method.
您可以在发出流之前执行各种操作。 transform
方法是一个示例,可用于在发出输入数据之前对其进行转换。
答案 1 :(得分:4)
StreamSink
是StreamConsumer
,这意味着它可以使用多个流(由addStream
https://api.dartlang.org/stable/1.24.3/dart-async/StreamConsumer/addStream.html添加)并处理这些流发出的事件。
如果是StreamSink
的{{1}},则添加的流中的所有事件都由StreamController
创建的流发出。
这样,您可以将一个或多个流管道(转发)到另一个流中。
答案 2 :(得分:0)
让我们举一个Flutter中的SINKS&STREAMS的简单示例。请阅读评论
class LoginBloc {
final _repository = Repository();
final _loginResponse = BehaviorSubject<bool>(); //---->> a simple Sink
Stream<bool> get isSuccessful => _loginResponse.stream; //-----> Stream linked with above sink
/*
* Below is an async function which uses Repository class
* to hit a login API and gets the result in a variable
* isUserLoginSuccessful[true/false]. and then Add the result
* into the sink.
* now whenever something is added to the sink, a callback is given to
* the stream linked to that Sink, which is managed by the framework itself
*
*/
Future getLoginResponse() async {
bool isUserLoginSuccessful = await _repository.processUserLogin();
_loginResponse.sink.add(isUserLoginSuccessful);
}
dispose() {
_loginResponse.close();
}
}
现在,我正在登录屏幕中使用此LoginBloc。
class Login extends StatelessWidget {
final LoginBloc loginBloc; // ----> Here is the Object of LoginBloc
Login(this.loginBloc);
void _onClickLoginButton() async {
// Hit login API
// fetch Login API response data
loginBloc.getLoginResponse(); //------> here is the function we are using in Login
}
@override
Widget build(BuildContext context) {
return StreamBuilder<bool>( // ----> You need to use a StreamBuilder Widget on the top Root, or according to the Business logic
stream: loginBloc.isSuccessful, // ----> here is the stream which is triggered by Sink which is linked by this stream
builder: (context, snapshot) {
// DO WHATEVER YOU WANT AFTER CALLBACK TO STREAM
});
我希望这可以使您的流和汇概念更加清晰。
答案 3 :(得分:0)
如果您正在寻找关于流和接收器的非常基本的定义,请参考此:
流-传送带称为流 StreamController ,这是控制流的内容 StreamTransformer ,这是处理输入数据的方法 StreamBuilder ,它是一种将流作为输入并向我们提供构建器的方法,该构建器会在每次出现流的新值时进行重建 接收器,需要输入内容的属性 流,该属性将输出从流中输出
有关更多详细信息,pls refer the following article: