actions-test/lib/tools/fetch_wrapper.dart
Jakob Meier bb9a8621a0
Moved User into application wide conntext.
Every page (after login) has access
to the User object via context.read/watch<User>().

This reduces localstore and asnyc operations,
as the screens do not have to load the user every time.
Additionally this prevents anyone from
using the without a user object.
2023-03-25 17:18:46 +01:00

71 lines
1.6 KiB
Dart

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,
{required Future<Response> Function() req,
Function(Map<String, dynamic> body)? onOK,
bool Function()? onNetworkErr,
bool Function()? onUnknownErr,
Function()? onAnyErr,
Function()? after,
bool Function(Map<String, dynamic>)? onServerErr}) async {
Response res;
try {
res = await req();
} catch (_) {
// network error
bool showBar = true;
if (onNetworkErr != null) {
showBar = onNetworkErr();
}
if (showBar && sm != null) {
showSimpleSnackbar(sm, text: 'Network Error', action: 'Dismiss');
}
if (onAnyErr != null) {
onAnyErr();
}
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');
}
if (onAnyErr != null) {
onAnyErr();
}
}
} catch (_) {
bool showBar = true;
if (onUnknownErr != null) {
showBar = onUnknownErr();
}
if (showBar && sm != null) {
showSimpleSnackbar(sm, text: 'Unknown Error', action: 'OK');
}
}
if (after != null) {
after();
}
}