flavian
flavian

Reputation: 28511

How do you create a singleton component in Dart and pass a handler to it to all other components when needed?

I'm trying to create a central notification service for the app, to report simple errors via the same "pipeline". It may be the wrong approach, but I need a material-popup stuck to the main HTML body, displaying on-demand as required by various components.

import 'package:angular/angular.dart';
import 'package:angular_components/angular_components.dart';
import 'package:angular_components/laminate/overlay/zindexer.dart';


@Component(
    selector: 'hv-alerts',
    templateUrl: 'alert_service.html',
    directives: [
      MaterialPopupComponent,
      PopupSourceDirective
    ],
    providers: [
      ClassProvider(ZIndexer),
      materialProviders,
      popupBindings
    ]
)

class AlertService {

  RelativePosition get popupPosition => RelativePosition.AdjacentTop;

  bool popupVisible = false;

  void setVisible(bool flag) {
    popupVisible = flag;
  }


  PopupSizeProvider popupSize = FixedPopupSizeProvider(
      minWidth: 400,
      minHeight: 75,
      maxWidth: 600,
      maxHeight: 75
  );


  static final AlertService _instance = AlertService();
}

Is there a way to pass in the handler to this material-popup via a singleton or Factory or whatever, and allow other services to call an AlertService.show()?

Upvotes: 1

Views: 130

Answers (2)

Night King
Night King

Reputation: 455

This is what I would do:

  • Create an Alert Service (not a component, a regular class)
  • Inject this alert service into your AppComponent
  • Use this service to pass around the view that controls the popup and manipulate it accordingly

It is quite easy to pull-off.

Upvotes: 2

Ted Sander
Ted Sander

Reputation: 1899

The component's lifecycle is dependant on the element in the templates itself. Such if you had two elements with the same selector you would have two components. You can't have them by singletons themselves.

That said how I would do this is abstract the service part of it, and have it be a separate class that would be injected into the popup component and any usage. The popup would listen to a stream know when to show the popup, and the clients would send an event on a StreamController to tell the popup when to show. If you wanted to be a bit safer you could provide two different interfaces the stream, and the stream controller which were backed by the same entity. This would allow you more quickly see who was consuming alerts, and who was producing them.

Upvotes: 0

Related Questions