title: Dart/Flutter - yield from callback function
body: <p>I need to make a function call which does not return anything (<code>void</code>). Only way to get notified about function completion is sending a <code>callback</code> function.<br>
  Now I an using <code>BLoC</code> pattern along with <code>ReDux</code>, When an event is dispatched, I dispatch another action to store of <code>redux</code>, After <code>action</code> is completed it calls the <code>callback</code> function. And now inside <code>callback</code> function, I want to update the <code>state</code> of <code>bloc</code>. Below is my implementation,</p>
  
  <pre><code>if (event is Login) {
    yield currentState.copyWith(formProcessing: true);
    store.dispatch(authActions.login(
      currentState.username,
      currentState.password,
      (error, data) {
        print(error);
        print(data);
        // I want to yield here.
        yield currentState.copyWith(formProcessing: false);
      },
    ));
  }
  </code></pre>
  
  <p>As shown in the above code snippet, Inside the callback function, I want to <code>yield</code>.</p>
  
  <h1>Solution</h1>
  
  <p>Create a function that returns the future and makes callback function to store dispatch, Heres sample.</p>
  
  <pre><code>if (event is Login) {
    yield currentState.copyWith(formProcessing: true);
  
    try {
      dynamic result = await loginAction(store, currentState.username, currentState.password);
      print(result);
      yield currentState.copyWith(formProcessing: false);
    } catch (e) {
      print(e);
    }
  }
  
  Future loginAction(store, username, password) {
    var completer = new Completer();
  
    store.dispatch(authActions.login(
      username,
      password,
      (error, data) {
        if (error != null) {
          completer.completeError(error);
        } else if (data != null) {
          completer.complete(data);
        }
      },
    ));
  
    return completer.future;
  }
  </code></pre>