What is the difference between Sink and Stream in Flutter?

后端 未结 4 642
栀梦
栀梦 2021-02-03 23:50

The Google I/O 2018 video about Flutter explains how to use Dart streams to manage state in a Flutter application. The speaker talked about using Sink as input stre

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-04 00:26

    Let us take a simple example of SINKS & STREAMS in Flutter. Please Reade the comments

           class LoginBloc {
              final _repository = Repository();
              final _loginResponse = BehaviorSubject();  //---->> a simple Sink
              Stream 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();
              }
            }
    

    Now, I am using this LoginBloc in Login Screen.

         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(    // ----> 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
    });
    

    i hope this may make your stream & sink concept more clearer.

提交回复
热议问题