fromChannel<D, P> static method

InitialData<D> fromChannel<D, P>(
  1. Channel<P> channel,
  2. D initialValue(
    1. P payload
    )
)

Creates an InitialData that produces its value by calling initialValue with the payload provided when entering the state through channel.

var s1 = StateKey('state1');
var s2 = StateKey('state2');
var s2Channel = Channel<String>(s2);
class S2Data {
  String value = '';
}
var builder = StateTreeBuilder(initialState: parentState);

builder.state(s1, (b) {
  b.onMessageValue('go', (b) => b.enterChannel(s2Channel, (msgCtx, msg) => 'Hi!'));
});

builder.dataState<S2Data>(
  s2,
  InitialData.fromChannel(channel, (payload) => S2Data()..value = payload),
  (b) {
    b.onEnter((b) {
      // Will print 'Hi!'
      b.run((transCtx, data) => print(data.value));
    });
  });

Implementation

static InitialData<D> fromChannel<D, P>(Channel<P> channel, D Function(P payload) initialValue) {
  return InitialData._((transCtx) {
    try {
      return initialValue(transCtx.payloadOrThrow<P>());
    } catch (e) {
      throw StateError('Failed to obtain inital data of type $D for '
          'channel ${channel.label != null ? '"${channel.label}" ' : ''}'
          'to state ${channel.to}: $e');
    }
  });
}