im so tired man

This commit is contained in:
Wowieee4
2026-05-28 11:27:06 +07:00
parent 66da2473e1
commit 6272ece15d
86 changed files with 1759 additions and 4090 deletions
@@ -2,6 +2,9 @@
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.VIBRATE" />
@@ -13,7 +16,8 @@
<application
android:label="WalkGuide"
android:name="${applicationName}"
android:icon="@mipmap/ic_launcher">
android:icon="@mipmap/ic_launcher"
android:usesCleartextTraffic="true">
<activity
android:name=".MainActivity"
android:exported="true"
@@ -34,6 +38,9 @@
<meta-data
android:name="flutterEmbedding"
android:value="2" />
<meta-data
android:name="io.flutter.embedding.android.EnableImpeller"
android:value="false" />
</application>
<queries>
@@ -0,0 +1,36 @@
<svg width="512" height="512" viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg">
<defs>
<linearGradient id="bg-grad" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="#0B132B"/>
<stop offset="100%" stop-color="#1C2541"/>
</linearGradient>
<linearGradient id="cyan-glow" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="#48CAE4"/>
<stop offset="100%" stop-color="#0077B6"/>
</linearGradient>
<linearGradient id="amber-glow" x1="0%" y1="100%" x2="100%" y2="0%">
<stop offset="0%" stop-color="#FFB703"/>
<stop offset="100%" stop-color="#FB8500"/>
</linearGradient>
<filter id="shadow" x="-20%" y="-20%" width="140%" height="140%">
<feDropShadow dx="0" dy="12" stdDeviation="16" flood-color="#000000" flood-opacity="0.45"/>
</filter>
</defs>
<rect width="512" height="512" rx="115" fill="url(#bg-grad)"/>
<circle cx="256" cy="256" r="180" fill="none" stroke="#48CAE4" stroke-width="2" opacity="0.15" stroke-dasharray="10 14"/>
<circle cx="256" cy="256" r="110" fill="none" stroke="#48CAE4" stroke-width="3" opacity="0.3"/>
<path d="M 130 180 C 130 320, 180 370, 220 370 C 260 370, 256 270, 256 270"
fill="none"
stroke="url(#cyan-glow)"
stroke-width="52"
stroke-linecap="round"
filter="url(#shadow)"/>
<path d="M 382 180 C 382 320, 332 370, 292 370 C 252 370, 256 270, 256 270"
fill="none"
stroke="url(#amber-glow)"
stroke-width="52"
stroke-linecap="round"
filter="url(#shadow)"/>
<circle cx="256" cy="210" r="36" fill="#FFFFFF" filter="url(#shadow)"/>
<circle cx="256" cy="210" r="14" fill="#0B132B"/>
</svg>

After

Width:  |  Height:  |  Size: 1.7 KiB

