2021-02-24 20:52:18 +01:00
|
|
|
import 'package:flutter/foundation.dart';
|
|
|
|
import 'package:flutter/material.dart';
|
2021-04-05 20:14:39 +02:00
|
|
|
import 'package:lemmy_api_client/v3.dart';
|
2021-02-24 20:52:18 +01:00
|
|
|
|
|
|
|
import '../hooks/delayed_loading.dart';
|
|
|
|
|
|
|
|
/// Executes an API action that uses [DelayedLoading], has a try-catch
|
2021-03-10 08:34:30 +01:00
|
|
|
/// that displays a [SnackBar] when the action fails
|
2021-02-24 20:52:18 +01:00
|
|
|
Future<void> delayedAction<T>({
|
|
|
|
@required BuildContext context,
|
|
|
|
@required DelayedLoading delayedLoading,
|
|
|
|
@required String instanceHost,
|
|
|
|
@required LemmyApiQuery<T> query,
|
|
|
|
Function(T) onSuccess,
|
|
|
|
Function(T) cleanup,
|
|
|
|
}) async {
|
|
|
|
assert(delayedLoading != null);
|
|
|
|
assert(instanceHost != null);
|
|
|
|
assert(query != null);
|
|
|
|
assert(context != null);
|
|
|
|
|
|
|
|
T val;
|
|
|
|
try {
|
|
|
|
delayedLoading.start();
|
2021-04-05 20:14:39 +02:00
|
|
|
val = await LemmyApiV3(instanceHost).run<T>(query);
|
2021-02-24 20:52:18 +01:00
|
|
|
onSuccess?.call(val);
|
|
|
|
// ignore: avoid_catches_without_on_clauses
|
|
|
|
} catch (e) {
|
2021-03-10 08:34:30 +01:00
|
|
|
ScaffoldMessenger.of(context)
|
|
|
|
.showSnackBar(SnackBar(content: Text(e.toString())));
|
2021-02-24 20:52:18 +01:00
|
|
|
}
|
|
|
|
cleanup?.call(val);
|
|
|
|
delayedLoading.cancel();
|
|
|
|
}
|