2023-12-30 21:23:42 +00:00
|
|
|
import 'dart:async';
|
|
|
|
|
|
|
|
import 'package:flutter/material.dart';
|
|
|
|
import 'package:provider/provider.dart';
|
2024-01-01 16:11:05 +00:00
|
|
|
import 'package:visibility_detector/visibility_detector.dart';
|
2023-12-30 21:23:42 +00:00
|
|
|
|
2024-01-01 16:11:05 +00:00
|
|
|
import '../../providers/BaseProvider.dart';
|
2023-12-30 21:23:42 +00:00
|
|
|
|
|
|
|
class APIBuilder<T extends BaseProvider, K, DTO> extends StatefulWidget {
|
|
|
|
const APIBuilder(
|
|
|
|
{super.key,
|
|
|
|
required this.onLoad,
|
|
|
|
required this.onData,
|
|
|
|
this.interval,
|
|
|
|
this.dto});
|
|
|
|
|
|
|
|
final DTO? dto;
|
|
|
|
final Duration? interval;
|
|
|
|
final Widget Function() onLoad;
|
|
|
|
final Widget Function(K t) onData;
|
|
|
|
|
|
|
|
@override
|
|
|
|
State<APIBuilder<T, K, DTO>> createState() => _APIBuilderState<T, K, DTO>();
|
|
|
|
}
|
|
|
|
|
|
|
|
class _APIBuilderState<T extends BaseProvider, K, DTO>
|
|
|
|
extends State<APIBuilder<T, K, DTO>> {
|
|
|
|
Timer? timer;
|
2024-01-01 16:11:05 +00:00
|
|
|
bool visible = true;
|
2023-12-30 21:23:42 +00:00
|
|
|
|
|
|
|
@override
|
|
|
|
void initState() {
|
|
|
|
super.initState();
|
|
|
|
Provider.of<T>(context, listen: false).loadFuture(context, dto: widget.dto);
|
|
|
|
|
|
|
|
if (widget.interval != null) {
|
|
|
|
timer = Timer.periodic(widget.interval!, (Timer t) {
|
2024-01-01 16:11:05 +00:00
|
|
|
if (visible) {
|
|
|
|
Provider.of<T>(context, listen: false)
|
|
|
|
.refresh(context, dto: widget.dto);
|
|
|
|
}
|
2023-12-30 21:23:42 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
@override
|
|
|
|
void dispose() {
|
|
|
|
super.dispose();
|
|
|
|
timer?.cancel();
|
|
|
|
}
|
|
|
|
|
|
|
|
@override
|
|
|
|
Widget build(BuildContext context) {
|
|
|
|
final Future<K> fut = Provider.of<T>(context).data as Future<K>;
|
|
|
|
|
2024-01-01 16:11:05 +00:00
|
|
|
return VisibilityDetector(
|
|
|
|
key: widget.key ?? const Key("APIBuilder"),
|
|
|
|
onVisibilityChanged: (visibilityInfo) {
|
|
|
|
var visiblePercentage = visibilityInfo.visibleFraction * 100;
|
|
|
|
|
|
|
|
if (mounted) {
|
|
|
|
setState(() {
|
|
|
|
visible = visiblePercentage != 0;
|
|
|
|
});
|
2023-12-30 21:23:42 +00:00
|
|
|
}
|
2024-01-01 16:11:05 +00:00
|
|
|
|
|
|
|
debugPrint(
|
|
|
|
'Widget ${visibilityInfo.key} is ${visiblePercentage}% visible');
|
2023-12-30 21:23:42 +00:00
|
|
|
},
|
2024-01-01 16:11:05 +00:00
|
|
|
child: FutureBuilder<K>(
|
|
|
|
future: fut,
|
|
|
|
builder: (context, snapshot) {
|
|
|
|
if (snapshot.hasData) {
|
|
|
|
return widget.onData(snapshot.data!);
|
|
|
|
} else {
|
|
|
|
return widget.onLoad();
|
|
|
|
}
|
|
|
|
},
|
|
|
|
),
|
2023-12-30 21:23:42 +00:00
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|