关于Flutter的Google I / O 2018 video解释了如何使用Dart流来管理Flutter应用程序中的状态。演讲者谈到使用Sink
作为输入流和Stream
作为输出流。 Sink
和Stream
有什么区别?我搜索了文档,但它没有说太多的谢谢。
StreamSink
是一个StreamConsumer
,这意味着它可以采取几个流(由addStream
添加)并处理这些流发出的事件。
如果它是StreamSink
的StreamController
,那么来自添加的流的所有事件都由StreamController
创建的流发出。
这样,您可以将一个或多个流管道(转发)到另一个流中。
我将尝试用一个简单的例子来解释,因为从那时起它很容易理解。
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
方法是一个示例,可用于在输入数据发出之前对其进行转换。
让我们举一个Sputter中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
});
我希望这可以使您的流和接收器概念更清晰。