+133 -106
View File
@@ -1,9 +1,11 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:google_fonts/google_fonts.dart';
import 'app_cubit.dart';
import 'router.dart';
import '../core/i18n/app_strings.dart';
import '../core/theme/app_colors.dart';
class WalkGuideApp extends StatelessWidget {
@@ -15,126 +17,151 @@ class WalkGuideApp extends StatelessWidget {
return BlocProvider(
create: (_) => AppCubit(),
child: MaterialApp.router(
title: 'WalkGuide',
debugShowCheckedModeBanner: false,
routerConfig: appRouter,
theme: ThemeData(
useMaterial3: true,
colorScheme: ColorScheme.fromSeed(
seedColor: seed,
brightness: Brightness.light,
primary: seed,
secondary: AppColors.accent,
error: AppColors.danger,
),
scaffoldBackgroundColor: AppColors.surface,
textTheme: GoogleFonts.interTextTheme().apply(
bodyColor: AppColors.text,
displayColor: AppColors.text,
),
pageTransitionsTheme: const PageTransitionsTheme(
builders: {
TargetPlatform.android: ZoomPageTransitionsBuilder(),
TargetPlatform.iOS: CupertinoPageTransitionsBuilder(),
TargetPlatform.windows: FadeUpwardsPageTransitionsBuilder(),
},
),
appBarTheme: const AppBarTheme(
centerTitle: false,
backgroundColor: AppColors.surface,
foregroundColor: AppColors.text,
elevation: 0,
surfaceTintColor: Colors.transparent,
),
cardTheme: CardThemeData(
elevation: 0,
color: AppColors.surfaceRaised,
surfaceTintColor: Colors.transparent,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
side: const BorderSide(color: AppColors.border),
child: BlocBuilder<AppCubit, AppState>(
builder: (context, state) => MaterialApp.router(
title: 'WalkGuide',
debugShowCheckedModeBanner: false,
routerConfig: appRouter,
builder: (context, child) {
final media = MediaQuery.of(context);
return MediaQuery(
data: media.copyWith(
textScaler: media.textScaler.clamp(
minScaleFactor: 0.9,
maxScaleFactor: 1.15,
),
),
child: child ?? const SizedBox.shrink(),
);
},
locale: state.localeCode == 'en-US'
? const Locale('en', 'US')
: const Locale('id', 'ID'),
supportedLocales: AppStrings.supportedLocales,
localizationsDelegates: const [
AppStringsDelegate(),
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
theme: ThemeData(
useMaterial3: true,
visualDensity: VisualDensity.adaptivePlatformDensity,
colorScheme: ColorScheme.fromSeed(
seedColor: seed,
brightness: Brightness.light,
primary: seed,
secondary: AppColors.accent,
error: AppColors.danger,
),
),
dividerTheme: const DividerThemeData(
color: AppColors.border,
thickness: 1,
space: 1,
),
iconButtonTheme: IconButtonThemeData(
style: IconButton.styleFrom(
scaffoldBackgroundColor: AppColors.surface,
textTheme: GoogleFonts.interTextTheme().apply(
bodyColor: AppColors.text,
displayColor: AppColors.text,
),
pageTransitionsTheme: const PageTransitionsTheme(
builders: {
TargetPlatform.android: ZoomPageTransitionsBuilder(),
TargetPlatform.iOS: CupertinoPageTransitionsBuilder(),
TargetPlatform.windows: FadeUpwardsPageTransitionsBuilder(),
},
),
appBarTheme: const AppBarTheme(
centerTitle: false,
backgroundColor: AppColors.surface,
foregroundColor: AppColors.text,
backgroundColor: Colors.white,
elevation: 0,
surfaceTintColor: Colors.transparent,
),
cardTheme: CardThemeData(
elevation: 0,
color: AppColors.surfaceRaised,
surfaceTintColor: Colors.transparent,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
side: const BorderSide(color: AppColors.border),
),
),
),
navigationBarTheme: NavigationBarThemeData(
elevation: 0,
height: 76,
backgroundColor: Colors.white,
indicatorColor: const Color(0xFFDDEAFE),
surfaceTintColor: Colors.transparent,
labelTextStyle: WidgetStateProperty.resolveWith(
(states) => TextStyle(
fontSize: 12,
fontWeight: states.contains(WidgetState.selected)
? FontWeight.w800
: FontWeight.w500,
dividerTheme: const DividerThemeData(
color: AppColors.border,
thickness: 1,
space: 1,
),
iconButtonTheme: IconButtonThemeData(
style: IconButton.styleFrom(
foregroundColor: AppColors.text,
backgroundColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
side: const BorderSide(color: AppColors.border),
),
),
),
),
filledButtonTheme: FilledButtonThemeData(
style: FilledButton.styleFrom(
backgroundColor: seed,
foregroundColor: Colors.white,
minimumSize: const Size(0, 50),
textStyle: const TextStyle(fontWeight: FontWeight.w800),
navigationBarTheme: NavigationBarThemeData(
elevation: 0,
height: 76,
backgroundColor: Colors.white,
indicatorColor: const Color(0xFFDDEAFE),
surfaceTintColor: Colors.transparent,
labelTextStyle: WidgetStateProperty.resolveWith(
(states) => TextStyle(
fontSize: 12,
fontWeight: states.contains(WidgetState.selected)
? FontWeight.w800
: FontWeight.w500,
),
),
),
filledButtonTheme: FilledButtonThemeData(
style: FilledButton.styleFrom(
backgroundColor: seed,
foregroundColor: Colors.white,
minimumSize: const Size(0, 50),
textStyle: const TextStyle(fontWeight: FontWeight.w800),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
),
),
outlinedButtonTheme: OutlinedButtonThemeData(
style: OutlinedButton.styleFrom(
minimumSize: const Size(0, 50),
foregroundColor: seed,
textStyle: const TextStyle(fontWeight: FontWeight.w800),
side: const BorderSide(color: AppColors.border),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
),
),
snackBarTheme: SnackBarThemeData(
behavior: SnackBarBehavior.floating,
backgroundColor: AppColors.text,
contentTextStyle: GoogleFonts.inter(
color: Colors.white,
fontWeight: FontWeight.w600,
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
borderRadius: BorderRadius.circular(8),
),
),
),
outlinedButtonTheme: OutlinedButtonThemeData(
style: OutlinedButton.styleFrom(
minimumSize: const Size(0, 50),
foregroundColor: seed,
textStyle: const TextStyle(fontWeight: FontWeight.w800),
side: const BorderSide(color: AppColors.border),
shape: RoundedRectangleBorder(
inputDecorationTheme: InputDecorationTheme(
filled: true,
fillColor: Colors.white,
contentPadding:
const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: const BorderSide(color: AppColors.border),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: const BorderSide(color: AppColors.border),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: const BorderSide(color: seed, width: 1.5),
),
),
),
snackBarTheme: SnackBarThemeData(
behavior: SnackBarBehavior.floating,
backgroundColor: AppColors.text,
contentTextStyle: GoogleFonts.inter(
color: Colors.white,
fontWeight: FontWeight.w600,
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
),
inputDecorationTheme: InputDecorationTheme(
filled: true,
fillColor: Colors.white,
contentPadding:
const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: const BorderSide(color: AppColors.border),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: const BorderSide(color: AppColors.border),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: const BorderSide(color: seed, width: 1.5),
),
),
),
@@ -4,14 +4,26 @@ class AppState {
final bool online;
final String? role;
final String? serverUrl;
final String localeCode;
const AppState({required this.online, this.role, this.serverUrl});
const AppState({
required this.online,
this.role,
this.serverUrl,
this.localeCode = 'id-ID',
});
AppState copyWith({bool? online, String? role, String? serverUrl}) {
AppState copyWith({
bool? online,
String? role,
String? serverUrl,
String? localeCode,
}) {
return AppState(
online: online ?? this.online,
role: role ?? this.role,
serverUrl: serverUrl ?? this.serverUrl,
localeCode: localeCode ?? this.localeCode,
);
}
}
@@ -25,5 +37,7 @@ class AppCubit extends Cubit<AppState> {
void setOnline(bool value) => emit(state.copyWith(online: value));
void setLocaleCode(String value) => emit(state.copyWith(localeCode: value));
void clearSession() => emit(const AppState(online: true));
}
@@ -1,6 +1,4 @@
import 'package:get_it/get_it.dart';
import 'package:flutter/foundation.dart';
import '../core/constants/app_constants.dart';
import '../core/ai/obstacle_alert_strategy.dart';
import '../core/ai/obstacle_analyzer.dart';
@@ -85,12 +83,5 @@ Future<void> initDependencies() async {
}
await ignoreInitFailure(() => sl<TtsService>().init(), label: 'TTS init');
await sl<YoloDetector>().init();
if (!kIsWeb) {
await ignoreInitFailure(() => sl<SttService>().init(), label: 'STT init');
}
sl<VoiceCommandHandler>().loadDefaultCommands();
if (!kIsWeb) {
await sl<FcmService>().init();
}
}
@@ -22,6 +22,9 @@ class AppConstants {
if (!cleaned.startsWith('http://') && !cleaned.startsWith('https://')) {
cleaned = 'http://$cleaned';
}
cleaned = cleaned
.replaceFirst('://localhost', '://127.0.0.1')
.replaceFirst('://0.0.0.0', '://127.0.0.1');
while (cleaned.endsWith('/')) {
cleaned = cleaned.substring(0, cleaned.length - 1);
}
@@ -61,7 +64,6 @@ class AppConstants {
await prefs.setString(_selectedYoloModelKey, path);
}
// Agora App ID tetap bisa dioverride saat build: --dart-define=AGORA_APP_ID=...
static const String agoraAppId = String.fromEnvironment('AGORA_APP_ID',
defaultValue: 'e36c2b6592e34cfda1f6ea6432a5e68d');
// Set at build time with: --dart-define=AGORA_APP_ID=your_app_id
static const String agoraAppId = String.fromEnvironment('AGORA_APP_ID');
}
@@ -75,6 +75,8 @@ bool _looksTechnical(String message) {
'duplicate key',
'constraint',
'sql [',
'illegal base64',
'base64 character',
];
return blocked.any(lower.contains);
}
@@ -1,9 +1,19 @@
import 'package:flutter/widgets.dart';
class AppStrings {
final String localeCode;
const AppStrings(this.localeCode);
static const supportedLocales = ['id-ID', 'en-US'];
static const supportedLocales = [
Locale('id', 'ID'),
Locale('en', 'US'),
];
static AppStrings of(BuildContext context) {
return Localizations.of<AppStrings>(context, AppStrings) ??
const AppStrings('id-ID');
}
String get walkGuideStarted => _pick(
id: 'WalkGuide dimulai',
@@ -29,3 +39,21 @@ class AppStrings {
return localeCode == 'en-US' ? en : id;
}
}
class AppStringsDelegate extends LocalizationsDelegate<AppStrings> {
const AppStringsDelegate();
@override
bool isSupported(Locale locale) {
return locale.languageCode == 'id' || locale.languageCode == 'en';
}
@override
Future<AppStrings> load(Locale locale) async {
final code = locale.languageCode == 'en' ? 'en-US' : 'id-ID';
return AppStrings(code);
}
@override
bool shouldReload(covariant LocalizationsDelegate<AppStrings> old) => false;
}
@@ -1,4 +1,5 @@
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import '../constants/app_constants.dart';
import '../storage/secure_storage.dart';
@@ -24,8 +25,15 @@ class ApiClient {
_dio.interceptors.addAll([
_AuthInterceptor(_secureStorage, _dio),
_ErrorInterceptor(),
LogInterceptor(requestBody: true, responseBody: true),
]);
if (kDebugMode) {
_dio.interceptors.add(LogInterceptor(
requestBody: false,
responseBody: false,
requestHeader: false,
responseHeader: false,
));
}
}
Dio get dio => _dio;
@@ -42,7 +50,8 @@ class _AuthInterceptor extends Interceptor {
_AuthInterceptor(this._storage, this._dio);
@override
void onRequest(RequestOptions options, RequestInterceptorHandler handler) async {
void onRequest(
RequestOptions options, RequestInterceptorHandler handler) async {
final token = await _storage.getAccessToken();
if (token != null) {
options.headers['Authorization'] = 'Bearer $token';
@@ -166,6 +166,11 @@ class CallService {
debugPrint('Agora remote user offline: $remoteUid $reason');
_onRemoteUserOffline?.call();
},
onRemoteAudioStateChanged: (_, remoteUid, state, reason, __) {
debugPrint(
'Agora remote audio state: uid=$remoteUid state=$state reason=$reason',
);
},
onError: (type, msg) {
debugPrint('Agora error: $type $msg');
if (!joinCompleter.isCompleted) joinCompleter.complete(false);
@@ -175,9 +180,18 @@ class CallService {
await _engine!.setChannelProfile(
ChannelProfileType.channelProfileCommunication,
);
await _engine!.setClientRole(role: ClientRoleType.clientRoleBroadcaster);
await _engine!.setAudioProfile(
profile: AudioProfileType.audioProfileDefault,
scenario: AudioScenarioType.audioScenarioMeeting,
);
await _engine!.enableAudio();
await _engine!.enableLocalAudio(true);
await _engine!.muteAllRemoteAudioStreams(false);
await _engine!.muteLocalAudioStream(false);
await _engine!.adjustRecordingSignalVolume(100);
await _engine!.adjustPlaybackSignalVolume(100);
await _engine!.setDefaultAudioRouteToSpeakerphone(true);
await _engine!.setEnableSpeakerphone(true);
await _engine!.joinChannel(
token: token ?? '',
@@ -9,7 +9,6 @@ import '../network/api_client.dart';
class FcmService {
final ApiClient _apiClient;
final FirebaseMessaging _messaging = FirebaseMessaging.instance;
final FlutterLocalNotificationsPlugin _localNotifications =
FlutterLocalNotificationsPlugin();
@@ -18,6 +17,7 @@ class FcmService {
Future<void> init() async {
if (kIsWeb) return;
try {
final messaging = FirebaseMessaging.instance;
await _localNotifications.initialize(
const InitializationSettings(
android: AndroidInitializationSettings('@mipmap/ic_launcher'),
@@ -31,10 +31,10 @@ class FcmService {
} catch (_) {}
},
);
await _messaging.requestPermission(alert: true, badge: true, sound: true);
final token = await _messaging.getToken();
await messaging.requestPermission(alert: true, badge: true, sound: true);
final token = await messaging.getToken();
if (token != null) await syncToken(token);
FirebaseMessaging.instance.onTokenRefresh.listen(syncToken);
messaging.onTokenRefresh.listen(syncToken);
FirebaseMessaging.onMessage.listen((message) {
debugPrint('FCM foreground: ${message.data}');
_showLocalNotification(message);
@@ -55,6 +55,10 @@ class FcmService {
Future<void> syncToken(String token) async {
try {
if (_apiClient.baseUrl == null) {
debugPrint('FCM token sync skipped: server URL is not ready.');
return;
}
await _apiClient.dio.put('/auth/fcm-token', data: {'fcmToken': token});
} catch (e) {
debugPrint('FCM token sync skipped: $e');
@@ -1,5 +1,6 @@
import 'dart:async';
import 'package:battery_plus/battery_plus.dart';
import 'package:dio/dio.dart';
import 'package:geolocator/geolocator.dart';
@@ -10,6 +11,7 @@ import 'offline_queue_service.dart';
class LocationReporterService {
final ApiClient _apiClient;
final OfflineQueueService _offlineQueue;
final Battery _battery = Battery();
Timer? _timer;
LocationReporterService(this._apiClient, this._offlineQueue);
@@ -32,12 +34,14 @@ class LocationReporterService {
try {
await Geolocator.requestPermission();
final position = await Geolocator.getCurrentPosition();
final batteryLevel = await _readBatteryLevel();
await _apiClient.dio.post('/user/location', data: {
'lat': position.latitude,
'lng': position.longitude,
'accuracy': position.accuracy,
'speed': position.speed,
'heading': position.heading,
if (batteryLevel != null) 'batteryLevel': batteryLevel,
});
} on DioException catch (_) {
await _offlineQueue.enqueue(OfflineRequest(
@@ -50,4 +54,12 @@ class LocationReporterService {
// GPS permission can be unavailable during desktop/web testing.
}
}
Future<int?> _readBatteryLevel() async {
try {
return await _battery.batteryLevel;
} catch (_) {
return null;
}
}
}
@@ -19,6 +19,8 @@ class VoiceCommand {
/// Callback yang dipanggil saat command terdeteksi
/// Registered oleh router/screen yang relevan
typedef CommandCallback = void Function(VoiceCommandKey key);
typedef CommandRouter = void Function(String route);
typedef CommandAction = void Function();
class VoiceCommandHandler {
final SttService _stt;
@@ -26,9 +28,19 @@ class VoiceCommandHandler {
List<VoiceCommand> _commands = [];
CommandCallback? onCommand;
CommandRouter? _router;
final Map<VoiceCommandKey, CommandAction> _actions = {};
VoiceCommandHandler(this._stt, this._tts);
void registerRouter(CommandRouter router) {
_router = router;
}
void registerAction(VoiceCommandKey key, CommandAction action) {
_actions[key] = action;
}
void loadCommands(List<VoiceCommand> commands) {
_commands = commands;
_stt.onResult = _processText;
@@ -66,9 +78,28 @@ class VoiceCommandHandler {
}
void _handleCommand(VoiceCommandKey key) {
_routeFor(key);
_actions[key]?.call();
onCommand?.call(key);
// Built-in actions for TTS-only commands
if (key == VoiceCommandKey.repeatLast) _tts.repeatLast();
if (key == VoiceCommandKey.stopTts) _tts.stop();
}
void _routeFor(VoiceCommandKey key) {
final route = switch (key) {
VoiceCommandKey.openWalkguide || VoiceCommandKey.startWalkguide =>
'/user/walkguide',
VoiceCommandKey.openNotification => '/user/notifications',
VoiceCommandKey.openSos || VoiceCommandKey.sendSos => '/user/sos',
VoiceCommandKey.openActivity => '/user/activity',
VoiceCommandKey.openNavigation => '/user/navigation',
VoiceCommandKey.openSettings => '/user/settings',
VoiceCommandKey.callGuardian => '/call',
_ => null,
};
if (route != null) {
_router?.call(route);
}
}
}
@@ -0,0 +1,3 @@
Activity log application layer.
This layer is reserved for Cubit/BLoC orchestration between the activity log UI and domain contracts.
@@ -0,0 +1,3 @@
Activity log data layer.
This layer is reserved for remote/local data sources and repository implementations.
@@ -0,0 +1,3 @@
Activity log domain layer.
This layer is reserved for entities, repository contracts, and use cases.
@@ -0,0 +1,3 @@
AI benchmark application layer.
This layer is reserved for benchmark Cubit/BLoC orchestration.
@@ -0,0 +1,3 @@
AI benchmark data layer.
This layer is reserved for benchmark result persistence and export adapters.
@@ -0,0 +1,3 @@
AI benchmark domain layer.
This layer is reserved for benchmark entities and use cases.
@@ -0,0 +1,3 @@
Auth application layer.
This layer is reserved for auth Cubit/BLoC orchestration between auth UI and auth domain contracts.
@@ -151,163 +151,182 @@ class _AuthFrame extends StatelessWidget {
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xFFEAF4FF),
body: Stack(
children: [
const Positioned.fill(
child: DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [Color(0xFFD9EEFF), Color(0xFFF7FAFC)],
),
),
),
),
Positioned(
top: -90,
right: -60,
child: TweenAnimationBuilder<double>(
tween: Tween(begin: 0.85, end: 1),
duration: const Duration(milliseconds: 900),
curve: Curves.easeOutCubic,
builder: (_, value, child) => Transform.scale(
scale: value,
child: child,
),
child: Container(
width: 260,
height: 260,
decoration: BoxDecoration(
color: const Color(0xFF2563EB).withValues(alpha: 0.14),
shape: BoxShape.circle,
),
),
),
),
Center(
child: SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 430),
child: TweenAnimationBuilder<double>(
tween: Tween(begin: 18, end: 0),
duration: const Duration(milliseconds: 520),
curve: Curves.easeOutCubic,
builder: (_, offset, child) => Opacity(
opacity: (1 - offset / 18).clamp(0.0, 1.0),
child: Transform.translate(
offset: Offset(0, offset),
child: child,
body: LayoutBuilder(
builder: (context, constraints) {
final compact =
constraints.maxWidth < 480 || constraints.maxHeight < 720;
return Stack(
children: [
const Positioned.fill(
child: DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [Color(0xFFD9EEFF), Color(0xFFF7FAFC)],
),
),
child: RepaintBoundary(
child: Container(
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.96),
borderRadius: BorderRadius.circular(30),
border: Border.all(
color: Colors.white.withValues(alpha: 0.8)),
boxShadow: [
BoxShadow(
color:
const Color(0xFF1E3A8A).withValues(alpha: 0.14),
blurRadius: 40,
offset: const Offset(0, 20),
),
],
),
),
Positioned(
top: compact ? -70 : -90,
right: compact ? -70 : -60,
child: Container(
width: compact ? 180 : 260,
height: compact ? 180 : 260,
decoration: BoxDecoration(
color: const Color(0xFF2563EB).withValues(alpha: 0.12),
shape: BoxShape.circle,
),
),
),
Center(
child: SingleChildScrollView(
keyboardDismissBehavior:
ScrollViewKeyboardDismissBehavior.onDrag,
padding: EdgeInsets.fromLTRB(
compact ? 14 : 24,
compact ? 12 : 24,
compact ? 14 : 24,
20 + MediaQuery.of(context).viewInsets.bottom,
),
child: ConstrainedBox(
constraints: BoxConstraints(maxWidth: compact ? 380 : 430),
child: TweenAnimationBuilder<double>(
tween: Tween(begin: 18, end: 0),
duration: const Duration(milliseconds: 520),
curve: Curves.easeOutCubic,
builder: (_, offset, child) => Opacity(
opacity: (1 - offset / 18).clamp(0.0, 1.0),
child: Transform.translate(
offset: Offset(0, offset),
child: child,
),
),
child: Padding(
padding: const EdgeInsets.fromLTRB(24, 26, 24, 24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
child: RepaintBoundary(
child: Container(
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.96),
borderRadius:
BorderRadius.circular(compact ? 22 : 30),
border: Border.all(
color: Colors.white.withValues(alpha: 0.8)),
boxShadow: [
BoxShadow(
color: const Color(0xFF1E3A8A)
.withValues(alpha: 0.14),
blurRadius: compact ? 24 : 40,
offset: const Offset(0, 18),
),
],
),
child: Padding(
padding: EdgeInsets.fromLTRB(
compact ? 18 : 24,
compact ? 18 : 26,
compact ? 18 : 24,
compact ? 18 : 24,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Container(
width: 56,
height: 56,
decoration: BoxDecoration(
gradient: const LinearGradient(
colors: [
Color(0xFF2563EB),
Color(0xFF0891B2)
Row(
children: [
Container(
width: compact ? 44 : 56,
height: compact ? 44 : 56,
decoration: BoxDecoration(
gradient: const LinearGradient(
colors: [
Color(0xFF2563EB),
Color(0xFF0891B2)
],
),
borderRadius: BorderRadius.circular(16),
),
child: Icon(Icons.navigation_rounded,
color: Colors.white,
size: compact ? 26 : 30),
),
const SizedBox(width: 12),
const Expanded(
child: Text(
'WalkGuide',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w900,
color: Color(0xFF0F172A),
),
),
),
],
),
SizedBox(height: compact ? 14 : 16),
if (!compact)
Container(
padding: const EdgeInsets.symmetric(
horizontal: 10, vertical: 6),
decoration: BoxDecoration(
color: const Color(0xFFEFF6FF),
borderRadius: BorderRadius.circular(999),
),
child: const Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.shield_outlined,
size: 14, color: Color(0xFF1D4ED8)),
SizedBox(width: 6),
Text(
'Secure Assistive Navigation',
style: TextStyle(
color: Color(0xFF1D4ED8),
fontSize: 11,
fontWeight: FontWeight.w800,
),
),
],
),
borderRadius: BorderRadius.circular(18),
),
child: const Icon(Icons.navigation_rounded,
color: Colors.white, size: 30),
if (!compact) const SizedBox(height: 18),
Text(
title,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: Theme.of(context)
.textTheme
.headlineMedium
?.copyWith(
fontSize: compact ? 26 : null,
fontWeight: FontWeight.w900,
color: const Color(0xFF0F172A),
),
),
const SizedBox(width: 12),
const Expanded(
child: Text(
'WalkGuide',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w900,
color: Color(0xFF0F172A),
),
const SizedBox(height: 6),
Text(
subtitle,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: Color(0xFF64748B),
height: 1.35,
),
),
SizedBox(height: compact ? 18 : 26),
child,
],
),
const SizedBox(height: 16),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 10, vertical: 6),
decoration: BoxDecoration(
color: const Color(0xFFEFF6FF),
borderRadius: BorderRadius.circular(999),
),
child: const Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.shield_outlined,
size: 14, color: Color(0xFF1D4ED8)),
SizedBox(width: 6),
Text(
'Secure Assistive Navigation',
style: TextStyle(
color: Color(0xFF1D4ED8),
fontSize: 11,
fontWeight: FontWeight.w800,
),
),
],
),
),
const SizedBox(height: 18),
Text(
title,
style: Theme.of(context)
.textTheme
.headlineMedium
?.copyWith(
fontWeight: FontWeight.w900,
color: const Color(0xFF0F172A),
),
),
const SizedBox(height: 6),
Text(
subtitle,
style: const TextStyle(
color: Color(0xFF64748B),
height: 1.35,
),
),
const SizedBox(height: 26),
child,
],
),
),
),
),
),
),
),
),
),
],
],
);
},
),
);
}
@@ -299,133 +299,151 @@ class _AuthFrame extends StatelessWidget {
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xFFEAF4FF),
body: Stack(
children: [
const Positioned.fill(
child: DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [Color(0xFFD9EEFF), Color(0xFFF7FAFC)],
),
),
),
),
Positioned(
top: -90,
right: -60,
child: TweenAnimationBuilder<double>(
tween: Tween(begin: 0.85, end: 1),
duration: const Duration(milliseconds: 900),
curve: Curves.easeOutCubic,
builder: (_, value, child) => Transform.scale(
scale: value,
child: child,
),
child: Container(
width: 260,
height: 260,
decoration: BoxDecoration(
color: const Color(0xFF2563EB).withValues(alpha: 0.14),
shape: BoxShape.circle,
),
),
),
),
Center(
child: SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 430),
child: TweenAnimationBuilder<double>(
tween: Tween(begin: 18, end: 0),
duration: const Duration(milliseconds: 520),
curve: Curves.easeOutCubic,
builder: (_, offset, child) => Opacity(
opacity: (1 - offset / 18).clamp(0.0, 1.0),
child: Transform.translate(
offset: Offset(0, offset),
child: child,
body: LayoutBuilder(
builder: (context, constraints) {
final compact =
constraints.maxWidth < 480 || constraints.maxHeight < 720;
return Stack(
children: [
const Positioned.fill(
child: DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [Color(0xFFD9EEFF), Color(0xFFF7FAFC)],
),
),
child: RepaintBoundary(
child: Container(
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.96),
borderRadius: BorderRadius.circular(30),
border: Border.all(
color: Colors.white.withValues(alpha: 0.8)),
boxShadow: [
BoxShadow(
color:
const Color(0xFF1E3A8A).withValues(alpha: 0.14),
blurRadius: 40,
offset: const Offset(0, 20),
),
],
),
),
Positioned(
top: compact ? -70 : -90,
right: compact ? -70 : -60,
child: Container(
width: compact ? 180 : 260,
height: compact ? 180 : 260,
decoration: BoxDecoration(
color: const Color(0xFF2563EB).withValues(alpha: 0.12),
shape: BoxShape.circle,
),
),
),
Center(
child: SingleChildScrollView(
keyboardDismissBehavior:
ScrollViewKeyboardDismissBehavior.onDrag,
padding: EdgeInsets.fromLTRB(
compact ? 14 : 24,
compact ? 12 : 24,
compact ? 14 : 24,
20 + MediaQuery.of(context).viewInsets.bottom,
),
child: ConstrainedBox(
constraints: BoxConstraints(maxWidth: compact ? 380 : 430),
child: TweenAnimationBuilder<double>(
tween: Tween(begin: 18, end: 0),
duration: const Duration(milliseconds: 520),
curve: Curves.easeOutCubic,
builder: (_, offset, child) => Opacity(
opacity: (1 - offset / 18).clamp(0.0, 1.0),
child: Transform.translate(
offset: Offset(0, offset),
child: child,
),
),
child: Padding(
padding: const EdgeInsets.fromLTRB(24, 26, 24, 24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
child: RepaintBoundary(
child: Container(
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.96),
borderRadius:
BorderRadius.circular(compact ? 22 : 30),
border: Border.all(
color: Colors.white.withValues(alpha: 0.8)),
boxShadow: [
BoxShadow(
color: const Color(0xFF1E3A8A)
.withValues(alpha: 0.14),
blurRadius: compact ? 24 : 40,
offset: const Offset(0, 18),
),
],
),
child: Padding(
padding: EdgeInsets.fromLTRB(
compact ? 18 : 24,
compact ? 18 : 26,
compact ? 18 : 24,
compact ? 18 : 24,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Container(
width: 56,
height: 56,
decoration: BoxDecoration(
color: const Color(0xFF1D4ED8),
borderRadius: BorderRadius.circular(18),
),
child: const Icon(Icons.navigation_rounded,
color: Colors.white, size: 30),
),
const SizedBox(width: 12),
const Expanded(
child: Text(
'WalkGuide',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w900,
color: Color(0xFF0F172A),
Row(
children: [
Container(
width: compact ? 44 : 56,
height: compact ? 44 : 56,
decoration: BoxDecoration(
color: const Color(0xFF1D4ED8),
borderRadius: BorderRadius.circular(16),
),
child: Icon(Icons.navigation_rounded,
color: Colors.white,
size: compact ? 26 : 30),
),
const SizedBox(width: 12),
const Expanded(
child: Text(
'WalkGuide',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w900,
color: Color(0xFF0F172A),
),
),
),
],
),
SizedBox(height: compact ? 14 : 22),
Text(
title,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: Theme.of(context)
.textTheme
.headlineMedium
?.copyWith(
fontSize: compact ? 26 : null,
fontWeight: FontWeight.w900,
color: const Color(0xFF0F172A),
),
),
const SizedBox(height: 6),
Text(
subtitle,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: Color(0xFF64748B),
height: 1.35,
),
),
SizedBox(height: compact ? 18 : 26),
child,
],
),
const SizedBox(height: 22),
Text(
title,
style: Theme.of(context)
.textTheme
.headlineMedium
?.copyWith(
fontWeight: FontWeight.w900,
color: const Color(0xFF0F172A),
),
),
const SizedBox(height: 6),
Text(
subtitle,
style: const TextStyle(
color: Color(0xFF64748B),
height: 1.35,
),
),
const SizedBox(height: 26),
child,
],
),
),
),
),
),
),
),
),
),
],
],
);
},
),
);
}
@@ -0,0 +1,3 @@
Call application layer.
This layer owns call state orchestration. The current route keeps a compatibility screen while call side effects are delegated to core services.
@@ -5,6 +5,7 @@ import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import '../../app/injection_container.dart';
import '../../core/errors/friendly_error.dart';
import '../../core/services/call_service.dart';
import '../../core/services/haptic_service.dart';
import '../../core/services/tts_service.dart';
@@ -63,65 +64,71 @@ class _CallScreenState extends State<CallScreen>
unawaited(_finishRemoteEnded());
});
try {
final invite = await callService.startPairedCall();
if (!mounted) return;
if (invite == null) {
final invite = await runFriendly<Map<String, dynamic>>(
() => callService.startPairedCall(),
onError: _failCall,
fallback: 'Panggilan gagal. Server tidak merespons.',
);
if (!mounted) return;
if (invite == null) {
if (_phase != _CallPhase.failed) {
_failCall('Panggilan gagal. Pastikan sudah pairing dan server aktif.');
return;
}
_otherId = _asInt(invite['receiverId']);
_activeChannel = invite['channelName']?.toString();
setState(() => _phase = _CallPhase.calling);
sl<TtsService>().speak(
'Panggilan dikirim ke ${widget.targetLabel}. Menunggu jawaban.',
);
_startAcceptedPolling();
_ringTimeout?.cancel();
_ringTimeout = Timer(const Duration(seconds: 45), () {
if (!mounted || _phase == _CallPhase.connected) return;
_failCall('Panggilan tidak dijawab.');
});
} catch (_) {
if (!mounted) return;
_failCall('Panggilan gagal. Server tidak merespons.');
return;
}
_otherId = _asInt(invite['receiverId']);
_activeChannel = invite['channelName']?.toString();
setState(() => _phase = _CallPhase.calling);
sl<TtsService>().speak(
'Panggilan dikirim ke ${widget.targetLabel}. Menunggu jawaban.',
);
_startAcceptedPolling();
_ringTimeout?.cancel();
_ringTimeout = Timer(const Duration(seconds: 45), () {
if (!mounted || _phase == _CallPhase.connected) return;
_failCall('Panggilan tidak dijawab.');
});
}
void _startAcceptedPolling() {
_acceptedPoll?.cancel();
_acceptedPoll = Timer.periodic(const Duration(seconds: 2), (_) async {
if (!mounted || _activeChannel == null) return;
try {
final state = await sl<CallService>()
final state = await runFriendly<Map<String, dynamic>>(
() => sl<CallService>()
.getCallState(_activeChannel)
.timeout(const Duration(seconds: 3));
final status = state?['status']?.toString();
if (status == 'ENDED') {
await _finishRemoteEnded();
return;
}
if (status == 'ACCEPTED') {
_markRemoteConnected();
return;
}
final accepted = await sl<CallService>()
.getAcceptedCall()
.timeout(const Duration(seconds: 3));
if (accepted?['type']?.toString() != 'CALL_ACCEPTED') return;
final channel = accepted?['channelName']?.toString();
if (_activeChannel != null &&
channel != null &&
channel.isNotEmpty &&
channel != _activeChannel) {
return;
}
_markRemoteConnected();
} catch (_) {
// Keep ringing; a short network hiccup should not cancel the call UI.
.timeout(const Duration(seconds: 3)),
onError: (_) {},
fallback: 'Polling panggilan gagal.',
);
if (state == null) return;
final status = state['status']?.toString();
if (status == 'ENDED') {
await _finishRemoteEnded();
return;
}
if (status == 'ACCEPTED') {
_markRemoteConnected();
return;
}
final accepted = await runFriendly<Map<String, dynamic>>(
() => sl<CallService>()
.getAcceptedCall()
.timeout(const Duration(seconds: 3)),
onError: (_) {},
fallback: 'Polling panggilan diterima gagal.',
);
if (accepted?['type']?.toString() != 'CALL_ACCEPTED') return;
final channel = accepted?['channelName']?.toString();
if (_activeChannel != null &&
channel != null &&
channel.isNotEmpty &&
channel != _activeChannel) {
return;
}
_markRemoteConnected();
});
}
@@ -319,7 +326,12 @@ class _IncomingCallScreenState extends State<IncomingCallScreen> {
setState(() => _responding = true);
sl<TtsService>().speak('Menerima panggilan.');
final joined = await _joinIncomingChannel();
final joined = await runFriendly<bool>(
() => _joinIncomingChannel(),
onError: (_) {},
fallback: 'Panggilan gagal tersambung.',
) ??
false;
if (!mounted) return;
if (!joined || _joinedChannel == null || widget.callerId == null) {
setState(() {
@@ -350,14 +362,16 @@ class _IncomingCallScreenState extends State<IncomingCallScreen> {
_statePoll?.cancel();
_statePoll = Timer.periodic(const Duration(seconds: 2), (_) async {
if (!mounted || _joinedChannel == null) return;
try {
final state = await sl<CallService>()
final state = await runFriendly<Map<String, dynamic>>(
() => sl<CallService>()
.getCallState(_joinedChannel)
.timeout(const Duration(seconds: 3));
if (state?['status']?.toString() == 'ENDED') {
await _finishIncomingRemoteEnded();
}
} catch (_) {}
.timeout(const Duration(seconds: 3)),
onError: (_) {},
fallback: 'Polling panggilan masuk gagal.',
);
if (state?['status']?.toString() == 'ENDED') {
await _finishIncomingRemoteEnded();
}
});
}
@@ -0,0 +1,3 @@
Call data layer.
This layer is reserved for call remote data sources and repository implementations over `/shared/call/**`.
@@ -0,0 +1,3 @@
Call domain layer.
This layer is reserved for call session entities, repository contracts, and call use cases.
@@ -0,0 +1,3 @@
Guardian dashboard application layer.
This layer is reserved for dashboard, map, SOS, notification, AI config, shortcut, and geofence Cubits.
@@ -0,0 +1,3 @@
Guardian dashboard data layer.
This layer is reserved for `/guardian/**` data sources and repository implementations.
@@ -0,0 +1,3 @@
Guardian dashboard domain layer.
This layer is reserved for Guardian dashboard entities, repository contracts, and use cases.
@@ -0,0 +1,3 @@
Home application layer.
This layer is reserved for role-specific home state orchestration.
@@ -0,0 +1,3 @@
Home data layer.
This layer is reserved for home/dashboard data adapters.
@@ -0,0 +1,3 @@
Home domain layer.
This layer is reserved for home/dashboard domain entities and use cases.
@@ -41,6 +41,7 @@ class _GuardianDashboardScreenState extends State<GuardianDashboardScreen>
// ── Live location (WebSocket) ────────────────────────────────────────────────
LatLng? _liveLatLng;
bool _liveConnected = false;
DateTime? _lastRealtimeStatusReload;
final MapController _mapController = MapController();
// ── Pulse animation for live dot ────────────────────────────────────────────
@@ -133,12 +134,13 @@ class _GuardianDashboardScreenState extends State<GuardianDashboardScreen>
'User',
userOnline: userStatus?['online'] as bool? ?? false,
userLastSeen: userStatus?['lastSeenAt']?.toString(),
battery: userStatus?['battery'] as int?,
speed: userStatus?['lastSpeed'] as double?,
obstaclesTotal: userStatus?['obstaclesToday'] as int? ??
dashboard?['obstaclesToday'] as int? ??
battery: (userStatus?['battery'] as num?)?.toInt(),
speed: (userStatus?['lastSpeed'] as num?)?.toDouble(),
obstaclesTotal: (userStatus?['obstaclesToday'] as num?)?.toInt() ??
(dashboard?['obstaclesToday'] as num?)?.toInt() ??
0,
unreadNotif: dashboard?['unreadNotifCount'] as int? ?? 0,
unreadNotif:
(dashboard?['unreadNotifCount'] as num?)?.toInt() ?? 0,
unreadSos: sosPending,
lastLat: lastLoc?['lat'] != null
? (lastLoc!['lat'] as num).toDouble()
@@ -247,6 +249,12 @@ class _GuardianDashboardScreenState extends State<GuardianDashboardScreen>
_liveConnected = true;
});
_moveMapSafely(newPos);
final now = DateTime.now();
if (_lastRealtimeStatusReload == null ||
now.difference(_lastRealtimeStatusReload!).inSeconds >= 15) {
_lastRealtimeStatusReload = now;
unawaited(_loadAll(silent: true));
}
});
ws.subscribeSos((sosData) {
if (!mounted) return;
@@ -3,7 +3,6 @@ import 'package:google_fonts/google_fonts.dart';
import 'package:camera/camera.dart';
import '../../../core/secure_storage.dart';
import '../../auth/presentation/login_screen.dart';
import '../../../../main.dart';
class UserDashboardScreen extends StatefulWidget {
const UserDashboardScreen({super.key});
@@ -12,7 +11,8 @@ class UserDashboardScreen extends StatefulWidget {
State<UserDashboardScreen> createState() => _UserDashboardScreenState();
}
class _UserDashboardScreenState extends State<UserDashboardScreen> with TickerProviderStateMixin {
class _UserDashboardScreenState extends State<UserDashboardScreen>
with TickerProviderStateMixin {
CameraController? _camCtrl;
late AnimationController _radarCtrl;
late Animation<double> _radarAnim;
@@ -31,8 +31,10 @@ class _UserDashboardScreenState extends State<UserDashboardScreen> with TickerPr
}
Future<void> _initCamera() async {
final cameras = await availableCameras();
if (cameras.isEmpty) return;
_camCtrl = CameraController(cameras[0], ResolutionPreset.high, enableAudio: false);
_camCtrl = CameraController(cameras[0], ResolutionPreset.medium,
enableAudio: false);
await _camCtrl!.initialize();
if (mounted) setState(() {});
}
@@ -85,7 +87,8 @@ class _UserDashboardScreenState extends State<UserDashboardScreen> with TickerPr
gradient: RadialGradient(
colors: [
Colors.transparent,
const Color(0xFF10B981).withValues(alpha: 0.05 + _radarCtrl.value * 0.08),
const Color(0xFF10B981)
.withValues(alpha: 0.05 + _radarCtrl.value * 0.08),
],
stops: const [0.5, 1.0],
radius: 1.4,
@@ -127,7 +130,8 @@ class _UserDashboardScreenState extends State<UserDashboardScreen> with TickerPr
),
child: Row(children: [
Container(
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
padding:
const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
decoration: BoxDecoration(
color: Colors.black.withValues(alpha: 0.54),
borderRadius: BorderRadius.circular(20),
@@ -158,7 +162,8 @@ class _UserDashboardScreenState extends State<UserDashboardScreen> with TickerPr
const Spacer(),
IconButton(
onPressed: _logout,
icon: const Icon(Icons.power_settings_new, color: Colors.white, size: 26),
icon: const Icon(Icons.power_settings_new,
color: Colors.white, size: 26),
style: IconButton.styleFrom(
backgroundColor: Colors.redAccent.withValues(alpha: 0.8),
),
@@ -204,15 +209,19 @@ class _UserDashboardScreenState extends State<UserDashboardScreen> with TickerPr
color: const Color(0x33F59E0B),
borderRadius: BorderRadius.circular(7),
),
child: const Icon(Icons.warning_amber_rounded, color: Color(0xFFF59E0B), size: 16),
child: const Icon(Icons.warning_amber_rounded,
color: Color(0xFFF59E0B), size: 16),
),
const SizedBox(width: 10),
Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Text('Obstacle ahead',
style: GoogleFonts.inter(
color: Colors.white, fontSize: 13, fontWeight: FontWeight.w500)),
color: Colors.white,
fontSize: 13,
fontWeight: FontWeight.w500)),
Text('2.1m — Haptic alert sent',
style: GoogleFonts.inter(color: Colors.white60, fontSize: 11)),
style:
GoogleFonts.inter(color: Colors.white60, fontSize: 11)),
]),
]),
),
@@ -234,9 +243,12 @@ class _UserDashboardScreenState extends State<UserDashboardScreen> with TickerPr
),
child: Column(children: [
Row(children: [
Expanded(child: _bigBtn(const Color(0xCC1A56DB), Icons.mic, () {})),
Expanded(
child: _bigBtn(const Color(0xCC1A56DB), Icons.mic, () {})),
const SizedBox(width: 12),
Expanded(child: _bigBtn(const Color(0xCCDC2626), Icons.phone_in_talk, () {})),
Expanded(
child: _bigBtn(
const Color(0xCCDC2626), Icons.phone_in_talk, () {})),
]),
const SizedBox(height: 8),
Text(
@@ -290,7 +302,8 @@ class _RadarPainter extends CustomPainter {
..style = PaintingStyle.stroke
..strokeWidth = 1.2;
for (final r in [48.0, 34.0, 20.0]) {
paint.color = const Color(0xFF60EFAB).withValues(alpha: 0.15 + (50 - r) / 100);
paint.color =
const Color(0xFF60EFAB).withValues(alpha: 0.15 + (50 - r) / 100);
canvas.drawCircle(center, r, paint);
}
paint
@@ -301,4 +314,4 @@ class _RadarPainter extends CustomPainter {
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
}
@@ -0,0 +1,3 @@
Manual application layer.
This layer is reserved for manual/TTS instruction state orchestration.
@@ -0,0 +1,3 @@
Manual data layer.
This layer is reserved for local command and shortcut documentation data sources.
@@ -0,0 +1,3 @@
Manual domain layer.
This layer is reserved for manual section entities and instruction use cases.
@@ -0,0 +1,3 @@
Manual presentation layer.
This layer is reserved for manual pages and widgets.
@@ -0,0 +1,3 @@
Navigation mode application layer.
This layer is reserved for navigation Cubit/BLoC orchestration.
@@ -0,0 +1,3 @@
Navigation mode data layer.
This layer is reserved for location, OSM, and OSRM data adapters.
@@ -0,0 +1,3 @@
Navigation mode domain layer.
This layer is reserved for route, waypoint, and navigation use cases.
@@ -61,35 +61,40 @@ class _NavState extends Cubit<int> {
StreamSubscription<Position>? _posStream;
void _set(_NavPhase p, String status) {
if (isClosed) return;
phase = p;
statusText = status;
_notify();
}
void _notify() => emit(state + 1);
void _notify() {
if (isClosed) return;
emit(state + 1);
}
// ── locate ──────────────────────────────────────────────────────────────
Future<bool> locate() async {
_set(_NavPhase.locating, 'Mencari lokasi GPS…');
final located = await guarded<bool>(
() async {
LocationPermission perm = await Geolocator.checkPermission();
if (perm == LocationPermission.denied) {
perm = await Geolocator.requestPermission();
}
if (perm == LocationPermission.deniedForever) {
_set(_NavPhase.error, 'Izin lokasi diblokir permanen.');
return false;
}
final pos = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high,
).timeout(const Duration(seconds: 12));
currentPosition = LatLng(pos.latitude, pos.longitude);
_set(_NavPhase.idle, 'Lokasi ditemukan. Cari tujuan atau ketuk peta.');
_reportToBackend(pos);
return true;
LocationPermission perm = await Geolocator.checkPermission();
if (perm == LocationPermission.denied) {
perm = await Geolocator.requestPermission();
}
if (perm == LocationPermission.deniedForever) {
_set(_NavPhase.error, 'Izin lokasi diblokir permanen.');
return false;
}
final pos = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high,
).timeout(const Duration(seconds: 12));
currentPosition = LatLng(pos.latitude, pos.longitude);
_set(_NavPhase.idle, 'Lokasi ditemukan. Cari tujuan atau ketuk peta.');
_reportToBackend(pos);
return true;
},
onTimeout: () => _set(_NavPhase.error, 'GPS timeout. Pastikan GPS aktif.'),
onTimeout: () =>
_set(_NavPhase.error, 'GPS timeout. Pastikan GPS aktif.'),
onError: (_) => _set(_NavPhase.error,
'Lokasi belum bisa dibaca. Pastikan GPS dan izin lokasi aktif.'),
);
@@ -113,33 +118,37 @@ class _NavState extends Cubit<int> {
Future<List<_Place>> searchPlaces(String query) async {
if (query.trim().isEmpty) return const [];
return await guarded<List<_Place>>(
() async {
final res = await Dio().get(
'https://nominatim.openstreetmap.org/search',
queryParameters: {
'q': query,
'format': 'jsonv2',
'limit': 6,
'addressdetails': 0,
if (currentPosition != null) 'viewbox': _viewbox(currentPosition!),
if (currentPosition != null) 'bounded': 0,
},
options: Options(
headers: {'User-Agent': 'WalkGuide/1.0 (walkguide@campus.ac.id)'},
receiveTimeout: const Duration(seconds: 8),
),
);
final list = res.data as List;
return list.map((e) {
final lat = double.tryParse(e['lat'].toString()) ?? 0;
final lng = double.tryParse(e['lon'].toString()) ?? 0;
return _Place(
displayName: e['display_name'].toString(),
position: LatLng(lat, lng),
);
}).toList();
},
) ?? const [];
() async {
final res = await Dio().get(
'https://nominatim.openstreetmap.org/search',
queryParameters: {
'q': query,
'format': 'jsonv2',
'limit': 6,
'addressdetails': 0,
if (currentPosition != null)
'viewbox': _viewbox(currentPosition!),
if (currentPosition != null) 'bounded': 0,
},
options: Options(
headers: {
'User-Agent': 'WalkGuide/1.0 (walkguide@campus.ac.id)'
},
receiveTimeout: const Duration(seconds: 8),
),
);
final list = res.data as List;
return list.map((e) {
final lat = double.tryParse(e['lat'].toString()) ?? 0;
final lng = double.tryParse(e['lon'].toString()) ?? 0;
return _Place(
displayName: e['display_name'].toString(),
position: LatLng(lat, lng),
);
}).toList();
},
) ??
const [];
}
String _viewbox(LatLng c) =>
@@ -148,23 +157,25 @@ class _NavState extends Cubit<int> {
// ── reverse geocode ──────────────────────────────────────────────────────
Future<String> reverseGeocode(LatLng pos) async {
return await guarded<String>(
() async {
final res = await Dio().get(
'https://nominatim.openstreetmap.org/reverse',
queryParameters: {
'lat': pos.latitude,
'lon': pos.longitude,
'format': 'jsonv2',
},
options: Options(
headers: {'User-Agent': 'WalkGuide/1.0 (walkguide@campus.ac.id)'},
receiveTimeout: const Duration(seconds: 6),
),
);
return res.data['display_name']?.toString() ??
'${pos.latitude.toStringAsFixed(5)}, ${pos.longitude.toStringAsFixed(5)}';
},
) ??
() async {
final res = await Dio().get(
'https://nominatim.openstreetmap.org/reverse',
queryParameters: {
'lat': pos.latitude,
'lon': pos.longitude,
'format': 'jsonv2',
},
options: Options(
headers: {
'User-Agent': 'WalkGuide/1.0 (walkguide@campus.ac.id)'
},
receiveTimeout: const Duration(seconds: 6),
),
);
return res.data['display_name']?.toString() ??
'${pos.latitude.toStringAsFixed(5)}, ${pos.longitude.toStringAsFixed(5)}';
},
) ??
'${pos.latitude.toStringAsFixed(5)}, ${pos.longitude.toStringAsFixed(5)}';
}
@@ -180,47 +191,47 @@ class _NavState extends Cubit<int> {
final origin = currentPosition!;
await guarded<void>(
() async {
final url = 'http://router.project-osrm.org/route/v1/foot/'
'${origin.longitude},${origin.latitude};'
'${dest.position.longitude},${dest.position.latitude}'
'?steps=true&geometries=geojson&overview=full&annotations=false';
final url = 'http://router.project-osrm.org/route/v1/foot/'
'${origin.longitude},${origin.latitude};'
'${dest.position.longitude},${dest.position.latitude}'
'?steps=true&geometries=geojson&overview=full&annotations=false';
final res = await Dio().get(
url,
options: Options(receiveTimeout: const Duration(seconds: 12)),
);
final res = await Dio().get(
url,
options: Options(receiveTimeout: const Duration(seconds: 12)),
);
final route = res.data['routes'][0];
final geom = route['geometry']['coordinates'] as List;
routePoints = geom.map((c) {
final lst = c as List;
return LatLng((lst[1] as num).toDouble(), (lst[0] as num).toDouble());
}).toList();
final route = res.data['routes'][0];
final geom = route['geometry']['coordinates'] as List;
routePoints = geom.map((c) {
final lst = c as List;
return LatLng((lst[1] as num).toDouble(), (lst[0] as num).toDouble());
}).toList();
// parse steps
final legs = route['legs'] as List;
final rawSteps = <_Step>[];
for (final leg in legs) {
for (final step in leg['steps'] as List) {
final maneuver = step['maneuver'] as Map;
final instruction = _buildInstruction(maneuver, step);
final dist = (step['distance'] as num?)?.toDouble() ?? 0;
final loc = maneuver['location'] as List;
rawSteps.add(_Step(
instruction: instruction,
distanceM: dist,
point:
LatLng((loc[1] as num).toDouble(), (loc[0] as num).toDouble()),
));
// parse steps
final legs = route['legs'] as List;
final rawSteps = <_Step>[];
for (final leg in legs) {
for (final step in leg['steps'] as List) {
final maneuver = step['maneuver'] as Map;
final instruction = _buildInstruction(maneuver, step);
final dist = (step['distance'] as num?)?.toDouble() ?? 0;
final loc = maneuver['location'] as List;
rawSteps.add(_Step(
instruction: instruction,
distanceM: dist,
point: LatLng(
(loc[1] as num).toDouble(), (loc[0] as num).toDouble()),
));
}
}
}
steps = rawSteps;
currentStepIndex = 0;
steps = rawSteps;
currentStepIndex = 0;
_set(_NavPhase.navigating,
steps.isNotEmpty ? steps[0].instruction : 'Ikuti rute biru.');
_notify();
_startTracking();
_set(_NavPhase.navigating,
steps.isNotEmpty ? steps[0].instruction : 'Ikuti rute biru.');
_notify();
_startTracking();
},
onError: (_) => _set(_NavPhase.error,
'Gagal mendapat rute. Periksa koneksi lalu coba lagi.'),
@@ -289,6 +300,7 @@ class _NavState extends Cubit<int> {
distanceFilter: 5,
),
).listen((pos) {
if (isClosed) return;
currentPosition = LatLng(pos.latitude, pos.longitude);
_reportToBackend(pos);
_updateStep();
@@ -298,6 +310,7 @@ class _NavState extends Cubit<int> {
void _updateStep() {
if (steps.isEmpty || phase != _NavPhase.navigating) return;
if (currentPosition == null) return;
if (currentStepIndex >= steps.length - 1) return;
final current = steps[currentStepIndex];
@@ -317,6 +330,7 @@ class _NavState extends Cubit<int> {
}
void stopNavigation() {
if (isClosed) return;
_posStream?.cancel();
_posStream = null;
destination = null;
@@ -0,0 +1,3 @@
Pairing application layer.
This layer is reserved for pairing Cubit/BLoC orchestration.
@@ -0,0 +1,3 @@
Pairing data layer.
This layer is reserved for `/shared/pairing/**` data sources and repository implementations.
@@ -0,0 +1,3 @@
Pairing domain layer.
This layer is reserved for pairing entities, repository contracts, and use cases.
@@ -0,0 +1,3 @@
Server connect application layer.
This layer is reserved for connection testing and save-server-url state orchestration.
@@ -0,0 +1,3 @@
Server connect data layer.
This layer is reserved for ping data sources and local server URL persistence adapters.
@@ -0,0 +1,3 @@
Server connect domain layer.
This layer is reserved for server info entities and connection use cases.
@@ -0,0 +1,3 @@
Server connect presentation layer.
This layer is reserved for first-run connection pages and widgets.
@@ -37,6 +37,7 @@ class _ServerConnectScreenState extends State<ServerConnectScreen> {
await runFriendlyAction(
() async {
final clean = AppConstants.normalizeServerUrl(_url.text);
await sl<ApiClient>().init(clean);
final res = await Dio(BaseOptions(
connectTimeout: AppConstants.pingTimeout,
receiveTimeout: AppConstants.pingTimeout,
@@ -47,7 +48,8 @@ class _ServerConnectScreenState extends State<ServerConnectScreen> {
: 'Server merespons, tetapi format ping tidak valid.';
},
onError: (message) => _message = message,
fallback: 'Tidak bisa terhubung. Periksa URL dan jaringan.',
fallback:
'Tidak bisa terhubung. Untuk HP via USB, jalankan adb reverse tcp:8080 tcp:8080 lalu pakai http://127.0.0.1:8080.',
);
if (mounted) setState(() => _loading = false);
}
@@ -60,6 +62,8 @@ class _ServerConnectScreenState extends State<ServerConnectScreen> {
}
void _useUsbUrl() => setState(() => _url.text = 'http://127.0.0.1:8080');
void _useAndroidEmulatorUrl() =>
setState(() => _url.text = 'http://10.0.2.2:8080');
@override
Widget build(BuildContext context) {
@@ -96,12 +100,23 @@ class _ServerConnectScreenState extends State<ServerConnectScreen> {
SafeArea(
child: LayoutBuilder(
builder: (context, constraints) {
final compact = constraints.maxWidth < 390;
final compact =
constraints.maxWidth < 480 || constraints.maxHeight < 720;
final horizontalPadding =
constraints.maxWidth < 480 ? 12.0 : 20.0;
return SingleChildScrollView(
padding: EdgeInsets.fromLTRB(20, compact ? 20 : 36, 20, 24),
keyboardDismissBehavior:
ScrollViewKeyboardDismissBehavior.onDrag,
padding: EdgeInsets.fromLTRB(
horizontalPadding,
compact ? 10 : 32,
horizontalPadding,
20 + MediaQuery.of(context).viewInsets.bottom,
),
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 460),
constraints:
BoxConstraints(maxWidth: compact ? 380 : 520),
child: TweenAnimationBuilder<double>(
tween: Tween(begin: 18, end: 0),
duration: const Duration(milliseconds: 520),
@@ -114,7 +129,8 @@ class _ServerConnectScreenState extends State<ServerConnectScreen> {
child: Container(
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.96),
borderRadius: BorderRadius.circular(28),
borderRadius:
BorderRadius.circular(compact ? 22 : 28),
border: Border.all(
color: Colors.white.withValues(alpha: 0.7)),
boxShadow: [
@@ -126,13 +142,18 @@ class _ServerConnectScreenState extends State<ServerConnectScreen> {
],
),
child: ClipRRect(
borderRadius: BorderRadius.circular(28),
borderRadius:
BorderRadius.circular(compact ? 22 : 28),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Container(
padding:
const EdgeInsets.fromLTRB(22, 22, 22, 20),
padding: EdgeInsets.fromLTRB(
compact ? 14 : 22,
compact ? 14 : 22,
compact ? 14 : 22,
compact ? 14 : 20,
),
decoration: const BoxDecoration(
color: Color(0xFF071226),
),
@@ -143,37 +164,38 @@ class _ServerConnectScreenState extends State<ServerConnectScreen> {
Row(
children: [
Container(
width: 48,
height: 48,
width: compact ? 38 : 48,
height: compact ? 38 : 48,
decoration: BoxDecoration(
color: const Color(0xFF2563EB),
borderRadius:
BorderRadius.circular(16),
),
child: const Icon(
Icons.navigation_rounded,
color: Colors.white,
size: 28),
child: Icon(
Icons.navigation_rounded,
color: Colors.white,
size: compact ? 24 : 28,
),
),
const SizedBox(width: 12),
const Expanded(
Expanded(
child: Text(
'WalkGuide Link',
'WalkGuide',
style: TextStyle(
color: Colors.white,
fontSize: 20,
fontSize: compact ? 16 : 20,
fontWeight: FontWeight.w900,
),
),
),
],
),
const SizedBox(height: 18),
const Text(
SizedBox(height: compact ? 14 : 18),
Text(
'Connect to Server',
style: TextStyle(
color: Colors.white,
fontSize: 30,
fontSize: compact ? 22 : 30,
fontWeight: FontWeight.w900,
height: 1,
),
@@ -191,7 +213,7 @@ class _ServerConnectScreenState extends State<ServerConnectScreen> {
),
),
Padding(
padding: const EdgeInsets.all(22),
padding: EdgeInsets.all(compact ? 14 : 22),
child: Column(
crossAxisAlignment:
CrossAxisAlignment.stretch,
@@ -217,13 +239,18 @@ class _ServerConnectScreenState extends State<ServerConnectScreen> {
label: 'USB: 127.0.0.1',
onTap: _useUsbUrl,
),
_HintChip(
icon: Icons.phone_android_outlined,
label: 'Emulator: 10.0.2.2',
onTap: _useAndroidEmulatorUrl,
),
const _HintChip(
icon: Icons.wifi_tethering_outlined,
label: 'Wi-Fi: IP laptop',
),
],
),
const SizedBox(height: 16),
SizedBox(height: compact ? 12 : 16),
OutlinedButton.icon(
onPressed: _loading ? null : _test,
icon: _loading
@@ -251,15 +278,17 @@ class _ServerConnectScreenState extends State<ServerConnectScreen> {
label: const Text('Continue'),
),
],
const SizedBox(height: 18),
const Center(
child: Text(
'v1.0.0 | Spring Boot + Flutter',
style: TextStyle(
fontSize: 11,
color: Color(0xFF94A3B8)),
if (!compact) ...[
const SizedBox(height: 18),
const Center(
child: Text(
'v1.0.0 | Spring Boot + Flutter',
style: TextStyle(
fontSize: 11,
color: Color(0xFF94A3B8)),
),
),
),
],
],
),
),
@@ -0,0 +1,3 @@
Settings application layer.
This layer is reserved for settings Cubit/BLoC orchestration.
@@ -0,0 +1,3 @@
Settings data layer.
This layer is reserved for `/user/settings` and local settings data adapters.
@@ -0,0 +1,3 @@
Settings domain layer.
This layer is reserved for settings entities, repository contracts, and update use cases.
@@ -125,6 +125,7 @@ class _UserSettingsScreenState extends State<UserSettingsScreen> {
setState(() => _saving = true);
// Apply TTS locally dulu
await sl<TtsService>().setLanguage(_ttsLanguage);
context.read<AppCubit>().setLocaleCode(_ttsLanguage);
if (_hapticEnabled) {
await sl<HapticService>().success();
}
@@ -243,9 +243,18 @@ class _SosScreenState extends State<SosScreen>
bloc: _sosCubit,
builder: (context, sosState) {
final sending = sosState.phase == SosPhase.sending;
final size = MediaQuery.sizeOf(context);
final compact = size.height < 620;
final landscapeTight = size.width > size.height && size.height < 520;
final pagePadding = compact ? 12.0 : 16.0;
final sectionGap = landscapeTight
? 8.0
: compact
? 12.0
: 24.0;
return SafeArea(
child: Padding(
padding: const EdgeInsets.all(16),
padding: EdgeInsets.all(pagePadding),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
@@ -278,14 +287,14 @@ class _SosScreenState extends State<SosScreen>
],
),
const SizedBox(height: 24),
SizedBox(height: sectionGap),
// Active SOS banner
if (_hasActiveSos)
_ActiveSosBanner(
event: _events.first, onRefresh: _loadHistory),
const SizedBox(height: 24),
SizedBox(height: sectionGap),
// SOS Button
Center(
@@ -312,6 +321,8 @@ class _SosScreenState extends State<SosScreen>
? 'SOS aktif — Guardian sudah mendapat notifikasi'
: 'Tekan tombol untuk kirim SOS darurat ke Guardian',
textAlign: TextAlign.center,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: TextStyle(
color: _hasActiveSos
? const Color(0xFFDC2626)
@@ -321,22 +332,25 @@ class _SosScreenState extends State<SosScreen>
),
),
const SizedBox(height: 28),
SizedBox(height: sectionGap),
// History section
const Text(
'Riwayat SOS',
style: TextStyle(fontWeight: FontWeight.w800, fontSize: 16),
),
const SizedBox(height: 10),
Expanded(
if (!landscapeTight) ...[
const Text(
'Riwayat SOS',
style: TextStyle(fontWeight: FontWeight.w800, fontSize: 16),
),
const SizedBox(height: 10),
Expanded(
child: _SosHistory(
loading: _historyLoading,
error: _historyError,
events: _events,
onRefresh: _loadHistory,
)),
loading: _historyLoading,
error: _historyError,
events: _events,
onRefresh: _loadHistory,
),
),
] else
const Spacer(),
],
),
),
@@ -361,8 +375,16 @@ class _SosButton extends StatelessWidget {
@override
Widget build(BuildContext context) {
final screen = MediaQuery.sizeOf(context);
final compact = screen.height < 620;
final landscapeTight = screen.width > screen.height && screen.height < 520;
final dimension = landscapeTight
? 132.0
: compact
? 154.0
: 200.0;
return SizedBox.square(
dimension: 200,
dimension: dimension,
child: FilledButton(
style: FilledButton.styleFrom(
shape: const CircleBorder(),
@@ -377,14 +399,14 @@ class _SosButton extends StatelessWidget {
children: [
Icon(
active ? Icons.emergency : Icons.emergency_outlined,
size: 48,
size: dimension < 150 ? 34 : 48,
color: Colors.white,
),
const SizedBox(height: 6),
SizedBox(height: dimension < 150 ? 3 : 6),
Text(
'SOS',
style: const TextStyle(
fontSize: 38,
style: TextStyle(
fontSize: dimension < 150 ? 28 : 38,
fontWeight: FontWeight.w900,
color: Colors.white,
letterSpacing: 2,
@@ -402,8 +424,16 @@ class _SendingIndicator extends StatelessWidget {
@override
Widget build(BuildContext context) {
final screen = MediaQuery.sizeOf(context);
final compact = screen.height < 620;
final landscapeTight = screen.width > screen.height && screen.height < 520;
final dimension = landscapeTight
? 132.0
: compact
? 154.0
: 200.0;
return SizedBox.square(
dimension: 200,
dimension: dimension,
child: DecoratedBox(
decoration: BoxDecoration(
color: const Color(0xFFDC2626).withValues(alpha: 0.15),
@@ -144,6 +144,7 @@ class _WalkGuideScreenState extends State<WalkGuideScreen>
() async {
final cameras = await availableCameras();
if (cameras.isEmpty) return;
await sl<YoloDetector>().init();
final backCamera = cameras.firstWhere(
(camera) => camera.lensDirection == CameraLensDirection.back,
orElse: () => cameras.first,
@@ -808,6 +809,7 @@ class _Page extends StatelessWidget {
@override
Widget build(BuildContext context) {
final compact = MediaQuery.sizeOf(context).height < 520;
return SafeArea(
child: DecoratedBox(
decoration: const BoxDecoration(
@@ -818,15 +820,20 @@ class _Page extends StatelessWidget {
),
),
child: Padding(
padding: const EdgeInsets.fromLTRB(16, 14, 16, 16),
padding: EdgeInsets.fromLTRB(
compact ? 12 : 16,
compact ? 8 : 14,
compact ? 12 : 16,
compact ? 10 : 16,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Container(
width: 46,
height: 46,
width: compact ? 38 : 46,
height: compact ? 38 : 46,
decoration: BoxDecoration(
color: const Color(0xFF2563EB),
borderRadius: BorderRadius.circular(14),
@@ -839,21 +846,24 @@ class _Page extends StatelessWidget {
),
],
),
child: const Icon(Icons.navigation_rounded,
color: Colors.white, size: 26),
child: Icon(Icons.navigation_rounded,
color: Colors.white, size: compact ? 22 : 26),
),
const SizedBox(width: 12),
SizedBox(width: compact ? 10 : 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context)
.textTheme
.headlineSmall
?.copyWith(
fontWeight: FontWeight.w900,
color: const Color(0xFF0F172A),
fontSize: compact ? 22 : null,
)),
if (subtitle != null)
Text(subtitle!,
@@ -866,7 +876,7 @@ class _Page extends StatelessWidget {
...?actions,
],
),
const SizedBox(height: 16),
SizedBox(height: compact ? 8 : 16),
Expanded(child: child),
],
),
+188 -17
View File
@@ -1,36 +1,207 @@
import 'dart:async';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'app/injection_container.dart';
import 'app/app.dart';
import 'core/constants/app_constants.dart';
import 'core/utils/init_guard.dart';
List<CameraDescription> cameras = [];
@pragma('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
await Firebase.initializeApp();
}
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await runZonedGuarded(
() async {
WidgetsFlutterBinding.ensureInitialized();
_installGlobalErrorUi();
await AppConstants.clearServerUrl();
cameras = await ignoreInitFailure(
availableCameras,
label: 'Camera init',
) ??
[];
if (!kIsWeb) {
final firebaseApp = await ignoreInitFailure(
() => Firebase.initializeApp(),
label: 'Firebase init',
);
if (firebaseApp != null) {
FirebaseMessaging.onBackgroundMessage(
_firebaseMessagingBackgroundHandler,
);
}
}
if (!kIsWeb) {
await ignoreInitFailure(() => Firebase.initializeApp(),
label: 'Firebase init');
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
try {
await initDependencies();
} catch (error, stackTrace) {
debugPrint('WalkGuide startup failed: $error\n$stackTrace');
runApp(WalkGuideFatalApp(error: error, stackTrace: stackTrace));
return;
}
runApp(const WalkGuideApp());
},
(error, stackTrace) {
debugPrint('WalkGuide uncaught error: $error\n$stackTrace');
runApp(WalkGuideFatalApp(error: error, stackTrace: stackTrace));
},
);
}
void _installGlobalErrorUi() {
FlutterError.onError = (details) {
FlutterError.presentError(details);
debugPrint('WalkGuide Flutter error: ${details.exceptionAsString()}');
};
PlatformDispatcher.instance.onError = (error, stackTrace) {
debugPrint('WalkGuide platform error: $error\n$stackTrace');
return true;
};
ErrorWidget.builder = (details) {
return WalkGuideErrorPanel(
title: 'WalkGuide UI Error',
message:
'A screen failed to render. Please report this message to the developer.',
details: details.exceptionAsString(),
);
};
}
class WalkGuideFatalApp extends StatelessWidget {
final Object error;
final StackTrace? stackTrace;
const WalkGuideFatalApp({
super.key,
required this.error,
this.stackTrace,
});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: WalkGuideErrorPanel(
title: 'WalkGuide Startup Error',
message:
'The app could not finish startup. Please report this screen to the developer.',
details: error.toString(),
stackTrace: stackTrace?.toString(),
),
);
}
}
class WalkGuideErrorPanel extends StatelessWidget {
final String title;
final String message;
final String details;
final String? stackTrace;
const WalkGuideErrorPanel({
super.key,
required this.title,
required this.message,
required this.details,
this.stackTrace,
});
@override
Widget build(BuildContext context) {
final textTheme = Theme.of(context).textTheme;
return Scaffold(
backgroundColor: const Color(0xFFF8FAFC),
body: SafeArea(
child: Center(
child: SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 520),
child: DecoratedBox(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(16),
border: Border.all(color: const Color(0xFFE2E8F0)),
boxShadow: const [
BoxShadow(
blurRadius: 24,
offset: Offset(0, 12),
color: Color(0x1A0F172A),
),
],
),
child: Padding(
padding: const EdgeInsets.all(22),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Icon(
Icons.error_outline,
color: Color(0xFFDC2626),
size: 42,
),
const SizedBox(height: 16),
Text(
title,
style: textTheme.headlineSmall?.copyWith(
fontWeight: FontWeight.w800,
color: const Color(0xFF0F172A),
),
),
const SizedBox(height: 8),
Text(
message,
style: textTheme.bodyMedium?.copyWith(
color: const Color(0xFF475569),
),
),
const SizedBox(height: 18),
Container(
width: double.infinity,
padding: const EdgeInsets.all(14),
decoration: BoxDecoration(
color: const Color(0xFFF1F5F9),
borderRadius: BorderRadius.circular(10),
border: Border.all(color: const Color(0xFFE2E8F0)),
),
child: SelectableText(
_formatDetails(),
style: const TextStyle(
fontFamily: 'monospace',
fontSize: 12,
color: Color(0xFF334155),
),
),
),
const SizedBox(height: 16),
const Text(
'Tip: close the app and open it again after fixing the configuration.',
style: TextStyle(
color: Color(0xFF64748B),
fontSize: 12,
),
),
],
),
),
),
),
),
),
),
);
}
// Init GetIt dependencies
await initDependencies();
runApp(const WalkGuideApp());
String _formatDetails() {
final stack = stackTrace;
if (stack == null || stack.isEmpty) return details;
final shortStack = stack.split('\n').take(8).join('\n');
return '$details\n\n$shortStack';
}
}
@@ -26,7 +26,9 @@ class _UserShellState extends State<UserShell> {
super.initState();
_loadVoiceCommands();
_startHardwareShortcuts();
sl<SttService>().startListening();
WidgetsBinding.instance.addPostFrameCallback((_) {
_startVoiceListening();
});
sl<VoiceCommandHandler>().onCommand = (key) {
if (!mounted) return;
switch (key) {
@@ -64,6 +66,17 @@ class _UserShellState extends State<UserShell> {
};
}
Future<void> _startVoiceListening() async {
await runFriendlyAction(
() async {
await sl<SttService>().init();
await sl<SttService>().startListening();
},
onError: (_) {},
fallback: 'Voice listener belum bisa dimuat.',
);
}
Future<void> _loadVoiceCommands() async {
await runFriendlyAction(
() async {
@@ -182,42 +195,41 @@ class _AppShell extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: AppColors.surface,
body: AnimatedSwitcher(
duration: const Duration(milliseconds: 180),
switchInCurve: Curves.easeOutCubic,
switchOutCurve: Curves.easeInCubic,
child: KeyedSubtree(
key: ValueKey(location),
child: child,
),
),
bottomNavigationBar: DecoratedBox(
decoration: BoxDecoration(
color: Colors.white,
border: const Border(top: BorderSide(color: AppColors.border)),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.06),
blurRadius: 18,
offset: const Offset(0, -8),
),
],
),
child: NavigationBar(
selectedIndex: _selectedIndex,
onDestinationSelected: (index) => context.go(items[index].route),
destinations: [
for (final item in items)
NavigationDestination(
icon: Icon(item.icon),
selectedIcon: Icon(item.selectedIcon),
label: item.label,
),
],
),
),
return LayoutBuilder(
builder: (context, constraints) {
final useRail = constraints.maxWidth >= 760;
final content = AnimatedSwitcher(
duration: const Duration(milliseconds: 180),
switchInCurve: Curves.easeOutCubic,
switchOutCurve: Curves.easeInCubic,
child: KeyedSubtree(
key: ValueKey(location),
child: child,
),
);
return Scaffold(
backgroundColor: AppColors.surface,
body: useRail
? Row(
children: [
_RailNavigation(
items: items,
selectedIndex: _selectedIndex,
),
const VerticalDivider(width: 1, color: AppColors.border),
Expanded(child: content),
],
)
: content,
bottomNavigationBar: useRail
? null
: _BottomScrollNavigation(
items: items,
selectedIndex: _selectedIndex,
),
);
},
);
}
@@ -227,6 +239,194 @@ class _AppShell extends StatelessWidget {
}
}
class _RailNavigation extends StatelessWidget {
final List<_ShellItem> items;
final int selectedIndex;
const _RailNavigation({
required this.items,
required this.selectedIndex,
});
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
final compact = constraints.maxHeight < 520;
final width = compact ? 76.0 : 86.0;
final itemHeight = compact ? 58.0 : 70.0;
return DecoratedBox(
decoration: const BoxDecoration(color: Colors.white),
child: SafeArea(
right: false,
child: SizedBox(
width: width,
child: ListView.separated(
padding: EdgeInsets.symmetric(
horizontal: 8,
vertical: compact ? 6 : 12,
),
itemCount: items.length,
separatorBuilder: (_, __) => SizedBox(height: compact ? 2 : 6),
itemBuilder: (context, index) {
final item = items[index];
final selected = index == selectedIndex;
return Semantics(
button: true,
selected: selected,
label: item.label,
child: InkWell(
borderRadius: BorderRadius.circular(18),
onTap: () => context.go(items[index].route),
child: AnimatedContainer(
duration: const Duration(milliseconds: 160),
height: itemHeight,
padding: const EdgeInsets.symmetric(horizontal: 4),
decoration: BoxDecoration(
color: selected
? const Color(0xFFEFF6FF)
: Colors.transparent,
borderRadius: BorderRadius.circular(18),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
selected ? item.selectedIcon : item.icon,
size: compact ? 23 : 25,
color: selected
? AppColors.primary
: const Color(0xFF334155),
),
SizedBox(height: compact ? 2 : 5),
Text(
item.label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: compact ? 10 : 12,
height: 1,
fontWeight: selected
? FontWeight.w800
: FontWeight.w600,
color: selected
? const Color(0xFF1D4ED8)
: const Color(0xFF334155),
),
),
],
),
),
),
);
},
),
),
),
);
},
);
}
}
class _BottomScrollNavigation extends StatelessWidget {
final List<_ShellItem> items;
final int selectedIndex;
const _BottomScrollNavigation({
required this.items,
required this.selectedIndex,
});
@override
Widget build(BuildContext context) {
final bottom = MediaQuery.of(context).padding.bottom;
final extraBottom = bottom > 12 ? 12.0 : bottom;
return DecoratedBox(
decoration: BoxDecoration(
color: Colors.white,
border: const Border(top: BorderSide(color: AppColors.border)),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.06),
blurRadius: 18,
offset: const Offset(0, -8),
),
],
),
child: SafeArea(
top: false,
child: SizedBox(
height: 68 + extraBottom,
child: ListView.separated(
scrollDirection: Axis.horizontal,
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
itemCount: items.length,
separatorBuilder: (_, __) => const SizedBox(width: 6),
itemBuilder: (context, index) {
final item = items[index];
final selected = index == selectedIndex;
return Semantics(
button: true,
selected: selected,
label: item.label,
child: InkWell(
borderRadius: BorderRadius.circular(12),
onTap: () => context.go(item.route),
child: AnimatedContainer(
duration: const Duration(milliseconds: 160),
width: 72,
padding: const EdgeInsets.symmetric(horizontal: 6),
decoration: BoxDecoration(
color: selected
? const Color(0xFFEFF6FF)
: Colors.transparent,
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: selected
? const Color(0xFFBFDBFE)
: Colors.transparent,
),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
selected ? item.selectedIcon : item.icon,
color: selected
? AppColors.primary
: const Color(0xFF64748B),
size: 22,
),
const SizedBox(height: 4),
Text(
item.label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 11,
fontWeight:
selected ? FontWeight.w800 : FontWeight.w600,
color: selected
? AppColors.primary
: const Color(0xFF64748B),
),
),
],
),
),
),
);
},
),
),
),
);
}
}
class _ShellItem {
final String label;
final IconData icon;
@@ -19,62 +19,127 @@ class FeaturePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return SafeArea(
child: Padding(
padding: const EdgeInsets.fromLTRB(16, 14, 16, 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TweenAnimationBuilder<double>(
tween: Tween(begin: 12, end: 0),
duration: const Duration(milliseconds: 360),
curve: Curves.easeOutCubic,
builder: (_, offset, child) => Opacity(
opacity: (1 - offset / 12).clamp(0.0, 1.0),
child: Transform.translate(
offset: Offset(0, offset),
child: child,
child: LayoutBuilder(
builder: (context, constraints) {
final short = constraints.maxHeight < 520;
final compact = constraints.maxWidth < 420 || short;
final wide = constraints.maxWidth >= 900;
final horizontal = compact ? 12.0 : 20.0;
return Padding(
padding: EdgeInsets.fromLTRB(
horizontal,
short ? 8 : 12,
horizontal,
short ? 10 : 14,
),
child: Center(
child: ConstrainedBox(
constraints: BoxConstraints(
maxWidth: wide ? 1160 : double.infinity,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TweenAnimationBuilder<double>(
tween: Tween(begin: 12, end: 0),
duration: const Duration(milliseconds: 360),
curve: Curves.easeOutCubic,
builder: (_, offset, child) => Opacity(
opacity: (1 - offset / 12).clamp(0.0, 1.0),
child: Transform.translate(
offset: Offset(0, offset),
child: child,
),
),
child: compact
? Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_FeatureHeading(
title: title,
subtitle: subtitle,
compact: compact,
),
if (trailing != null) ...[
const SizedBox(height: 10),
Align(
alignment: Alignment.centerLeft,
child: trailing!,
),
],
],
)
: Row(
children: [
Expanded(
child: _FeatureHeading(
title: title,
subtitle: subtitle,
compact: compact,
),
),
if (trailing != null) trailing!,
],
),
),
SizedBox(height: short ? 8 : (compact ? 12 : 16)),
Expanded(
child: child,
),
],
),
),
child: Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
style: Theme.of(context)
.textTheme
.headlineSmall
?.copyWith(
fontWeight: FontWeight.w900,
color: AppColors.text,
),
),
const SizedBox(height: 2),
Text(
subtitle,
style: const TextStyle(
color: AppColors.muted,
fontWeight: FontWeight.w500,
),
),
],
),
),
if (trailing != null) trailing!,
],
),
),
const SizedBox(height: 16),
Expanded(child: child),
],
),
);
},
),
);
}
}
class _FeatureHeading extends StatelessWidget {
final String title;
final String subtitle;
final bool compact;
const _FeatureHeading({
required this.title,
required this.subtitle,
required this.compact,
});
@override
Widget build(BuildContext context) {
final short = MediaQuery.sizeOf(context).height < 520;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
maxLines: short ? 1 : 2,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.headlineSmall?.copyWith(
fontSize: compact ? 22 : null,
fontWeight: FontWeight.w900,
color: AppColors.text,
),
),
const SizedBox(height: 2),
Text(
subtitle,
maxLines: short ? 1 : (compact ? 2 : 3),
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: AppColors.muted,
fontWeight: FontWeight.w500,
height: 1.25,
),
),
],
);
}
}
class FeatureEmptyPanel extends StatelessWidget {
final IconData icon;
final String title;
@@ -7,6 +7,7 @@ import Foundation
import agora_rtc_engine
import audio_session
import battery_plus
import connectivity_plus
import device_info_plus
import firebase_core
@@ -27,6 +28,7 @@ import sqlite3_flutter_libs
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
AgoraRtcNgPlugin.register(with: registry.registrar(forPlugin: "AgoraRtcNgPlugin"))
AudioSessionPlugin.register(with: registry.registrar(forPlugin: "AudioSessionPlugin"))
BatteryPlusMacosPlugin.register(with: registry.registrar(forPlugin: "BatteryPlusMacosPlugin"))
ConnectivityPlusPlugin.register(with: registry.registrar(forPlugin: "ConnectivityPlusPlugin"))
DeviceInfoPlusMacosPlugin.register(with: registry.registrar(forPlugin: "DeviceInfoPlusMacosPlugin"))
FLTFirebaseCorePlugin.register(with: registry.registrar(forPlugin: "FLTFirebaseCorePlugin"))
@@ -65,6 +65,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "0.1.25"
battery_plus:
dependency: "direct main"
description:
name: battery_plus
sha256: "03d5a6bb36db9d2b977c548f6b0262d5a84c4d5a4cfee2edac4a91d57011b365"
url: "https://pub.dev"
source: hosted
version: "6.2.3"
battery_plus_platform_interface:
dependency: transitive
description:
name: battery_plus_platform_interface
sha256: e8342c0f32de4b1dfd0223114b6785e48e579bfc398da9471c9179b907fa4910
url: "https://pub.dev"
source: hosted
version: "2.0.1"
bloc:
dependency: transitive
description:
@@ -571,6 +587,11 @@ packages:
url: "https://pub.dev"
source: hosted
version: "7.2.0"
flutter_localizations:
dependency: "direct main"
description: flutter
source: sdk
version: "0.0.0"
flutter_map:
dependency: "direct main"
description:
@@ -1652,6 +1673,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "0.3.1"
upower:
dependency: transitive
description:
name: upower
sha256: cf042403154751180affa1d15614db7fa50234bc2373cd21c3db666c38543ebf
url: "https://pub.dev"
source: hosted
version: "0.7.0"
uuid:
dependency: transitive
description:
@@ -9,6 +9,8 @@ environment:
dependencies:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
# State management
flutter_bloc: ^8.1.6
@@ -50,6 +52,7 @@ dependencies:
# Location
geolocator: ^12.0.0
battery_plus: ^6.2.3
# Agora VoIP
agora_rtc_engine: ^6.3.2
@@ -7,6 +7,7 @@
#include "generated_plugin_registrant.h"
#include <agora_rtc_engine/agora_rtc_engine_plugin.h>
#include <battery_plus/battery_plus_windows_plugin.h>
#include <connectivity_plus/connectivity_plus_windows_plugin.h>
#include <firebase_core/firebase_core_plugin_c_api.h>
#include <flutter_secure_storage_windows/flutter_secure_storage_windows_plugin.h>
@@ -21,6 +22,8 @@
void RegisterPlugins(flutter::PluginRegistry* registry) {
AgoraRtcEnginePluginRegisterWithRegistrar(
registry->GetRegistrarForPlugin("AgoraRtcEnginePlugin"));
BatteryPlusWindowsPluginRegisterWithRegistrar(
registry->GetRegistrarForPlugin("BatteryPlusWindowsPlugin"));
ConnectivityPlusWindowsPluginRegisterWithRegistrar(
registry->GetRegistrarForPlugin("ConnectivityPlusWindowsPlugin"));
FirebaseCorePluginCApiRegisterWithRegistrar(
@@ -4,6 +4,7 @@
list(APPEND FLUTTER_PLUGIN_LIST
agora_rtc_engine
battery_plus
connectivity_plus
firebase_core
flutter_secure_storage_windows