feat: implement Iteration 0 foundation (backend + Flutter client)
Backend (Go): - Project structure with chi router, pgxpool, goose migrations - JWT auth (access/refresh tokens) with Firebase token verification - NoopTokenVerifier for local dev without Firebase credentials - PostgreSQL user repository with atomic profile updates (transactions) - Mifflin-St Jeor calorie calculation based on profile data - REST API: POST /auth/login, /auth/refresh, /auth/logout, GET/PUT /profile, GET /health - Middleware: auth, CORS (localhost wildcard), logging, recovery, request_id - Unit tests (51 passing) and integration tests (testcontainers) - Docker Compose setup with postgres healthcheck and graceful shutdown Flutter client: - Riverpod state management with GoRouter navigation - Firebase Auth (email/password + Google sign-in with web popup support) - Platform-aware API URLs (web/Android/iOS) - Dio HTTP client with JWT auth interceptor and concurrent refresh handling - Secure token storage - Screens: Login, Register, Home (tabs: Menu, Recipes, Products, Profile) - Unit tests (17 passing) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
21
client/lib/app.dart
Normal file
21
client/lib/app.dart
Normal file
@@ -0,0 +1,21 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import 'core/router/app_router.dart';
|
||||
import 'core/theme/app_theme.dart';
|
||||
|
||||
class App extends ConsumerWidget {
|
||||
const App({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final router = ref.watch(routerProvider);
|
||||
|
||||
return MaterialApp.router(
|
||||
title: 'FoodAI',
|
||||
theme: appTheme(),
|
||||
routerConfig: router,
|
||||
debugShowCheckedModeBanner: false,
|
||||
);
|
||||
}
|
||||
}
|
||||
45
client/lib/core/api/api_client.dart
Normal file
45
client/lib/core/api/api_client.dart
Normal file
@@ -0,0 +1,45 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import '../auth/secure_storage.dart';
|
||||
import 'auth_interceptor.dart';
|
||||
|
||||
class ApiClient {
|
||||
late final Dio _dio;
|
||||
|
||||
ApiClient({required String baseUrl, required SecureStorageService storage}) {
|
||||
_dio = Dio(BaseOptions(
|
||||
baseUrl: baseUrl,
|
||||
connectTimeout: const Duration(seconds: 10),
|
||||
receiveTimeout: const Duration(seconds: 30),
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
));
|
||||
|
||||
_dio.interceptors.addAll([
|
||||
AuthInterceptor(storage: storage, dio: _dio),
|
||||
LogInterceptor(requestBody: true, responseBody: true),
|
||||
]);
|
||||
}
|
||||
|
||||
/// Exposed for testing only.
|
||||
ApiClient.withDio(this._dio);
|
||||
|
||||
Future<Map<String, dynamic>> get(String path,
|
||||
{Map<String, dynamic>? params}) async {
|
||||
final response = await _dio.get(path, queryParameters: params);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>> post(String path, {dynamic data}) async {
|
||||
final response = await _dio.post(path, data: data);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>> put(String path, {dynamic data}) async {
|
||||
final response = await _dio.put(path, data: data);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>> delete(String path) async {
|
||||
final response = await _dio.delete(path);
|
||||
return response.data;
|
||||
}
|
||||
}
|
||||
22
client/lib/core/api/api_exceptions.dart
Normal file
22
client/lib/core/api/api_exceptions.dart
Normal file
@@ -0,0 +1,22 @@
|
||||
class ApiException implements Exception {
|
||||
final String message;
|
||||
final int? statusCode;
|
||||
|
||||
const ApiException(this.message, {this.statusCode});
|
||||
|
||||
@override
|
||||
String toString() => 'ApiException($statusCode): $message';
|
||||
}
|
||||
|
||||
class UnauthorizedException extends ApiException {
|
||||
const UnauthorizedException([super.message = 'Unauthorized'])
|
||||
: super(statusCode: 401);
|
||||
}
|
||||
|
||||
class BadRequestException extends ApiException {
|
||||
const BadRequestException(super.message) : super(statusCode: 400);
|
||||
}
|
||||
|
||||
class NetworkException extends ApiException {
|
||||
const NetworkException([super.message = 'No internet connection']);
|
||||
}
|
||||
94
client/lib/core/api/auth_interceptor.dart
Normal file
94
client/lib/core/api/auth_interceptor.dart
Normal file
@@ -0,0 +1,94 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import '../auth/secure_storage.dart';
|
||||
|
||||
class AuthInterceptor extends Interceptor {
|
||||
final SecureStorageService _storage;
|
||||
final Dio _dio;
|
||||
|
||||
// Prevents multiple simultaneous token refresh requests
|
||||
bool _isRefreshing = false;
|
||||
final List<({RequestOptions options, ErrorInterceptorHandler handler})>
|
||||
_pendingRequests = [];
|
||||
|
||||
AuthInterceptor({required SecureStorageService storage, required Dio dio})
|
||||
: _storage = storage,
|
||||
_dio = dio;
|
||||
|
||||
@override
|
||||
Future<void> onRequest(
|
||||
RequestOptions options,
|
||||
RequestInterceptorHandler handler,
|
||||
) async {
|
||||
if (options.path.startsWith('/auth/')) {
|
||||
return handler.next(options);
|
||||
}
|
||||
|
||||
final token = await _storage.getAccessToken();
|
||||
if (token != null) {
|
||||
options.headers['Authorization'] = 'Bearer $token';
|
||||
}
|
||||
handler.next(options);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> onError(
|
||||
DioException err,
|
||||
ErrorInterceptorHandler handler,
|
||||
) async {
|
||||
if (err.response?.statusCode != 401) {
|
||||
return handler.next(err);
|
||||
}
|
||||
|
||||
final refreshToken = await _storage.getRefreshToken();
|
||||
if (refreshToken == null) {
|
||||
return handler.next(err);
|
||||
}
|
||||
|
||||
// If a refresh is already in progress, queue this request
|
||||
if (_isRefreshing) {
|
||||
_pendingRequests.add((options: err.requestOptions, handler: handler));
|
||||
return;
|
||||
}
|
||||
|
||||
_isRefreshing = true;
|
||||
try {
|
||||
final response = await _dio.post('/auth/refresh', data: {
|
||||
'refresh_token': refreshToken,
|
||||
});
|
||||
|
||||
final newAccessToken = response.data['access_token'] as String;
|
||||
final newRefreshToken = response.data['refresh_token'] as String;
|
||||
|
||||
await _storage.saveTokens(
|
||||
accessToken: newAccessToken,
|
||||
refreshToken: newRefreshToken,
|
||||
);
|
||||
|
||||
// Retry the original request
|
||||
final retryOptions = err.requestOptions;
|
||||
retryOptions.headers['Authorization'] = 'Bearer $newAccessToken';
|
||||
final retryResponse = await _dio.fetch(retryOptions);
|
||||
handler.resolve(retryResponse);
|
||||
|
||||
// Retry all pending requests with the new token
|
||||
for (final pending in _pendingRequests) {
|
||||
pending.options.headers['Authorization'] = 'Bearer $newAccessToken';
|
||||
try {
|
||||
final r = await _dio.fetch(pending.options);
|
||||
pending.handler.resolve(r);
|
||||
} catch (e) {
|
||||
pending.handler.next(err);
|
||||
}
|
||||
}
|
||||
} catch (_) {
|
||||
await _storage.clearTokens();
|
||||
handler.next(err);
|
||||
for (final pending in _pendingRequests) {
|
||||
pending.handler.next(err);
|
||||
}
|
||||
} finally {
|
||||
_isRefreshing = false;
|
||||
_pendingRequests.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
160
client/lib/core/auth/auth_provider.dart
Normal file
160
client/lib/core/auth/auth_provider.dart
Normal file
@@ -0,0 +1,160 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../shared/models/user.dart';
|
||||
import '../api/api_client.dart';
|
||||
import '../config/app_config.dart';
|
||||
import 'auth_service.dart';
|
||||
import 'secure_storage.dart';
|
||||
import 'package:firebase_auth/firebase_auth.dart' as fb;
|
||||
|
||||
enum AuthStatus { unknown, authenticated, unauthenticated }
|
||||
|
||||
class AuthState {
|
||||
final AuthStatus status;
|
||||
final User? user;
|
||||
final bool isLoading;
|
||||
final String? error;
|
||||
|
||||
const AuthState({
|
||||
this.status = AuthStatus.unknown,
|
||||
this.user,
|
||||
this.isLoading = false,
|
||||
this.error,
|
||||
});
|
||||
|
||||
AuthState copyWith({
|
||||
AuthStatus? status,
|
||||
User? user,
|
||||
bool? isLoading,
|
||||
String? error,
|
||||
}) {
|
||||
return AuthState(
|
||||
status: status ?? this.status,
|
||||
user: user ?? this.user,
|
||||
isLoading: isLoading ?? this.isLoading,
|
||||
error: error,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class AuthNotifier extends StateNotifier<AuthState> {
|
||||
final AuthService? _authService;
|
||||
|
||||
AuthNotifier(AuthService authService) : _authService = authService, super(const AuthState()) {
|
||||
_checkAuth();
|
||||
}
|
||||
|
||||
@visibleForTesting
|
||||
AuthNotifier.test(super.initialState)
|
||||
: _authService = null;
|
||||
|
||||
Future<void> _checkAuth() async {
|
||||
final isAuth = await _authService!.isAuthenticated();
|
||||
state = state.copyWith(
|
||||
status: isAuth ? AuthStatus.authenticated : AuthStatus.unauthenticated,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> signInWithEmail(String email, String password) async {
|
||||
state = state.copyWith(isLoading: true, error: null);
|
||||
try {
|
||||
final user = await _authService!.signInWithEmail(email, password);
|
||||
state = AuthState(
|
||||
status: AuthStatus.authenticated,
|
||||
user: user,
|
||||
);
|
||||
} catch (e) {
|
||||
state = state.copyWith(
|
||||
isLoading: false,
|
||||
error: _mapError(e),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> signInWithGoogle() async {
|
||||
state = state.copyWith(isLoading: true, error: null);
|
||||
try {
|
||||
final user = await _authService!.signInWithGoogle();
|
||||
state = AuthState(
|
||||
status: AuthStatus.authenticated,
|
||||
user: user,
|
||||
);
|
||||
} catch (e) {
|
||||
state = state.copyWith(
|
||||
isLoading: false,
|
||||
error: _mapError(e),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> register(String email, String password, String name) async {
|
||||
state = state.copyWith(isLoading: true, error: null);
|
||||
try {
|
||||
final user =
|
||||
await _authService!.registerWithEmail(email, password, name);
|
||||
state = AuthState(
|
||||
status: AuthStatus.authenticated,
|
||||
user: user,
|
||||
);
|
||||
} catch (e) {
|
||||
state = state.copyWith(
|
||||
isLoading: false,
|
||||
error: _mapError(e),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> signOut() async {
|
||||
await _authService!.signOut();
|
||||
state = const AuthState(status: AuthStatus.unauthenticated);
|
||||
}
|
||||
|
||||
String _mapError(dynamic e) {
|
||||
if (e is fb.FirebaseAuthException) {
|
||||
switch (e.code) {
|
||||
case 'wrong-password':
|
||||
case 'user-not-found':
|
||||
return 'Неверный email или пароль';
|
||||
case 'email-already-in-use':
|
||||
return 'Email уже зарегистрирован';
|
||||
case 'weak-password':
|
||||
return 'Пароль слишком простой';
|
||||
case 'invalid-email':
|
||||
return 'Некорректный email';
|
||||
default:
|
||||
return 'Ошибка авторизации: ${e.message}';
|
||||
}
|
||||
}
|
||||
return 'Произошла ошибка. Попробуйте позже.';
|
||||
}
|
||||
}
|
||||
|
||||
final appConfigProvider = Provider<AppConfig>((ref) {
|
||||
return AppConfig.development;
|
||||
});
|
||||
|
||||
final secureStorageProvider = Provider<SecureStorageService>((ref) {
|
||||
return SecureStorageService();
|
||||
});
|
||||
|
||||
final apiClientProvider = Provider<ApiClient>((ref) {
|
||||
final config = ref.read(appConfigProvider);
|
||||
final storage = ref.read(secureStorageProvider);
|
||||
return ApiClient(
|
||||
baseUrl: config.apiBaseUrl,
|
||||
storage: storage,
|
||||
);
|
||||
});
|
||||
|
||||
final authServiceProvider = Provider<AuthService>((ref) {
|
||||
return AuthService(
|
||||
firebaseAuth: fb.FirebaseAuth.instance,
|
||||
apiClient: ref.read(apiClientProvider),
|
||||
storage: ref.read(secureStorageProvider),
|
||||
);
|
||||
});
|
||||
|
||||
final authProvider = StateNotifierProvider<AuthNotifier, AuthState>((ref) {
|
||||
return AuthNotifier(ref.read(authServiceProvider));
|
||||
});
|
||||
92
client/lib/core/auth/auth_service.dart
Normal file
92
client/lib/core/auth/auth_service.dart
Normal file
@@ -0,0 +1,92 @@
|
||||
import 'package:firebase_auth/firebase_auth.dart' as fb;
|
||||
import 'package:flutter/foundation.dart' show kIsWeb;
|
||||
import 'package:google_sign_in/google_sign_in.dart';
|
||||
|
||||
import '../../shared/models/user.dart';
|
||||
import '../api/api_client.dart';
|
||||
import 'secure_storage.dart';
|
||||
|
||||
class AuthService {
|
||||
final fb.FirebaseAuth _firebaseAuth;
|
||||
final ApiClient _apiClient;
|
||||
final SecureStorageService _storage;
|
||||
|
||||
AuthService({
|
||||
required fb.FirebaseAuth firebaseAuth,
|
||||
required ApiClient apiClient,
|
||||
required SecureStorageService storage,
|
||||
}) : _firebaseAuth = firebaseAuth,
|
||||
_apiClient = apiClient,
|
||||
_storage = storage;
|
||||
|
||||
Future<User> signInWithGoogle() async {
|
||||
if (kIsWeb) {
|
||||
// На вебе используем signInWithPopup — открывает Google popup в браузере
|
||||
final provider = fb.GoogleAuthProvider();
|
||||
final userCredential = await _firebaseAuth.signInWithPopup(provider);
|
||||
return _authenticateWithBackend(userCredential);
|
||||
} else {
|
||||
// На мобильных используем google_sign_in
|
||||
final googleUser = await GoogleSignIn().signIn();
|
||||
if (googleUser == null) {
|
||||
throw Exception('Google sign-in cancelled');
|
||||
}
|
||||
final googleAuth = await googleUser.authentication;
|
||||
final credential = fb.GoogleAuthProvider.credential(
|
||||
accessToken: googleAuth.accessToken,
|
||||
idToken: googleAuth.idToken,
|
||||
);
|
||||
final userCredential =
|
||||
await _firebaseAuth.signInWithCredential(credential);
|
||||
return _authenticateWithBackend(userCredential);
|
||||
}
|
||||
}
|
||||
|
||||
Future<User> signInWithEmail(String email, String password) async {
|
||||
final userCredential = await _firebaseAuth.signInWithEmailAndPassword(
|
||||
email: email,
|
||||
password: password,
|
||||
);
|
||||
return _authenticateWithBackend(userCredential);
|
||||
}
|
||||
|
||||
Future<User> registerWithEmail(
|
||||
String email, String password, String name) async {
|
||||
final userCredential = await _firebaseAuth.createUserWithEmailAndPassword(
|
||||
email: email,
|
||||
password: password,
|
||||
);
|
||||
await userCredential.user!.updateDisplayName(name);
|
||||
return _authenticateWithBackend(userCredential);
|
||||
}
|
||||
|
||||
Future<User> _authenticateWithBackend(fb.UserCredential credential) async {
|
||||
final idToken = await credential.user!.getIdToken();
|
||||
|
||||
final response = await _apiClient.post('/auth/login', data: {
|
||||
'firebase_token': idToken,
|
||||
});
|
||||
|
||||
await _storage.saveTokens(
|
||||
accessToken: response['access_token'],
|
||||
refreshToken: response['refresh_token'],
|
||||
);
|
||||
|
||||
return User.fromJson(response['user']);
|
||||
}
|
||||
|
||||
Future<void> signOut() async {
|
||||
try {
|
||||
await _apiClient.post('/auth/logout');
|
||||
} catch (_) {
|
||||
// Don't block logout on backend failure
|
||||
}
|
||||
await _firebaseAuth.signOut();
|
||||
await _storage.clearTokens();
|
||||
}
|
||||
|
||||
Future<bool> isAuthenticated() async {
|
||||
final token = await _storage.getAccessToken();
|
||||
return token != null;
|
||||
}
|
||||
}
|
||||
24
client/lib/core/auth/secure_storage.dart
Normal file
24
client/lib/core/auth/secure_storage.dart
Normal file
@@ -0,0 +1,24 @@
|
||||
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
||||
|
||||
class SecureStorageService {
|
||||
final FlutterSecureStorage _storage;
|
||||
|
||||
SecureStorageService({FlutterSecureStorage? storage})
|
||||
: _storage = storage ?? const FlutterSecureStorage();
|
||||
|
||||
Future<void> saveTokens({
|
||||
required String accessToken,
|
||||
required String refreshToken,
|
||||
}) async {
|
||||
await _storage.write(key: 'access_token', value: accessToken);
|
||||
await _storage.write(key: 'refresh_token', value: refreshToken);
|
||||
}
|
||||
|
||||
Future<String?> getAccessToken() => _storage.read(key: 'access_token');
|
||||
Future<String?> getRefreshToken() => _storage.read(key: 'refresh_token');
|
||||
|
||||
Future<void> clearTokens() async {
|
||||
await _storage.delete(key: 'access_token');
|
||||
await _storage.delete(key: 'refresh_token');
|
||||
}
|
||||
}
|
||||
25
client/lib/core/config/app_config.dart
Normal file
25
client/lib/core/config/app_config.dart
Normal file
@@ -0,0 +1,25 @@
|
||||
import 'package:flutter/foundation.dart' show kIsWeb, defaultTargetPlatform, TargetPlatform;
|
||||
|
||||
class AppConfig {
|
||||
final String apiBaseUrl;
|
||||
|
||||
const AppConfig({required this.apiBaseUrl});
|
||||
|
||||
static AppConfig get development {
|
||||
if (kIsWeb) {
|
||||
return const AppConfig(apiBaseUrl: 'http://localhost:9090');
|
||||
}
|
||||
switch (defaultTargetPlatform) {
|
||||
case TargetPlatform.android:
|
||||
return const AppConfig(apiBaseUrl: 'http://10.0.2.2:9090');
|
||||
case TargetPlatform.iOS:
|
||||
return const AppConfig(apiBaseUrl: 'http://localhost:9090');
|
||||
default:
|
||||
return const AppConfig(apiBaseUrl: 'http://localhost:9090');
|
||||
}
|
||||
}
|
||||
|
||||
static const production = AppConfig(
|
||||
apiBaseUrl: 'https://api.food-ai.app',
|
||||
);
|
||||
}
|
||||
93
client/lib/core/router/app_router.dart
Normal file
93
client/lib/core/router/app_router.dart
Normal file
@@ -0,0 +1,93 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
import '../auth/auth_provider.dart';
|
||||
import '../../features/auth/login_screen.dart';
|
||||
import '../../features/auth/register_screen.dart';
|
||||
import '../../features/home/home_screen.dart';
|
||||
import '../../features/products/products_screen.dart';
|
||||
import '../../features/menu/menu_screen.dart';
|
||||
import '../../features/recipes/recipes_screen.dart';
|
||||
import '../../features/profile/profile_screen.dart';
|
||||
|
||||
final routerProvider = Provider<GoRouter>((ref) {
|
||||
final authState = ref.watch(authProvider);
|
||||
|
||||
return GoRouter(
|
||||
initialLocation: '/home',
|
||||
redirect: (context, state) {
|
||||
final isLoggedIn = authState.status == AuthStatus.authenticated;
|
||||
final isAuthRoute = state.matchedLocation.startsWith('/auth');
|
||||
|
||||
if (authState.status == AuthStatus.unknown) return null;
|
||||
if (!isLoggedIn && !isAuthRoute) return '/auth/login';
|
||||
if (isLoggedIn && isAuthRoute) return '/home';
|
||||
return null;
|
||||
},
|
||||
routes: [
|
||||
GoRoute(
|
||||
path: '/auth/login',
|
||||
builder: (_, __) => const LoginScreen(),
|
||||
),
|
||||
GoRoute(
|
||||
path: '/auth/register',
|
||||
builder: (_, __) => const RegisterScreen(),
|
||||
),
|
||||
ShellRoute(
|
||||
builder: (context, state, child) => MainShell(child: child),
|
||||
routes: [
|
||||
GoRoute(path: '/home', builder: (_, __) => const HomeScreen()),
|
||||
GoRoute(
|
||||
path: '/products',
|
||||
builder: (_, __) => const ProductsScreen()),
|
||||
GoRoute(path: '/menu', builder: (_, __) => const MenuScreen()),
|
||||
GoRoute(
|
||||
path: '/recipes', builder: (_, __) => const RecipesScreen()),
|
||||
GoRoute(
|
||||
path: '/profile', builder: (_, __) => const ProfileScreen()),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
});
|
||||
|
||||
class MainShell extends StatelessWidget {
|
||||
final Widget child;
|
||||
|
||||
const MainShell({super.key, required this.child});
|
||||
|
||||
static const _tabs = [
|
||||
'/home',
|
||||
'/products',
|
||||
'/menu',
|
||||
'/recipes',
|
||||
'/profile',
|
||||
];
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final location = GoRouterState.of(context).matchedLocation;
|
||||
final currentIndex = _tabs.indexOf(location).clamp(0, _tabs.length - 1);
|
||||
|
||||
return Scaffold(
|
||||
body: child,
|
||||
bottomNavigationBar: BottomNavigationBar(
|
||||
currentIndex: currentIndex,
|
||||
onTap: (index) => context.go(_tabs[index]),
|
||||
items: const [
|
||||
BottomNavigationBarItem(
|
||||
icon: Icon(Icons.home), label: 'Главная'),
|
||||
BottomNavigationBarItem(
|
||||
icon: Icon(Icons.kitchen), label: 'Продукты'),
|
||||
BottomNavigationBarItem(
|
||||
icon: Icon(Icons.calendar_month), label: 'Меню'),
|
||||
BottomNavigationBarItem(
|
||||
icon: Icon(Icons.menu_book), label: 'Рецепты'),
|
||||
BottomNavigationBarItem(
|
||||
icon: Icon(Icons.person), label: 'Профиль'),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
29
client/lib/core/theme/app_colors.dart
Normal file
29
client/lib/core/theme/app_colors.dart
Normal file
@@ -0,0 +1,29 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
abstract class AppColors {
|
||||
// Primary
|
||||
static const primary = Color(0xFF4CAF50);
|
||||
static const primaryLight = Color(0xFF81C784);
|
||||
static const primaryDark = Color(0xFF388E3C);
|
||||
|
||||
// Accent
|
||||
static const accent = Color(0xFFFF9800);
|
||||
|
||||
// Background
|
||||
static const background = Color(0xFFF5F5F5);
|
||||
static const surface = Color(0xFFFFFFFF);
|
||||
|
||||
// Text
|
||||
static const textPrimary = Color(0xFF212121);
|
||||
static const textSecondary = Color(0xFF757575);
|
||||
|
||||
// Status
|
||||
static const error = Color(0xFFE53935);
|
||||
static const warning = Color(0xFFFFA726);
|
||||
static const success = Color(0xFF66BB6A);
|
||||
|
||||
// Shelf life indicators
|
||||
static const freshGreen = Color(0xFF4CAF50);
|
||||
static const warningYellow = Color(0xFFFFC107);
|
||||
static const expiredRed = Color(0xFFE53935);
|
||||
}
|
||||
31
client/lib/core/theme/app_theme.dart
Normal file
31
client/lib/core/theme/app_theme.dart
Normal file
@@ -0,0 +1,31 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'app_colors.dart';
|
||||
|
||||
ThemeData appTheme() {
|
||||
return ThemeData(
|
||||
useMaterial3: true,
|
||||
colorSchemeSeed: AppColors.primary,
|
||||
scaffoldBackgroundColor: AppColors.background,
|
||||
appBarTheme: const AppBarTheme(
|
||||
centerTitle: true,
|
||||
elevation: 0,
|
||||
backgroundColor: AppColors.surface,
|
||||
foregroundColor: AppColors.textPrimary,
|
||||
),
|
||||
bottomNavigationBarTheme: const BottomNavigationBarThemeData(
|
||||
selectedItemColor: AppColors.primary,
|
||||
unselectedItemColor: AppColors.textSecondary,
|
||||
type: BottomNavigationBarType.fixed,
|
||||
),
|
||||
inputDecorationTheme: InputDecorationTheme(
|
||||
border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
|
||||
contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||
),
|
||||
elevatedButtonTheme: ElevatedButtonThemeData(
|
||||
style: ElevatedButton.styleFrom(
|
||||
minimumSize: const Size(double.infinity, 48),
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
190
client/lib/features/auth/login_screen.dart
Normal file
190
client/lib/features/auth/login_screen.dart
Normal file
@@ -0,0 +1,190 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
import '../../core/auth/auth_provider.dart';
|
||||
import '../../core/theme/app_colors.dart';
|
||||
|
||||
class LoginScreen extends ConsumerStatefulWidget {
|
||||
const LoginScreen({super.key});
|
||||
|
||||
@override
|
||||
ConsumerState<LoginScreen> createState() => _LoginScreenState();
|
||||
}
|
||||
|
||||
class _LoginScreenState extends ConsumerState<LoginScreen> {
|
||||
final _formKey = GlobalKey<FormState>();
|
||||
final _emailController = TextEditingController();
|
||||
final _passwordController = TextEditingController();
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_emailController.dispose();
|
||||
_passwordController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final authState = ref.watch(authProvider);
|
||||
|
||||
ref.listen<AuthState>(authProvider, (previous, next) {
|
||||
if (next.status == AuthStatus.authenticated) {
|
||||
context.go('/home');
|
||||
}
|
||||
if (next.error != null) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(next.error!),
|
||||
backgroundColor: AppColors.error,
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
return Scaffold(
|
||||
body: SafeArea(
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Form(
|
||||
key: _formKey,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
const SizedBox(height: 60),
|
||||
Icon(
|
||||
Icons.restaurant_menu,
|
||||
size: 80,
|
||||
color: AppColors.primary,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'FoodAI',
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.headlineLarge?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
color: AppColors.primary,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'Управляйте питанием\nс помощью AI',
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.bodyLarge?.copyWith(
|
||||
color: AppColors.textSecondary,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 48),
|
||||
TextFormField(
|
||||
controller: _emailController,
|
||||
keyboardType: TextInputType.emailAddress,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Email',
|
||||
prefixIcon: Icon(Icons.email_outlined),
|
||||
),
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return 'Введите email';
|
||||
}
|
||||
if (!RegExp(r'^[^@]+@[^@]+\.[^@]+').hasMatch(value)) {
|
||||
return 'Некорректный email';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextFormField(
|
||||
controller: _passwordController,
|
||||
obscureText: true,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Пароль',
|
||||
prefixIcon: Icon(Icons.lock_outlined),
|
||||
),
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return 'Введите пароль';
|
||||
}
|
||||
if (value.length < 6) {
|
||||
return 'Минимум 6 символов';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
ElevatedButton(
|
||||
onPressed: authState.isLoading ? null : _signInWithEmail,
|
||||
child: authState.isLoading
|
||||
? const SizedBox(
|
||||
height: 20,
|
||||
width: 20,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: const Text('Войти'),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
Row(
|
||||
children: [
|
||||
const Expanded(child: Divider()),
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: Text(
|
||||
'или',
|
||||
style: TextStyle(color: AppColors.textSecondary),
|
||||
),
|
||||
),
|
||||
const Expanded(child: Divider()),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
OutlinedButton.icon(
|
||||
onPressed: authState.isLoading ? null : _signInWithGoogle,
|
||||
icon: const Text('G',
|
||||
style: TextStyle(
|
||||
fontSize: 18, fontWeight: FontWeight.bold)),
|
||||
label: const Text('Войти через Google'),
|
||||
style: OutlinedButton.styleFrom(
|
||||
minimumSize: const Size(double.infinity, 48),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12)),
|
||||
),
|
||||
),
|
||||
if (defaultTargetPlatform == TargetPlatform.iOS) ...[
|
||||
const SizedBox(height: 12),
|
||||
OutlinedButton.icon(
|
||||
onPressed: authState.isLoading ? null : () {},
|
||||
icon: const Icon(Icons.apple, size: 24),
|
||||
label: const Text('Войти через Apple'),
|
||||
style: OutlinedButton.styleFrom(
|
||||
minimumSize: const Size(double.infinity, 48),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12)),
|
||||
),
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 24),
|
||||
TextButton(
|
||||
onPressed: () => context.go('/auth/register'),
|
||||
child: const Text('Нет аккаунта? Регистрация'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _signInWithEmail() {
|
||||
if (_formKey.currentState!.validate()) {
|
||||
ref.read(authProvider.notifier).signInWithEmail(
|
||||
_emailController.text.trim(),
|
||||
_passwordController.text,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void _signInWithGoogle() {
|
||||
ref.read(authProvider.notifier).signInWithGoogle();
|
||||
}
|
||||
}
|
||||
158
client/lib/features/auth/register_screen.dart
Normal file
158
client/lib/features/auth/register_screen.dart
Normal file
@@ -0,0 +1,158 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
import '../../core/auth/auth_provider.dart';
|
||||
import '../../core/theme/app_colors.dart';
|
||||
|
||||
class RegisterScreen extends ConsumerStatefulWidget {
|
||||
const RegisterScreen({super.key});
|
||||
|
||||
@override
|
||||
ConsumerState<RegisterScreen> createState() => _RegisterScreenState();
|
||||
}
|
||||
|
||||
class _RegisterScreenState extends ConsumerState<RegisterScreen> {
|
||||
final _formKey = GlobalKey<FormState>();
|
||||
final _nameController = TextEditingController();
|
||||
final _emailController = TextEditingController();
|
||||
final _passwordController = TextEditingController();
|
||||
final _confirmPasswordController = TextEditingController();
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_nameController.dispose();
|
||||
_emailController.dispose();
|
||||
_passwordController.dispose();
|
||||
_confirmPasswordController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final authState = ref.watch(authProvider);
|
||||
|
||||
ref.listen<AuthState>(authProvider, (previous, next) {
|
||||
if (next.status == AuthStatus.authenticated) {
|
||||
context.go('/home');
|
||||
}
|
||||
if (next.error != null) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(next.error!),
|
||||
backgroundColor: AppColors.error,
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Регистрация')),
|
||||
body: SafeArea(
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Form(
|
||||
key: _formKey,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
const SizedBox(height: 24),
|
||||
TextFormField(
|
||||
controller: _nameController,
|
||||
textCapitalization: TextCapitalization.words,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Имя',
|
||||
prefixIcon: Icon(Icons.person_outlined),
|
||||
),
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return 'Введите имя';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextFormField(
|
||||
controller: _emailController,
|
||||
keyboardType: TextInputType.emailAddress,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Email',
|
||||
prefixIcon: Icon(Icons.email_outlined),
|
||||
),
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return 'Введите email';
|
||||
}
|
||||
if (!RegExp(r'^[^@]+@[^@]+\.[^@]+').hasMatch(value)) {
|
||||
return 'Некорректный email';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextFormField(
|
||||
controller: _passwordController,
|
||||
obscureText: true,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Пароль',
|
||||
prefixIcon: Icon(Icons.lock_outlined),
|
||||
),
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return 'Введите пароль';
|
||||
}
|
||||
if (value.length < 6) {
|
||||
return 'Минимум 6 символов';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextFormField(
|
||||
controller: _confirmPasswordController,
|
||||
obscureText: true,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Подтверждение пароля',
|
||||
prefixIcon: Icon(Icons.lock_outlined),
|
||||
),
|
||||
validator: (value) {
|
||||
if (value != _passwordController.text) {
|
||||
return 'Пароли не совпадают';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 32),
|
||||
ElevatedButton(
|
||||
onPressed: authState.isLoading ? null : _register,
|
||||
child: authState.isLoading
|
||||
? const SizedBox(
|
||||
height: 20,
|
||||
width: 20,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: const Text('Зарегистрироваться'),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextButton(
|
||||
onPressed: () => context.go('/auth/login'),
|
||||
child: const Text('Уже есть аккаунт? Войти'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _register() {
|
||||
if (_formKey.currentState!.validate()) {
|
||||
ref.read(authProvider.notifier).register(
|
||||
_emailController.text.trim(),
|
||||
_passwordController.text,
|
||||
_nameController.text.trim(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
13
client/lib/features/home/home_screen.dart
Normal file
13
client/lib/features/home/home_screen.dart
Normal file
@@ -0,0 +1,13 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class HomeScreen extends StatelessWidget {
|
||||
const HomeScreen({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Главная')),
|
||||
body: const Center(child: Text('Раздел в разработке')),
|
||||
);
|
||||
}
|
||||
}
|
||||
13
client/lib/features/menu/menu_screen.dart
Normal file
13
client/lib/features/menu/menu_screen.dart
Normal file
@@ -0,0 +1,13 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class MenuScreen extends StatelessWidget {
|
||||
const MenuScreen({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Меню')),
|
||||
body: const Center(child: Text('Раздел в разработке')),
|
||||
);
|
||||
}
|
||||
}
|
||||
13
client/lib/features/products/products_screen.dart
Normal file
13
client/lib/features/products/products_screen.dart
Normal file
@@ -0,0 +1,13 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class ProductsScreen extends StatelessWidget {
|
||||
const ProductsScreen({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Продукты')),
|
||||
body: const Center(child: Text('Раздел в разработке')),
|
||||
);
|
||||
}
|
||||
}
|
||||
13
client/lib/features/profile/profile_screen.dart
Normal file
13
client/lib/features/profile/profile_screen.dart
Normal file
@@ -0,0 +1,13 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class ProfileScreen extends StatelessWidget {
|
||||
const ProfileScreen({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Профиль')),
|
||||
body: const Center(child: Text('Раздел в разработке')),
|
||||
);
|
||||
}
|
||||
}
|
||||
13
client/lib/features/recipes/recipes_screen.dart
Normal file
13
client/lib/features/recipes/recipes_screen.dart
Normal file
@@ -0,0 +1,13 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class RecipesScreen extends StatelessWidget {
|
||||
const RecipesScreen({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Рецепты')),
|
||||
body: const Center(child: Text('Раздел в разработке')),
|
||||
);
|
||||
}
|
||||
}
|
||||
51
client/lib/firebase_options.dart
Normal file
51
client/lib/firebase_options.dart
Normal file
@@ -0,0 +1,51 @@
|
||||
import 'package:firebase_core/firebase_core.dart' show FirebaseOptions;
|
||||
import 'package:flutter/foundation.dart'
|
||||
show defaultTargetPlatform, kIsWeb, TargetPlatform;
|
||||
|
||||
class DefaultFirebaseOptions {
|
||||
static FirebaseOptions get currentPlatform {
|
||||
if (kIsWeb) {
|
||||
return web;
|
||||
}
|
||||
switch (defaultTargetPlatform) {
|
||||
case TargetPlatform.android:
|
||||
return android;
|
||||
case TargetPlatform.iOS:
|
||||
return ios;
|
||||
default:
|
||||
throw UnsupportedError(
|
||||
'DefaultFirebaseOptions are not supported for this platform.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Web config — from Firebase Console → Project Settings → Your apps → Web
|
||||
static const FirebaseOptions web = FirebaseOptions(
|
||||
apiKey: 'AIzaSyA9m_zlnQP3T9x0_AZGi5yYH-NQ9C1uPqc',
|
||||
authDomain: 'food-ai-efd52.firebaseapp.com',
|
||||
projectId: 'food-ai-efd52',
|
||||
storageBucket: 'food-ai-efd52.firebasestorage.app',
|
||||
messagingSenderId: '844967109320',
|
||||
appId: '1:844967109320:web:3a1c6307a6d14810fdbbfd',
|
||||
measurementId: 'G-PNKBVM3PDN',
|
||||
);
|
||||
|
||||
// TODO: заполнить после добавления Android-приложения в Firebase Console
|
||||
static const FirebaseOptions android = FirebaseOptions(
|
||||
apiKey: 'YOUR_ANDROID_API_KEY',
|
||||
appId: 'YOUR_ANDROID_APP_ID',
|
||||
messagingSenderId: '844967109320',
|
||||
projectId: 'food-ai-efd52',
|
||||
storageBucket: 'food-ai-efd52.firebasestorage.app',
|
||||
);
|
||||
|
||||
// TODO: заполнить после добавления iOS-приложения в Firebase Console
|
||||
static const FirebaseOptions ios = FirebaseOptions(
|
||||
apiKey: 'YOUR_IOS_API_KEY',
|
||||
appId: 'YOUR_IOS_APP_ID',
|
||||
messagingSenderId: '844967109320',
|
||||
projectId: 'food-ai-efd52',
|
||||
storageBucket: 'food-ai-efd52.firebasestorage.app',
|
||||
iosBundleId: 'com.foodai.foodAi',
|
||||
);
|
||||
}
|
||||
19
client/lib/main.dart
Normal file
19
client/lib/main.dart
Normal file
@@ -0,0 +1,19 @@
|
||||
import 'package:firebase_core/firebase_core.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import 'app.dart';
|
||||
import 'firebase_options.dart';
|
||||
|
||||
void main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
await Firebase.initializeApp(
|
||||
options: DefaultFirebaseOptions.currentPlatform,
|
||||
);
|
||||
|
||||
runApp(
|
||||
const ProviderScope(
|
||||
child: App(),
|
||||
),
|
||||
);
|
||||
}
|
||||
47
client/lib/shared/models/user.dart
Normal file
47
client/lib/shared/models/user.dart
Normal file
@@ -0,0 +1,47 @@
|
||||
import 'package:json_annotation/json_annotation.dart';
|
||||
|
||||
part 'user.g.dart';
|
||||
|
||||
@JsonSerializable()
|
||||
class User {
|
||||
final String id;
|
||||
final String email;
|
||||
final String name;
|
||||
@JsonKey(name: 'avatar_url')
|
||||
final String? avatarUrl;
|
||||
@JsonKey(name: 'height_cm')
|
||||
final int? heightCm;
|
||||
@JsonKey(name: 'weight_kg')
|
||||
final double? weightKg;
|
||||
final int? age;
|
||||
final String? gender;
|
||||
final String? activity;
|
||||
final String? goal;
|
||||
@JsonKey(name: 'daily_calories')
|
||||
final int? dailyCalories;
|
||||
final String plan;
|
||||
@JsonKey(defaultValue: {})
|
||||
final Map<String, dynamic> preferences;
|
||||
|
||||
const User({
|
||||
required this.id,
|
||||
required this.email,
|
||||
required this.name,
|
||||
this.avatarUrl,
|
||||
this.heightCm,
|
||||
this.weightKg,
|
||||
this.age,
|
||||
this.gender,
|
||||
this.activity,
|
||||
this.goal,
|
||||
this.dailyCalories,
|
||||
required this.plan,
|
||||
this.preferences = const {},
|
||||
});
|
||||
|
||||
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
|
||||
Map<String, dynamic> toJson() => _$UserToJson(this);
|
||||
|
||||
bool get hasCompletedOnboarding =>
|
||||
heightCm != null && weightKg != null && age != null && gender != null;
|
||||
}
|
||||
39
client/lib/shared/models/user.g.dart
Normal file
39
client/lib/shared/models/user.g.dart
Normal file
@@ -0,0 +1,39 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'user.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// JsonSerializableGenerator
|
||||
// **************************************************************************
|
||||
|
||||
User _$UserFromJson(Map<String, dynamic> json) => User(
|
||||
id: json['id'] as String,
|
||||
email: json['email'] as String,
|
||||
name: json['name'] as String,
|
||||
avatarUrl: json['avatar_url'] as String?,
|
||||
heightCm: (json['height_cm'] as num?)?.toInt(),
|
||||
weightKg: (json['weight_kg'] as num?)?.toDouble(),
|
||||
age: (json['age'] as num?)?.toInt(),
|
||||
gender: json['gender'] as String?,
|
||||
activity: json['activity'] as String?,
|
||||
goal: json['goal'] as String?,
|
||||
dailyCalories: (json['daily_calories'] as num?)?.toInt(),
|
||||
plan: json['plan'] as String,
|
||||
preferences: json['preferences'] as Map<String, dynamic>? ?? {},
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$UserToJson(User instance) => <String, dynamic>{
|
||||
'id': instance.id,
|
||||
'email': instance.email,
|
||||
'name': instance.name,
|
||||
'avatar_url': instance.avatarUrl,
|
||||
'height_cm': instance.heightCm,
|
||||
'weight_kg': instance.weightKg,
|
||||
'age': instance.age,
|
||||
'gender': instance.gender,
|
||||
'activity': instance.activity,
|
||||
'goal': instance.goal,
|
||||
'daily_calories': instance.dailyCalories,
|
||||
'plan': instance.plan,
|
||||
'preferences': instance.preferences,
|
||||
};
|
||||
Reference in New Issue
Block a user