2023-03-23 14:48:53 +01:00
|
|
|
import 'package:flutter/material.dart';
|
|
|
|
import 'package:outbag_app/backend/errors.dart';
|
|
|
|
import 'package:outbag_app/backend/request.dart';
|
|
|
|
import 'package:outbag_app/tools/snackbar.dart';
|
|
|
|
|
|
|
|
void doNetworkRequest(ScaffoldMessengerState? sm,
|
2023-03-25 17:18:46 +01:00
|
|
|
{required Future<Response> Function() req,
|
|
|
|
Function(Map<String, dynamic> body)? onOK,
|
2023-03-23 14:48:53 +01:00
|
|
|
bool Function()? onNetworkErr,
|
|
|
|
bool Function()? onUnknownErr,
|
2023-03-24 21:10:42 +01:00
|
|
|
Function()? onAnyErr,
|
2023-03-23 14:48:53 +01:00
|
|
|
Function()? after,
|
2023-03-25 17:18:46 +01:00
|
|
|
bool Function(Map<String, dynamic>)? onServerErr}) async {
|
2023-03-23 14:48:53 +01:00
|
|
|
Response res;
|
|
|
|
try {
|
2023-03-25 17:18:46 +01:00
|
|
|
res = await req();
|
2023-03-23 14:48:53 +01:00
|
|
|
} catch (_) {
|
|
|
|
// network error
|
|
|
|
bool showBar = true;
|
|
|
|
|
|
|
|
if (onNetworkErr != null) {
|
|
|
|
showBar = onNetworkErr();
|
|
|
|
}
|
|
|
|
|
|
|
|
if (showBar && sm != null) {
|
|
|
|
showSimpleSnackbar(sm, text: 'Network Error', action: 'Dismiss');
|
|
|
|
}
|
2023-03-24 21:10:42 +01:00
|
|
|
if (onAnyErr != null) {
|
|
|
|
onAnyErr();
|
|
|
|
}
|
2023-03-23 14:48:53 +01:00
|
|
|
if (after != null) {
|
|
|
|
after();
|
|
|
|
}
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
|
|
|
if (res.res == Result.ok) {
|
|
|
|
if (onOK != null) {
|
|
|
|
await onOK(res.body);
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
// server error
|
|
|
|
bool showBar = true;
|
|
|
|
|
|
|
|
if (onServerErr != null) {
|
|
|
|
showBar = onServerErr(res.body);
|
|
|
|
}
|
|
|
|
if (showBar && sm != null) {
|
|
|
|
showSimpleSnackbar(sm, text: errorAsString(res.body), action: 'OK');
|
|
|
|
}
|
2023-03-24 21:10:42 +01:00
|
|
|
if (onAnyErr != null) {
|
|
|
|
onAnyErr();
|
|
|
|
}
|
2023-03-23 14:48:53 +01:00
|
|
|
}
|
2023-03-24 21:10:42 +01:00
|
|
|
} catch (_) {
|
2023-03-23 14:48:53 +01:00
|
|
|
bool showBar = true;
|
|
|
|
|
|
|
|
if (onUnknownErr != null) {
|
|
|
|
showBar = onUnknownErr();
|
|
|
|
}
|
|
|
|
|
|
|
|
if (showBar && sm != null) {
|
|
|
|
showSimpleSnackbar(sm, text: 'Unknown Error', action: 'OK');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (after != null) {
|
|
|
|
after();
|
|
|
|
}
|
|
|
|
}
|