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
@@ -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,
);
},
),
),
);
},
);
}
}