feat: implement API client with JSON handling and error mapping; enhance routing and state management in app shell

This commit is contained in:
Nils-Johan Gynther
2026-04-22 07:29:21 +02:00
parent 82ba334f2d
commit e8de1d3625
12 changed files with 586 additions and 133 deletions
+114 -11
View File
@@ -1,5 +1,9 @@
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'api_exception.dart';
/// Platform-neutral HTTP client.
/// API base URL is injected at build time via --dart-define=API_BASE_URL.
/// Default is same-origin '/api' to avoid mixed-content on HTTPS sites.
@@ -19,18 +23,117 @@ class ApiClient {
if (token != null) 'Authorization': 'Bearer $token',
};
Future<http.Response> get(String path, {String? token}) =>
_client.get(Uri.parse('$baseUrl$path'), headers: _headers(token: token));
Future<dynamic> getJson(String path, {String? token}) async {
final response = await _client.get(
Uri.parse('$baseUrl$path'),
headers: _headers(token: token),
);
return _decodeOrNull(_guardResponse(response));
}
Future<http.Response> post(String path, String body, {String? token}) =>
_client.post(Uri.parse('$baseUrl$path'),
headers: _headers(token: token), body: body);
Future<dynamic> postJson(
String path, {
Object? body,
String? token,
}) async {
final response = await _client.post(
Uri.parse('$baseUrl$path'),
headers: _headers(token: token),
body: body == null ? null : jsonEncode(body),
);
return _decodeOrNull(_guardResponse(response));
}
Future<http.Response> put(String path, String body, {String? token}) =>
_client.put(Uri.parse('$baseUrl$path'),
headers: _headers(token: token), body: body);
Future<dynamic> putJson(
String path, {
Object? body,
String? token,
}) async {
final response = await _client.put(
Uri.parse('$baseUrl$path'),
headers: _headers(token: token),
body: body == null ? null : jsonEncode(body),
);
return _decodeOrNull(_guardResponse(response));
}
Future<http.Response> delete(String path, {String? token}) =>
_client.delete(Uri.parse('$baseUrl$path'),
headers: _headers(token: token));
Future<dynamic> deleteJson(String path, {String? token}) async {
final response = await _client.delete(
Uri.parse('$baseUrl$path'),
headers: _headers(token: token),
);
return _decodeOrNull(_guardResponse(response));
}
http.Response _guardResponse(http.Response response) {
if (response.statusCode < 400) {
return response;
}
final parsedBody = _decodeOrNull(response);
final serverMessage = _extractMessage(parsedBody);
if (response.statusCode == 401) {
throw ApiException(
type: ApiErrorType.unauthorized,
statusCode: 401,
message: serverMessage ?? 'Unauthorized',
);
}
if (response.statusCode == 403) {
throw ApiException(
type: ApiErrorType.forbidden,
statusCode: 403,
message: serverMessage ?? 'Forbidden',
);
}
if (response.statusCode >= 500) {
throw ApiException(
type: ApiErrorType.server,
statusCode: response.statusCode,
message: serverMessage ?? 'Server error',
);
}
throw ApiException(
type: ApiErrorType.unknown,
statusCode: response.statusCode,
message: serverMessage ?? 'Request failed',
);
}
dynamic _decodeOrNull(http.Response response) {
final body = response.body.trim();
if (body.isEmpty) {
return null;
}
try {
return jsonDecode(body);
} catch (_) {
return body;
}
}
String? _extractMessage(dynamic parsedBody) {
if (parsedBody is Map<String, dynamic>) {
final message = parsedBody['message'];
if (message is String && message.trim().isNotEmpty) {
return message;
}
if (message is List && message.isNotEmpty) {
return message.first.toString();
}
final error = parsedBody['error'];
if (error is String && error.trim().isNotEmpty) {
return error;
}
}
if (parsedBody is String && parsedBody.trim().isNotEmpty) {
return parsedBody;
}
return null;
}
}
@@ -0,0 +1,21 @@
import 'api_exception.dart';
String mapErrorToUserMessage(Object error) {
if (error is ApiException) {
switch (error.type) {
case ApiErrorType.unauthorized:
return 'Din session har gatt ut. Logga in igen.';
case ApiErrorType.forbidden:
return 'Du saknar behorighet for denna funktion.';
case ApiErrorType.server:
return 'Serverfel uppstod. Forsok igen om en stund.';
case ApiErrorType.network:
return 'Natverksfel. Kontrollera anslutningen och forsok igen.';
case ApiErrorType.unknown:
return error.message.isNotEmpty
? error.message
: 'Ett ovantat fel uppstod.';
}
}
return 'Ett ovantat fel uppstod.';
}
+25
View File
@@ -0,0 +1,25 @@
enum ApiErrorType {
unauthorized,
forbidden,
server,
network,
unknown,
}
class ApiException implements Exception {
final ApiErrorType type;
final int? statusCode;
final String message;
const ApiException({
required this.type,
required this.message,
this.statusCode,
});
@override
String toString() {
final status = statusCode == null ? '' : ' (HTTP $statusCode)';
return 'ApiException$type$status: $message';
}
}
+47 -8
View File
@@ -1,24 +1,63 @@
import 'package:flutter/widgets.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../core/ui/app_shell.dart';
import '../../features/auth/data/auth_providers.dart';
import '../../features/recipes/presentation/recipes_screen.dart';
import '../../features/auth/presentation/login_screen.dart';
import '../../features/profile/presentation/profile_screen.dart';
final appRouterProvider = Provider<GoRouter>((ref) {
final authState = ref.watch(authStateProvider);
return GoRouter(
initialLocation: '/login',
initialLocation: '/',
redirect: (context, state) {
final isLoading = authState.isLoading;
final token = authState.valueOrNull;
final isLoggedIn = token != null && token.isNotEmpty;
final isLoginRoute = state.matchedLocation == '/login';
final isRootRoute = state.matchedLocation == '/';
if (isLoading) {
return null;
}
if (isRootRoute) {
return isLoggedIn ? '/recipes' : '/login';
}
if (!isLoggedIn && !isLoginRoute) {
return '/login';
}
if (isLoggedIn && isLoginRoute) {
return '/recipes';
}
return null;
},
routes: [
GoRoute(path: '/', builder: (context, state) => const SizedBox.shrink()),
GoRoute(
path: '/login',
builder: (context, state) => const LoginScreen(),
),
GoRoute(
path: '/recipes',
builder: (context, state) => const RecipesScreen(),
),
GoRoute(
path: '/profile',
builder: (context, state) => const ProfileScreen(),
ShellRoute(
builder: (context, state, child) {
return AppShell(location: state.uri.path, child: child);
},
routes: [
GoRoute(
path: '/recipes',
builder: (context, state) => const RecipesScreen(),
),
GoRoute(
path: '/profile',
builder: (context, state) => const ProfileScreen(),
),
],
),
],
);
+121
View File
@@ -0,0 +1,121 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../features/auth/data/auth_providers.dart';
class AppShell extends ConsumerWidget {
final String location;
final Widget child;
const AppShell({
super.key,
required this.location,
required this.child,
});
static const _destinations = [
_AppDestination(
path: '/recipes',
title: 'Recept',
icon: Icons.restaurant_menu,
label: 'Recept',
),
_AppDestination(
path: '/profile',
title: 'Profil',
icon: Icons.person,
label: 'Profil',
),
];
int _selectedIndex() {
final index = _destinations.indexWhere(
(destination) => location.startsWith(destination.path),
);
return index < 0 ? 0 : index;
}
@override
Widget build(BuildContext context, WidgetRef ref) {
final selectedIndex = _selectedIndex();
final selectedDestination = _destinations[selectedIndex];
final isWide = MediaQuery.of(context).size.width >= 900;
Future<void> logout() async {
await ref.read(authStateProvider.notifier).logout();
if (context.mounted) {
context.go('/login');
}
}
void navigateTo(int index) {
final target = _destinations[index].path;
if (target != location && context.mounted) {
context.go(target);
}
}
return Scaffold(
appBar: AppBar(
title: Text(selectedDestination.title),
actions: [
IconButton(
tooltip: 'Logga ut',
icon: const Icon(Icons.logout),
onPressed: logout,
),
],
),
body: isWide
? Row(
children: [
NavigationRail(
selectedIndex: selectedIndex,
onDestinationSelected: navigateTo,
labelType: NavigationRailLabelType.all,
destinations: _destinations
.map(
(destination) => NavigationRailDestination(
icon: Icon(destination.icon),
label: Text(destination.label),
),
)
.toList(),
),
const VerticalDivider(width: 1),
Expanded(child: child),
],
)
: child,
bottomNavigationBar: isWide
? null
: NavigationBar(
selectedIndex: selectedIndex,
onDestinationSelected: navigateTo,
destinations: _destinations
.map(
(destination) => NavigationDestination(
icon: Icon(destination.icon),
label: destination.label,
),
)
.toList(),
),
);
}
}
class _AppDestination {
final String path;
final String title;
final IconData icon;
final String label;
const _AppDestination({
required this.path,
required this.title,
required this.icon,
required this.label,
});
}
@@ -0,0 +1,94 @@
import 'package:flutter/material.dart';
class LoadingStateView extends StatelessWidget {
final String? label;
const LoadingStateView({super.key, this.label});
@override
Widget build(BuildContext context) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const CircularProgressIndicator(),
if (label != null) ...[
const SizedBox(height: 12),
Text(label!),
],
],
),
);
}
}
class EmptyStateView extends StatelessWidget {
final String title;
final String? description;
const EmptyStateView({
super.key,
required this.title,
this.description,
});
@override
Widget build(BuildContext context) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(title, style: Theme.of(context).textTheme.titleMedium),
if (description != null) ...[
const SizedBox(height: 8),
Text(
description!,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodyMedium,
),
],
],
),
),
);
}
}
class ErrorStateView extends StatelessWidget {
final String message;
final VoidCallback? onRetry;
const ErrorStateView({
super.key,
required this.message,
this.onRetry,
});
@override
Widget build(BuildContext context) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
message,
textAlign: TextAlign.center,
style: TextStyle(color: Theme.of(context).colorScheme.error),
),
if (onRetry != null) ...[
const SizedBox(height: 12),
OutlinedButton(
onPressed: onRetry,
child: const Text('Forsok igen'),
),
],
],
),
),
);
}
}
@@ -1,5 +1,5 @@
import 'dart:convert';
import '../../../core/api/api_client.dart';
import '../../../core/api/api_exception.dart';
import '../../../core/platform/token_storage.dart';
class AuthRepository {
@@ -9,17 +9,37 @@ class AuthRepository {
AuthRepository(this._api, this._storage);
Future<String> login(String username, String password) async {
final response = await _api.post(
'/auth/login',
jsonEncode({'username': username, 'password': password}),
);
if (response.statusCode != 200 && response.statusCode != 201) {
throw Exception('Login failed: ${response.statusCode}');
try {
final data = await _api.postJson(
'/auth/login',
body: {'username': username, 'password': password},
);
if (data is! Map<String, dynamic>) {
throw const ApiException(
type: ApiErrorType.unknown,
message: 'Ogiltigt svar fran servern.',
);
}
final token = data['accessToken'];
if (token is! String || token.isEmpty) {
throw const ApiException(
type: ApiErrorType.unknown,
message: 'Svar saknar access token.',
);
}
await _storage.saveToken(token);
return token;
} on ApiException {
rethrow;
} catch (_) {
throw const ApiException(
type: ApiErrorType.network,
message: 'Kunde inte na servern.',
);
}
final data = jsonDecode(response.body) as Map<String, dynamic>;
final token = data['accessToken'] as String;
await _storage.saveToken(token);
return token;
}
Future<void> logout() => _storage.deleteToken();
@@ -1,6 +1,8 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../core/api/api_error_mapper.dart';
import '../data/auth_providers.dart';
class LoginScreen extends ConsumerStatefulWidget {
@@ -72,7 +74,8 @@ class _LoginScreenState extends ConsumerState<LoginScreen> {
Padding(
padding: const EdgeInsets.only(top: 12),
child: Text(
'Inloggning misslyckades',
mapErrorToUserMessage(authState.error!),
textAlign: TextAlign.center,
style: TextStyle(color: Theme.of(context).colorScheme.error),
),
),
@@ -1,37 +1,12 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../auth/data/auth_providers.dart';
class ProfileScreen extends ConsumerWidget {
class ProfileScreen extends StatelessWidget {
const ProfileScreen({super.key});
Future<void> _logout(BuildContext context, WidgetRef ref) async {
await ref.read(authStateProvider.notifier).logout();
if (context.mounted) context.go('/login');
}
@override
Widget build(BuildContext context, WidgetRef ref) {
return Scaffold(
appBar: AppBar(
title: const Text('Profil'),
actions: [
IconButton(
tooltip: 'Recept',
icon: const Icon(Icons.restaurant_menu),
onPressed: () => context.go('/recipes'),
),
IconButton(
tooltip: 'Logga ut',
icon: const Icon(Icons.logout),
onPressed: () => _logout(context, ref),
),
],
),
body: const Center(
child: Text('Profilsida (grundversion)'),
),
Widget build(BuildContext context) {
return const Center(
child: Text('Profilsida (grundversion)'),
);
}
}
@@ -1,5 +1,5 @@
import 'dart:convert';
import '../../../core/api/api_client.dart';
import '../../../core/api/api_exception.dart';
import '../domain/recipe.dart';
class RecipeRepository {
@@ -8,13 +8,26 @@ class RecipeRepository {
RecipeRepository(this._api);
Future<List<Recipe>> fetchRecipes({String? token}) async {
final response = await _api.get('/recipes', token: token);
if (response.statusCode != 200) {
throw Exception('Failed to load recipes: ${response.statusCode}');
try {
final data = await _api.getJson('/recipes', token: token);
if (data is! List) {
throw const ApiException(
type: ApiErrorType.unknown,
message: 'Ogiltigt svar fran servern.',
);
}
return data
.map((e) => Recipe.fromJson(e as Map<String, dynamic>))
.toList();
} on ApiException {
rethrow;
} catch (_) {
throw const ApiException(
type: ApiErrorType.network,
message: 'Kunde inte hamta recept.',
);
}
final List<dynamic> data = jsonDecode(response.body) as List<dynamic>;
return data
.map((e) => Recipe.fromJson(e as Map<String, dynamic>))
.toList();
}
}
@@ -1,40 +1,31 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../auth/data/auth_providers.dart';
import '../../../core/api/api_error_mapper.dart';
import '../../../core/ui/async_state_views.dart';
import '../data/recipe_providers.dart';
class RecipesScreen extends ConsumerWidget {
const RecipesScreen({super.key});
Future<void> _logout(BuildContext context, WidgetRef ref) async {
await ref.read(authStateProvider.notifier).logout();
if (context.mounted) context.go('/login');
}
@override
Widget build(BuildContext context, WidgetRef ref) {
final recipesAsync = ref.watch(recipesProvider);
return Scaffold(
appBar: AppBar(
title: const Text('Recept'),
actions: [
IconButton(
tooltip: 'Profil',
icon: const Icon(Icons.person),
onPressed: () => context.go('/profile'),
),
IconButton(
tooltip: 'Logga ut',
icon: const Icon(Icons.logout),
onPressed: () => _logout(context, ref),
),
],
return recipesAsync.when(
loading: () => const LoadingStateView(label: 'Laddar recept...'),
error: (error, _) => ErrorStateView(
message: mapErrorToUserMessage(error),
onRetry: () => ref.invalidate(recipesProvider),
),
body: recipesAsync.when(
loading: () => const Center(child: CircularProgressIndicator()),
error: (e, _) => Center(child: Text('Fel: $e')),
data: (recipes) => ListView.builder(
data: (recipes) {
if (recipes.isEmpty) {
return const EmptyStateView(
title: 'Inga recept hittades',
description: 'Lagg till ett recept for att komma igang.',
);
}
return ListView.builder(
itemCount: recipes.length,
itemBuilder: (context, index) {
final recipe = recipes[index];
@@ -52,8 +43,8 @@ class RecipesScreen extends ConsumerWidget {
: null,
);
},
),
),
);
},
);
}
}