5d333522a5
and rewrote the component's network requests. showSimpleSnackbar, allows displaying a simple snackbar, with text and one action button, that can be clicked. doNetworkRequest is supposed to be a wrapper for the already existing post* functions. It aims to make network requests and error handling easier, by containing all the try&catch blocks and being able to show snackbars.
100 lines
2.2 KiB
Dart
100 lines
2.2 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/backend/user.dart';
|
|
import 'package:outbag_app/tools/snackbar.dart';
|
|
|
|
void doNetworkRequest(ScaffoldMessengerState? sm,
|
|
{required Future<Response> Function(User?) req,
|
|
Function(Map<String, dynamic>)? onOK,
|
|
bool Function()? onNetworkErr,
|
|
bool Function()? onUnknownErr,
|
|
bool Function()? onUserErr,
|
|
Function()? after,
|
|
bool Function(Map<String, dynamic>)? onServerErr,
|
|
bool needUser = true}) async {
|
|
User? user;
|
|
try {
|
|
user = await User.fromDisk();
|
|
} catch (_) {
|
|
// no user data available
|
|
if (needUser) {
|
|
// show error & quit
|
|
bool showBar = true;
|
|
|
|
if (onUserErr != null) {
|
|
showBar = onUserErr();
|
|
}
|
|
|
|
if (showBar && sm != null) {
|
|
showSimpleSnackbar(sm, text: 'No user found', action: 'Authorize',
|
|
onTap: () {
|
|
try {
|
|
// try to remove broken user
|
|
User.removeDisk();
|
|
} catch (_) {}
|
|
});
|
|
}
|
|
if (after != null) {
|
|
after();
|
|
}
|
|
return;
|
|
}
|
|
}
|
|
|
|
Response res;
|
|
try {
|
|
res = await req(user);
|
|
} catch (_) {
|
|
// network error
|
|
bool showBar = true;
|
|
|
|
if (onNetworkErr != null) {
|
|
showBar = onNetworkErr();
|
|
}
|
|
|
|
if (showBar && sm != null) {
|
|
showSimpleSnackbar(sm, text: 'Network Error', action: 'Dismiss');
|
|
}
|
|
|
|
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');
|
|
}
|
|
}
|
|
} catch (e) {
|
|
bool showBar = true;
|
|
|
|
print(e);
|
|
|
|
if (onUnknownErr != null) {
|
|
showBar = onUnknownErr();
|
|
}
|
|
|
|
if (showBar && sm != null) {
|
|
showSimpleSnackbar(sm, text: 'Unknown Error', action: 'OK');
|
|
}
|
|
}
|
|
|
|
if (after != null) {
|
|
after();
|
|
}
|
|
}
|