2020-09-16 01:27:49 +02:00
|
|
|
import 'dart:async';
|
|
|
|
|
|
|
|
import 'package:flutter/material.dart';
|
|
|
|
import 'package:flutter_hooks/flutter_hooks.dart';
|
|
|
|
|
|
|
|
import 'ref.dart';
|
|
|
|
|
|
|
|
class DelayedLoading {
|
|
|
|
final bool pending;
|
|
|
|
final bool loading;
|
2021-01-03 21:03:32 +01:00
|
|
|
final VoidCallback start;
|
|
|
|
final VoidCallback cancel;
|
2020-09-16 01:27:49 +02:00
|
|
|
|
|
|
|
const DelayedLoading({
|
|
|
|
@required this.pending,
|
|
|
|
@required this.loading,
|
|
|
|
@required this.start,
|
|
|
|
@required this.cancel,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
/// When loading is [.start()]ed, it goes into a pending state
|
|
|
|
/// and loading is triggered after [delayDuration].
|
|
|
|
/// Everything can be reset with [.cancel()]
|
2020-09-19 12:27:57 +02:00
|
|
|
DelayedLoading useDelayedLoading(
|
|
|
|
[Duration delayDuration = const Duration(milliseconds: 500)]) {
|
2020-09-16 23:22:04 +02:00
|
|
|
final loading = useState(false);
|
|
|
|
final pending = useState(false);
|
|
|
|
final timerHandle = useRef<Timer>(null);
|
2020-09-16 01:27:49 +02:00
|
|
|
|
|
|
|
return DelayedLoading(
|
|
|
|
loading: loading.value,
|
|
|
|
pending: pending.value,
|
|
|
|
start: () {
|
|
|
|
timerHandle.current = Timer(delayDuration, () => loading.value = true);
|
|
|
|
pending.value = true;
|
|
|
|
},
|
|
|
|
cancel: () {
|
|
|
|
timerHandle.current?.cancel();
|
|
|
|
pending.value = false;
|
|
|
|
loading.value = false;
|
|
|
|
},
|
|
|
|
);
|
|
|
|
}
|