1
0
mirror of https://gitlab.com/comunic/comunicmobile synced 2024-11-30 00:36:28 +00:00
comunicmobile/lib/ui/widgets/safe_state.dart

42 lines
922 B
Dart
Raw Normal View History

2020-04-18 11:48:21 +00:00
import 'dart:async';
import 'package:comunic/helpers/events_helper.dart';
import 'package:flutter/material.dart';
/// Little State hack to avoid issues
///
/// @author Pierre HUBERT
abstract class SafeState<T extends StatefulWidget> extends State<T> {
2020-04-18 11:48:21 +00:00
final _subscriptions = List<StreamSubscription>();
@override
void dispose() {
// Close subscriptions
_subscriptions.forEach((f) => f.cancel());
super.dispose();
}
@override
void setState(fn) {
if (mounted) super.setState(fn);
}
2020-04-18 11:48:21 +00:00
/// Register to a new subscription
@protected
void listen<T>(void onEvent(T event)) {
_subscriptions.add(EventsHelper.on<T>(onEvent));
}
/// Register to a new subscription
///
/// Callback will we called inside of setState
@protected
void listenChangeState<T>(void onEvent(T event)) {
_subscriptions.add(EventsHelper.on<T>((d) {
setState(() => onEvent(d));
}));
}
}