-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate_codebase_feature_first.sh
More file actions
executable file
·3052 lines (2708 loc) · 87.8 KB
/
Copy pathcreate_codebase_feature_first.sh
File metadata and controls
executable file
·3052 lines (2708 loc) · 87.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/sh
set -e
echo "Starting create_codebase (feature-first) ..."
########################
# Directory layout (Feature-first)
#
# lib/
# core/ <- shared / cross-cutting code
# config/
# network/mockup/
# models/
# router/
# theme/
# widgets/
# features/ <- one folder per feature, each owns its own layers
# auth/{blocs,models,network,params,repositories,screens}
# home/screens
# product/{blocs,models,network,params,repositories,screens}
########################
# Assets (mockup JSON lives here; keep file so the folder is tracked and
# `flutter pub get` does not fail on the missing assets/mockup/ entry)
mkdir -p assets/mockup
touch assets/mockup/.gitkeep
# Core (shared) directories
mkdir -p lib/core/bloc
mkdir -p lib/core/config
mkdir -p lib/core/localization
mkdir -p lib/core/network/mockup
mkdir -p lib/core/models
mkdir -p lib/core/router
mkdir -p lib/core/theme
mkdir -p lib/core/widgets
# i18n: ARB translation sources live here, gen-l10n output goes to
# lib/core/localization/generated/
mkdir -p lib/l10n
# Auth feature
mkdir -p lib/features/auth/blocs
mkdir -p lib/features/auth/models
mkdir -p lib/features/auth/network
mkdir -p lib/features/auth/params
mkdir -p lib/features/auth/repositories
mkdir -p lib/features/auth/screens
# Home feature
mkdir -p lib/features/home/screens
# Product feature
mkdir -p lib/features/product/blocs
mkdir -p lib/features/product/models
mkdir -p lib/features/product/network
mkdir -p lib/features/product/params
mkdir -p lib/features/product/repositories
mkdir -p lib/features/product/screens
########################
# pubspec.yaml
########################
cat <<'EOF' > pubspec.yaml
name: codebase
description: A Flutter application with feature-first architecture
version: 1.0.0+1
environment:
sdk: ^3.10.0
flutter: ">=3.0.0"
dependencies:
auto_route: ^11.1.0
bloc: ^9.0.0
cupertino_icons: ^1.0.2
dart_mappable: ^4.3.0
dio: ^5.9.0
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
intl: ^0.20.2
flutter_bloc: ^9.1.1
flutter_screenutil: ^5.9.3
get_it: ^9.2.1
hive_ce: ^2.11.4
hive_ce_flutter: ^2.3.2
injectable: ^3.0.0
safe_json_annotation: ^0.2.0
path_to_regexp: ^0.4.0
retrofit: ^4.7.2
shared_preferences: ^2.5.3
talker_dio_logger: ^5.1.17
dev_dependencies:
analyzer: ^10.2.0
auto_route_generator: ^10.2.4
build_runner: ^2.7.1
flutter_flavorizr: ^2.5.0
dart_mappable_builder: ^4.3.0
flutter_lints: ^6.0.0
flutter_test:
sdk: flutter
hive_ce_generator: ^1.9.3
injectable_generator: ^3.0.2
retrofit_generator: ^10.0.4
safe_json_serializable: ^0.2.0
flutter:
uses-material-design: true
generate: true
assets:
- assets/mockup/
EOF
########################
# lib/main.dart
########################
cat <<'EOF' > lib/main.dart
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'core/config/app_config.dart';
import 'core/config/di_container.dart';
import 'app.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// Initialize app config for production
AppConfig.initialize(
environment: Environment.production,
apiBaseUrl: 'https://api.production.com',
appName: 'Flutter Feature App',
);
// Initialize dependency injection
await configureDependencies();
await ScreenUtil.ensureScreenSize();
runApp(const MyApp());
}
EOF
########################
# lib/main_dev.dart
########################
cat <<'EOF' > lib/main_dev.dart
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'core/config/app_config.dart';
import 'core/config/di_container.dart';
import 'app.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// Initialize app config for development
AppConfig.initialize(
environment: Environment.development,
apiBaseUrl: 'https://api.dev.com',
appName: 'Flutter Feature App Dev',
);
// Initialize dependency injection
await configureDependencies();
await ScreenUtil.ensureScreenSize();
runApp(const MyApp());
}
EOF
########################
# lib/main_staging.dart
########################
cat <<'EOF' > lib/main_staging.dart
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'core/config/app_config.dart';
import 'core/config/di_container.dart';
import 'app.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// Initialize app config for staging
AppConfig.initialize(
environment: Environment.staging,
apiBaseUrl: 'https://api.staging.com',
appName: 'Flutter Feature App Staging',
);
// Initialize dependency injection
await configureDependencies();
await ScreenUtil.ensureScreenSize();
runApp(const MyApp());
}
EOF
########################
# lib/main_prod.dart
########################
cat <<'EOF' > lib/main_prod.dart
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'core/config/app_config.dart';
import 'core/config/di_container.dart';
import 'app.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// Initialize app config for production
AppConfig.initialize(
environment: Environment.production,
apiBaseUrl: 'https://api.production.com',
appName: 'Flutter Feature App',
);
// Initialize dependency injection
await configureDependencies();
await ScreenUtil.ensureScreenSize();
runApp(const MyApp());
}
EOF
########################
# lib/app.dart
########################
cat <<'EOF' > lib/app.dart
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'core/bloc/app_multi_bloc_provider.dart';
import 'core/config/di_container.dart';
import 'core/config/app_config.dart';
import 'core/localization/generated/app_localizations.dart';
import 'core/localization/locale_cubit.dart';
import 'core/router/app_router.dart';
import 'core/theme/app_theme.dart';
import 'core/theme/theme_cubit.dart';
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(final BuildContext context) {
final appRouter = getIt<AppRouter>();
return ScreenUtilInit(
designSize: const Size(375, 812),
minTextAdapt: true,
builder: (final context, final child) {
return MultiBlocProvider(
providers: AppMultiBlocProvider.providers,
child: BlocBuilder<ThemeCubit, ThemeMode>(
builder: (final context, final themeMode) {
return BlocBuilder<LocaleCubit, Locale?>(
builder: (final context, final locale) {
return MaterialApp.router(
title: AppConfig.instance.appName,
theme: AppTheme.lightTheme,
darkTheme: AppTheme.darkTheme,
themeMode: themeMode,
locale: locale,
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: AppLocalizations.supportedLocales,
routerConfig: appRouter.config(),
debugShowCheckedModeBanner: false,
);
},
);
},
),
);
},
);
}
}
EOF
########################
# lib/core/bloc/app_multi_bloc_provider.dart
########################
cat <<'EOF' > lib/core/bloc/app_multi_bloc_provider.dart
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../features/auth/blocs/auth_cubit.dart';
import '../../features/product/blocs/product_cubit.dart';
import '../config/di_container.dart';
import '../localization/locale_cubit.dart';
import '../theme/theme_cubit.dart';
class AppMultiBlocProvider {
// NOTE: keep the explicit <Cubit> type argument on every BlocProvider.
// Without it, the providers list infers BlocProvider<dynamic> and the cubit
// is registered under `dynamic`, so context.read<XCubit>() fails with
// "Could not find the correct Provider<XCubit>".
static List<BlocProvider> get providers {
return [
BlocProvider<LocaleCubit>(create: (final _) => getIt<LocaleCubit>()),
BlocProvider<ThemeCubit>(create: (final _) => getIt<ThemeCubit>()),
BlocProvider<AuthCubit>(create: (final _) => getIt<AuthCubit>()),
BlocProvider<ProductCubit>(create: (final _) => getIt<ProductCubit>()),
];
}
}
EOF
########################
# lib/core/config/app_config.dart
########################
cat <<'EOF' > lib/core/config/app_config.dart
enum Environment { development, staging, production }
class AppConfig {
AppConfig._internal({
required this.environment,
required this.apiBaseUrl,
required this.appName,
});
static late AppConfig _instance;
static AppConfig get instance => _instance;
final Environment environment;
final String apiBaseUrl;
final String appName;
static void initialize({
required final Environment environment,
required final String apiBaseUrl,
required final String appName,
}) {
_instance = AppConfig._internal(
environment: environment,
apiBaseUrl: apiBaseUrl,
appName: appName,
);
}
bool get isDevelopment => environment == Environment.development;
bool get isStaging => environment == Environment.staging;
bool get isProduction => environment == Environment.production;
}
EOF
########################
# lib/core/config/di_container.dart
########################
cat <<'EOF' > lib/core/config/di_container.dart
import 'package:get_it/get_it.dart';
import 'package:injectable/injectable.dart';
import 'di_container.config.dart';
final getIt = GetIt.instance;
/// Wires up the whole dependency graph from annotations.
///
/// API services (@LazySingleton + @factoryMethod), repositories
/// (@LazySingleton) and cubits (@injectable) are discovered automatically by
/// injectable_generator, so you never edit this file when adding a feature.
/// Only infra that can't be annotated lives in [AppModule].
@InjectableInit()
Future<void> configureDependencies() async => getIt.init();
EOF
########################
# lib/core/config/app_module.dart
########################
cat <<'EOF' > lib/core/config/app_module.dart
import 'package:dio/dio.dart';
import 'package:injectable/injectable.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../network/dio_client.dart';
import '../router/app_router.dart';
import 'app_config.dart';
/// Registers third-party / infrastructure dependencies that can't carry an
/// injectable annotation on their own class.
@module
abstract class AppModule {
// Awaited during configureDependencies() and registered as a ready singleton.
@preResolve
Future<SharedPreferences> get prefs => SharedPreferences.getInstance();
@lazySingleton
DioClient dioClient() => DioClient(AppConfig.instance.apiBaseUrl);
@lazySingleton
Dio dio(final DioClient client) => client.dio;
@lazySingleton
AppRouter get router => AppRouter();
}
EOF
########################
# lib/core/localization/locale_cubit.dart
########################
cat <<'EOF' > lib/core/localization/locale_cubit.dart
import 'package:flutter/widgets.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:injectable/injectable.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'generated/app_localizations.dart';
/// Holds the currently selected [Locale] and persists the user's choice.
///
/// A `null` state means "follow the device locale" (the default on first run),
/// letting [MaterialApp] resolve the best match from [supportedLocales].
@lazySingleton
class LocaleCubit extends Cubit<Locale?> {
LocaleCubit(this._prefs) : super(_read(_prefs));
static const String _prefsKey = 'app_locale';
final SharedPreferences _prefs;
/// Locales the app ships translations for. Mirrors
/// `AppLocalizations.supportedLocales`, re-exported here for convenience.
static List<Locale> get supportedLocales =>
AppLocalizations.supportedLocales;
static Locale? _read(final SharedPreferences prefs) {
final code = prefs.getString(_prefsKey);
if (code == null || code.isEmpty) {
return null;
}
return Locale(code);
}
/// Switches the app to [locale] and remembers it across launches.
Future<void> setLocale(final Locale locale) async {
await _prefs.setString(_prefsKey, locale.languageCode);
emit(locale);
}
/// Clears the saved preference and falls back to the device locale.
Future<void> useSystemLocale() async {
await _prefs.remove(_prefsKey);
emit(null);
}
}
EOF
########################
# lib/core/localization/l10n_context_extension.dart
########################
cat <<'EOF' > lib/core/localization/l10n_context_extension.dart
import 'package:flutter/widgets.dart';
import 'generated/app_localizations.dart';
/// Shorthand for reading the active translations off [BuildContext].
///
/// `context.l10n.login` instead of `AppLocalizations.of(context).login`.
/// Goes through [AppLocalizations.of] (a [Localizations] lookup), so when
/// `LocaleCubit` changes the locale and `MaterialApp` rebuilds, widgets reading
/// `context.l10n` rebuild automatically — same reactivity, less typing.
extension L10nContextX on BuildContext {
AppLocalizations get l10n => AppLocalizations.of(this);
}
EOF
########################
# l10n.yaml (project root) — gen-l10n config
########################
cat <<'EOF' > l10n.yaml
arb-dir: lib/l10n
template-arb-file: app_en.arb
output-localization-file: app_localizations.dart
output-class: AppLocalizations
output-dir: lib/core/localization/generated
nullable-getter: false
EOF
########################
# lib/l10n/app_en.arb (template language)
########################
cat <<'EOF' > lib/l10n/app_en.arb
{
"@@locale": "en",
"appTitle": "Codebase",
"@appTitle": {
"description": "The application title shown to the user"
},
"languageName": "English",
"@languageName": {
"description": "Display name of this language in its own language"
},
"home": "Home",
"@home": {},
"login": "Login",
"@login": {},
"register": "Register",
"@register": {},
"logout": "Logout",
"@logout": {},
"email": "Email",
"@email": {},
"password": "Password",
"@password": {},
"pleaseEnterEmail": "Please enter your email",
"@pleaseEnterEmail": {},
"pleaseEnterPassword": "Please enter your password",
"@pleaseEnterPassword": {},
"noAccountRegister": "Do not have an account? Register",
"@noAccountRegister": {},
"language": "Language",
"@language": {},
"selectLanguage": "Select language",
"@selectLanguage": {},
"toggleTheme": "Toggle light/dark theme",
"@toggleTheme": {}
}
EOF
########################
# lib/l10n/app_vi.arb (Vietnamese)
########################
cat <<'EOF' > lib/l10n/app_vi.arb
{
"@@locale": "vi",
"appTitle": "Codebase",
"languageName": "Tiếng Việt",
"home": "Trang chủ",
"login": "Đăng nhập",
"register": "Đăng ký",
"logout": "Đăng xuất",
"email": "Email",
"password": "Mật khẩu",
"pleaseEnterEmail": "Vui lòng nhập email",
"pleaseEnterPassword": "Vui lòng nhập mật khẩu",
"noAccountRegister": "Chưa có tài khoản? Đăng ký",
"language": "Ngôn ngữ",
"selectLanguage": "Chọn ngôn ngữ",
"toggleTheme": "Đổi giao diện sáng/tối"
}
EOF
########################
# lib/core/network/dio_client.dart
########################
cat <<'EOF' > lib/core/network/dio_client.dart
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:talker_dio_logger/talker_dio_logger.dart';
import 'mockup/mockup_interceptor.dart';
class DioClient {
DioClient(final String baseUrl) {
_dio = Dio(
BaseOptions(
baseUrl: baseUrl,
connectTimeout: const Duration(seconds: 30),
receiveTimeout: const Duration(seconds: 30),
sendTimeout: const Duration(seconds: 30),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
),
);
if (kDebugMode) {
_dio.interceptors.add(
TalkerDioLogger(
settings: const TalkerDioLoggerSettings(
printRequestHeaders: true,
),
),
);
_dio.interceptors.add(MockUpInterceptor());
}
_dio.interceptors.add(
InterceptorsWrapper(
onRequest: (final options, final handler) {
// Add auth token if available
// final token = getAuthToken();
// if (token != null) {
// options.headers['Authorization'] = 'Bearer $token';
// }
handler.next(options);
},
onError: (final error, final handler) {
// Handle common errors
if (error.response?.statusCode == 401) {
// Handle unauthorized
}
handler.next(error);
},
),
);
}
late final Dio _dio;
Dio get dio => _dio;
}
EOF
########################
# lib/core/network/mockup/mockup_interceptor.dart
########################
cat <<'EOF' > lib/core/network/mockup/mockup_interceptor.dart
// Dart imports:
import 'dart:io';
// Package imports:
import 'package:dio/dio.dart';
// Project imports:
import 'mock_api.dart';
class MockUpInterceptor extends Interceptor {
@override
Future<void> onRequest(
final RequestOptions options,
final RequestInterceptorHandler handler,
) async {
if (options.method == 'GET' && options.headers['isMockUp'] == true) {
return handler.resolve(await mockGetResponse(options));
}
if (options.method == 'POST' && options.headers['isMockUp'] == true) {
return handler.resolve(await mockPostResponse(options));
}
if (options.method == 'PUT' && options.headers['isMockUp'] == true) {
return handler.resolve(await mockPostResponse(options));
}
return handler.next(options);
}
Future<Response<dynamic>> mockGetResponse(
final RequestOptions options,
) async {
return Response<dynamic>(
statusCode: HttpStatus.ok,
requestOptions: RequestOptions(path: options.path),
data: await MockApi.get(
options.path,
mockName: options.extra['mock'] as String?,
queryParameters: options.queryParameters,
),
);
}
Future<Response<dynamic>> mockPostResponse(
final RequestOptions options,
) async {
return Response<dynamic>(
statusCode: HttpStatus.ok,
requestOptions: RequestOptions(path: options.path),
data: await MockApi.post(
options.path,
mockName: options.extra['mock'] as String?,
queryParameters: options.queryParameters,
),
);
}
}
EOF
########################
# lib/core/network/mockup/mock_api.dart
########################
cat <<'EOF' > lib/core/network/mockup/mock_api.dart
// Dart imports:
import 'dart:convert';
// Flutter imports:
import 'package:flutter/services.dart';
// Project imports:
import 'map_mock_api.dart';
class MockApi {
// [mockName] comes from
// the api method's @Extra({'mock': '...'}) and wins over
// the path-based convention, so renaming an endpoint never breaks its mock.
static Future<Map<String, dynamic>?> get(
final String endpoint, {
final String? mockName,
final Map<String, dynamic>? queryParameters,
}) async {
return mock(
mockName ??
getJsonNameForGetRequest(endpoint, queryParameters: queryParameters),
);
}
static Future<Map<String, dynamic>?> post(
final String endpoint, {
final String? mockName,
final dynamic data,
final Map<String, dynamic>? queryParameters,
}) async {
return mock(
mockName ??
getJsonNameForPostRequest(
endpoint,
data: data,
queryParameters: queryParameters,
),
);
}
static Future<Map<String, dynamic>?> mock(final String? endpoint) async {
// the way how to load assets in packages
final String responseStr = await rootBundle.loadString(
'assets/mockup/$endpoint.json',
);
final Map<String, dynamic>? responseJson =
json.decode(responseStr) as Map<String, dynamic>?;
return responseJson;
}
}
EOF
########################
# lib/core/network/mockup/map_mock_api.dart
########################
cat <<'EOF' > lib/core/network/mockup/map_mock_api.dart
import 'package:path_to_regexp/path_to_regexp.dart';
// Mock JSON files are resolved from the request path BY CONVENTION:
// '/order' -> assets/mockup/order.json
// '/order/cancel' -> assets/mockup/order_cancel.json
// '/auth/login' -> assets/mockup/auth_login.json
// So a new feature only needs to drop its own json file in assets/mockup/ —
// there is nothing central to register here.
//
// These maps are OPTIONAL overrides, only for endpoints whose file name can't
// be derived from the path (e.g. routes with path params like '/products/{id}'
// that should all map to a single 'products.json'). Leave them empty otherwise.
final Map<String, String> mapMockApiForGetRequest = <String, String>{};
final Map<String, String> mapMockApiForPostRequest = <String, String>{};
String? getJsonNameForGetRequest(
final String endpoint, {
final Map<String, dynamic>? queryParameters,
}) =>
_resolveJsonName(endpoint, mapMockApiForGetRequest);
String? getJsonNameForPostRequest(
final String endpoint, {
final dynamic data,
final Map<String, dynamic>? queryParameters,
}) =>
_resolveJsonName(endpoint, mapMockApiForPostRequest);
String _resolveJsonName(
final String endpoint,
final Map<String, String> overrides,
) {
for (final String key in overrides.keys) {
if (hasMatch(endpoint, key)) {
return overrides[key]!;
}
}
// Convention: drop query + leading slash, turn '/' and '-' into '_'.
return endpoint
.split('?')
.first
.replaceAll(RegExp('^/+'), '')
.replaceAll('/', '_')
.replaceAll('-', '_');
}
bool hasMatch(final String path, final String endPoints) {
final String endPoint = endPoints.replaceAll('{', ':').replaceAll('}', '');
final RegExp regExp = pathToRegExp(endPoint);
return regExp.hasMatch(path);
}
EOF
########################
# lib/core/models/api_response.dart
########################
cat <<'EOF' > lib/core/models/api_response.dart
import 'package:safe_json_annotation/safe_json_annotation.dart';
part 'api_response.g.dart';
@JsonSerializable(genericArgumentFactories: true)
class ApiResponse<T> {
const ApiResponse({
this.success,
this.status,
this.code,
this.message,
this.data,
this.errors,
});
factory ApiResponse.fromJson(
final Map<String, dynamic> json,
final T Function(Object? json) fromJsonT,
) =>
_$ApiResponseFromJson(json, fromJsonT);
final bool? success;
final int? status;
final int? code;
final String? message;
final T? data;
final Map<String, dynamic>? errors;
Map<String, dynamic> toJson(final Object Function(T value) toJsonT) =>
_$ApiResponseToJson(this, toJsonT);
}
EOF
########################
# lib/core/router/app_router.dart
########################
cat <<'EOF' > lib/core/router/app_router.dart
import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import '../../features/auth/screens/login_screen.dart';
import '../../features/auth/screens/register_screen.dart';
import '../../features/home/screens/home_screen.dart';
import '../../features/product/screens/product_list_screen.dart';
import '../../features/product/screens/product_detail_screen.dart';
part 'app_router.gr.dart';
@AutoRouterConfig()
class AppRouter extends RootStackRouter {
@override
RouteType get defaultRouteType => const RouteType.adaptive();
@override
List<AutoRoute> get routes => [
// Auth routes
AutoRoute(
page: LoginRoute.page,
path: LoginScreen.path,
initial: true,
),
AutoRoute(
page: RegisterRoute.page,
path: RegisterScreen.path,
),
// Main routes
AutoRoute(
page: HomeRoute.page,
path: HomeScreen.path,
),
AutoRoute(
page: ProductListRoute.page,
path: ProductListScreen.path,
),
AutoRoute(
page: ProductDetailRoute.page,
path: ProductDetailScreen.path,
),
];
}
EOF
########################
# lib/features/auth/network/auth_service.dart
########################
cat <<'EOF' > lib/features/auth/network/auth_service.dart
import 'package:dio/dio.dart';
import 'package:injectable/injectable.dart';
import 'package:retrofit/retrofit.dart';
import '../models/user_model.dart';
import '../../../core/models/api_response.dart';
import '../params/login_params.dart';
import '../params/register_params.dart';
part 'auth_service.g.dart';
@LazySingleton()
@RestApi()
abstract class AuthService {
// No baseUrl param: injectable only injects Dio. Retrofit still generates its
// own baseUrl-aware constructor in _AuthService, so nothing is lost.
@factoryMethod
factory AuthService(final Dio dio) = _AuthService;
// @Extra binds the mock file name to the method (assets/mockup/login.json),
// independent of the path — change the path and the mock still resolves.
@POST('/auth/login')
@Extra({'mock': 'login'})
Future<ApiResponse<UserModelData>> login(
@Body() final LoginParams params, {
@Header('isMockUp') final bool? isMockUp,
});
@POST('/auth/register')
@Extra({'mock': 'register'})
Future<ApiResponse<UserModelData>> register(
@Body() final RegisterParams params, {
@Header('isMockUp') final bool? isMockUp,
});
@POST('/auth/logout')
@Extra({'mock': 'logout'})
Future<ApiResponse<UserModelData>> logout({
@Header('isMockUp') final bool? isMockUp,
});
@GET('/auth/profile')
@Extra({'mock': 'profile'})
Future<ApiResponse<UserModelData>> getProfile({
@Header('isMockUp') final bool? isMockUp,
});
}
EOF
########################
# lib/features/auth/params/login_params.dart
########################
cat <<'EOF' > lib/features/auth/params/login_params.dart
import 'package:dart_mappable/dart_mappable.dart';
part 'login_params.mapper.dart';
@MappableClass()
class LoginParams with LoginParamsMappable {
const LoginParams({
required this.email,
required this.password,
});
final String email;
final String password;
}
EOF
########################
# lib/features/auth/params/register_params.dart
########################
cat <<'EOF' > lib/features/auth/params/register_params.dart
import 'package:dart_mappable/dart_mappable.dart';
part 'register_params.mapper.dart';
@MappableClass()
class RegisterParams with RegisterParamsMappable {
const RegisterParams({
required this.email,
required this.password,
required this.name,
});
final String email;
final String password;
final String name;
}
EOF
########################
# lib/features/auth/models/user_model.dart
########################
cat <<'EOF' > lib/features/auth/models/user_model.dart
import 'package:safe_json_annotation/safe_json_annotation.dart';
part 'user_model.g.dart';
@JsonSerializable()
class UserModel {
UserModel({
this.success,
this.code,
this.message,
this.data,
});
factory UserModel.fromJson(final Map<String, dynamic> json) =>
_$UserModelFromJson(json);
@JsonKey(name: 'success')