flutter_event_bus 0.0.2

  • Readme
  • Changelog
  • Installing
  • 80

flutter_event_bus #

Star this Repo Pub Package

Flutter Event Bus is an EventBus designed specific for Flutter app, which enable developer to write flutter app with Interactor pattern, which is similar to Bloc but less structured on some aspect.

Why another Event Bus #

There is a Event Bus package, why create another one?

Marco Jakob did a great job while creating Event Bus package, which provides a generic Event Bus pattern implementation that can be used anywhere in Dart ecosystem.

But while writing app in Interactor pattern in flutter, there are a few common usages that existing library are not really convenient. So Flutter Event Bus has been carefully customised for these use cases.

Event Bus #

Event Bus is a pub/sub system to enable components collaborate with each other without direct coupling. Component can publish event to make announcement when something happens, or respond to event to take action.

Basic Usage #

class TextChangedEvent{
  final String text;
  const TextChangedEvent(this.text);
}

final eventBus = EventBus();

eventBus.respond<TextChangedEvent>((TextChangedEvent event) =>
  print("Text changed to ${event.text}");
);

eventBus.publish(TextChangedEvent("new text"));

Stop responding events #

final subscription = eventBus.respond<TextChangedEvent>(responder);

eventBus.publish(TextChangedEvent("Responded")); // This event will be responded by responder

subscription.dispose();

eventBus.publish(TextChangedEvent("Ignored")); // This event will not be responded by responder

Respond to different type of events #

final subscription = eventBus
  .respond<EventA>(responderA) // Subscribe to EventA
  .respond<EventB>(responderB) // Subscribe to EventB
  .respond<EventC>(responderC) // Subscribe to EventC
  .respond(genericResponder); // Subscribe to EventA EventB EventC and any other event on event bus

  // Generic Responder could be useful for monitoring, logging or diagnosis purpose, probably will be hardly used to take action to event

subscription.dispose(); // All previous 4 subscriptions will be cancelled all together

Used in Flutter #

Event Bus Widget #

To embed EventBus in Flutter, you can use EventBusWidget, which provide EventBus to its child tree.

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) =>
    EventBusWidget(
      child: MaterialApp(
        // .....
      )
    );
}

Capture user interaction #

You're like to publish event in stateless widget to broadcast user interaction into your app.

class SubmitFormEvent { }

class SubmitButton extends StatelessWidget {
  @override
  Widget build(BuildContext context) =>
    FlatButton(
      child: const Text("Publish"),
      onPressed: () {
        EventBus.publish(context, SubmitFormEvent()); // Publish event to the event bus provided by ancestor EventBusWidget
      }
    )
}

Capture state changes #

You might also wish to publish some event when app state had a certain change

class MyWidgetState extends State<MyWidget> {
  int _counter = 0;
  EventBus eventBus;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();

    eventBus = EventBus.of(context); // Find EventBus provided by ancestor EventBusWidget
  }


  void _incrementCounter(InreaseCounterEvent event) {
    setState(() {
      if(++_counter == 100) {
        eventBus.publish(CounterMaximizedEvent());
      }
    });
  }
}

Respond events #

To respond to events you can listening event bus directly. But more commonly you will do it via Interactor.

You can use Interactor as base class as your stateful widget state, and implements the subscribeEvents method to describe the events that interactor can handle. Interactor manages the subscription and cancel the subscription when it is removed from the tree.

class IncreaseCounterEvent {}
class DecreaseCounterEvent {}
class CounterChangedEvent {
  final int value;
  CounterChangedEvent(this.value);
}

class MyPage extends StatefulWidget {
  MyPage({Key key}) : super(key: key);

  @override
  _MyPageInteractor createState() => _MyPageInteractor();
}

class _MyPageInteractor extends Interactor<MyHomePage> {
  int _counter = 0;

  @override
  Widget build(BuildContext context) {
    // Build the widget tree as usual
  }

  @override
  Subscription subscribeEvents() => eventBus
    .respond<IncreaseCounterEvent>(_incrementCounter)
    .respond<DecreaseCounterEvent>(_decrementCounter);

  void _incrementCounter(IncreaseCounterEvent event) {
    setState(() {
      _counter++;

      eventBus.publish(CounterChangedEvent(_counter));
    });
  }

   void _incrementCounter(DecreaseCounterEvent event) {
    setState(() {
      _counter--;

      if(_counter < 0) {
        _counter = 0;
        eventBus.publish(CounterReachZeroEvent());
      }

      eventBus.publish(CounterChangedEvent(_counter));
    });
  }
}

License #

The MIT License (MIT)

[0.0.2] - 2019-12-12 #

  • Added MIT license file
  • Fixed some lint warnings during publish
  • Added basic API document
  • Updated readme

[0.0.1] - 2019-12-12 #

  • First release
  • Added EventBus, EventBusWidget, Interactor, Responder and Subscription

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  flutter_event_bus: ^0.0.2

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:flutter_event_bus/flutter_event_bus.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
67
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
80
Overall:
Weighted score of the above. [more]
80
Learn more about scoring.

We analyzed this package on Apr 6, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.7.1
  • pana: 0.13.6
  • Flutter: 1.12.13+hotfix.8

Maintenance suggestions

Package is pre-v0.1 release. (-10 points)

While nothing is inherently wrong with versions of 0.0.*, it might mean that the author is still experimenting with the general direction of the API.

The description is too long. (-10 points)

Search engines display only the first part of the description. Try to keep the value of the description field in your package's pubspec.yaml file between 60 and 180 characters.

Maintain an example.

None of the files in the package's example/ directory matches known example patterns.

Common filename patterns include main.dart, example.dart, and flutter_event_bus.dart. Packages with multiple examples should provide example/README.md.

For more information see the pub package layout conventions.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.1.0 <3.0.0
flutter 0.0.0
Transitive dependencies
collection 1.14.11 1.14.12
meta 1.1.8
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
flutter_test
mockito ^4.1.1