emit method

ValueChanged<bool> emit(
  1. WidgetEvent event, {
  2. ValueChanged<bool>? onChanged,
})

Callback factory which accepts a T value and returns a closure to mutate value and call setState.

Accepts an optional second named parameter, onChanged, which allows arbitrary functionality to be wired through the WidgetEventMixin. If supplied, the onChanged function is only called when child widgets report events that make changes to the current set of WidgetEvents.

{@tool snippet} This example shows how to use the emit callback factory in other widgets, including the optional onChanged callback.

class MyWidget extends StatefulWidget {
  const MyWidget({
    Key? key,
    this.onPressed,
  }) : super(key: key);

  /// Something important this widget must do when pressed.
  final VoidCallback? onPressed;

  final WidgetEventController? eventsController;

  @override
  State<MyWidget> createState() => MyWidgetState();
}

class MyWidgetState extends State<MyWidget> with WidgetEventMixin<MyWidget> {
  @override
  Widget build(BuildContext context) {
    return Container(
      color: isPressed ? Colors.black : Colors.white,
      child: InkWell(
        onHighlightChanged: widgetEvents.emit(
          WidgetEvent.pressed,
          onChanged: (bool val) {
            if (val) {
              widget.onPressed?.call();
            }
          },
        ),
      ),
    );
  }
}

{@end-tool}

Implementation

ValueChanged<bool> emit(
  WidgetEvent event, {
  ValueChanged<bool>? onChanged,
}) {
  return (bool value) {
    if (this.value.contains(event) == value) return;
    toggle(event, value);
    onChanged?.call(value);
  };
}