2020-04-18 11:48:21 +00:00
|
|
|
import 'dart:async';
|
|
|
|
|
|
|
|
import 'package:comunic/helpers/events_helper.dart';
|
2019-05-01 15:52:41 +00:00
|
|
|
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>();
|
2020-05-06 16:16:57 +00:00
|
|
|
final _timers = List<Timer>();
|
2020-04-18 11:48:21 +00:00
|
|
|
|
2020-04-20 15:47:51 +00:00
|
|
|
bool _unmounted = false;
|
|
|
|
|
2020-04-18 11:48:21 +00:00
|
|
|
@override
|
|
|
|
void dispose() {
|
2020-04-20 15:47:51 +00:00
|
|
|
_unmounted = true;
|
|
|
|
|
2020-04-18 11:48:21 +00:00
|
|
|
// Close subscriptions
|
|
|
|
_subscriptions.forEach((f) => f.cancel());
|
|
|
|
|
2020-05-06 16:16:57 +00:00
|
|
|
// Stop intervals
|
|
|
|
_timers.forEach((f) => f.cancel());
|
|
|
|
|
2020-04-18 11:48:21 +00:00
|
|
|
super.dispose();
|
|
|
|
}
|
|
|
|
|
2019-05-01 15:52:41 +00:00
|
|
|
@override
|
|
|
|
void setState(fn) {
|
2020-04-20 15:47:51 +00:00
|
|
|
if (mounted && !_unmounted) super.setState(fn);
|
2019-05-01 15:52:41 +00:00
|
|
|
}
|
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));
|
|
|
|
}
|
2020-04-18 12:14:54 +00:00
|
|
|
|
|
|
|
/// 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));
|
|
|
|
}));
|
|
|
|
}
|
2020-05-05 16:18:09 +00:00
|
|
|
|
|
|
|
/// Safely mimic the setTimeout javascript function
|
|
|
|
///
|
|
|
|
/// If the widget is unmounted before the end of the timeout,
|
|
|
|
/// the callback function is not called
|
|
|
|
void setTimeout(int secs, void Function() cb) {
|
|
|
|
Timer(Duration(seconds: secs), () {
|
|
|
|
if (!_unmounted) cb();
|
|
|
|
});
|
|
|
|
}
|
2020-05-06 16:16:57 +00:00
|
|
|
|
|
|
|
/// Safely mimic the setInterval javascript function
|
|
|
|
void setInterval(int secs, void Function(Timer) cb) {
|
|
|
|
final timer = Timer.periodic(Duration(seconds: secs), cb);
|
|
|
|
_timers.add(timer);
|
|
|
|
}
|
2020-04-18 12:14:54 +00:00
|
|
|
}
|