feat: introduce FixMate Flutter app and React dashboard

- Add Flutter app shell (FixMateApp/MainScreen) with tabs: Report, Map,
  My Reports, Settings
- Implement capture and review flow (image_picker, geolocator, deterministic
  mock AI), and local storage (SharedPreferences + photo files on mobile)
- Build Map screen with flutter_map, marker clustering, filters, legend,
  marker details, and external maps deeplink
- Add My Reports list (view details, cycle status, delete) and Settings
  (language toggle via Provider, diagnostics, clear all data)
- Introduce JSON i18n loader and LocaleProvider; add EN/BM assets
- Define models (Report, enums) and UI badges (severity, status)

- Add static React dashboard (Leaflet map with clustering, heatmap toggle,
  filters incl. date range, queue, detail drawer), i18n (EN/BM), and
  demo data

- Update build/config and platform setup:
  - Extend pubspec with required packages and register i18n assets
  - Android: add CAMERA and location permissions; pin NDK version
  - iOS: add usage descriptions for camera, photo library, location
  - Gradle properties tuned for Windows/UNC stability
  - Register desktop plugins (Linux/macOS/Windows)
  - .gitignore: ignore .kilocode
  - Overhaul README and replace sample widget test
This commit is contained in:
2025-09-25 18:38:18 +08:00
parent d16e56bdcf
commit 6518df8ac1
39 changed files with 4377 additions and 162 deletions

111
lib/app.dart Normal file
View File

@@ -0,0 +1,111 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'l10n/i18n.dart';
import 'l10n/locale_provider.dart';
import 'screens/report_flow/capture_screen.dart';
import 'screens/map/map_screen.dart';
import 'screens/my_reports/my_reports_screen.dart';
import 'screens/settings/settings_screen.dart';
class FixMateApp extends StatelessWidget {
const FixMateApp({super.key});
@override
Widget build(BuildContext context) {
return Consumer<LocaleProvider>(
builder: (context, localeProvider, child) {
return MaterialApp(
title: I18n.t('app.name'),
theme: ThemeData(
primarySwatch: Colors.blue,
brightness: Brightness.light,
useMaterial3: true,
),
locale: localeProvider.locale,
supportedLocales: const [
Locale('en', 'US'),
Locale('ms', 'MY'),
],
home: const MainScreen(),
);
},
);
}
}
class MainScreen extends StatefulWidget {
const MainScreen({super.key});
@override
State<MainScreen> createState() => _MainScreenState();
}
class _MainScreenState extends State<MainScreen> {
int _selectedIndex = 0;
final List<Widget> _screens = [
const CaptureScreen(),
const MapScreen(),
const MyReportsScreen(),
const SettingsScreen(),
];
final List<String> _navLabels = [
'nav.report',
'nav.map',
'nav.myReports',
'nav.settings',
];
@override
Widget build(BuildContext context) {
return Scaffold(
body: _screens[_selectedIndex],
bottomNavigationBar: BottomNavigationBar(
currentIndex: _selectedIndex,
onTap: (index) {
setState(() {
_selectedIndex = index;
});
},
type: BottomNavigationBarType.fixed,
items: [
BottomNavigationBarItem(
icon: const Icon(Icons.camera_alt),
label: I18n.t(_navLabels[0]),
),
BottomNavigationBarItem(
icon: const Icon(Icons.map),
label: I18n.t(_navLabels[1]),
),
BottomNavigationBarItem(
icon: const Icon(Icons.list),
label: I18n.t(_navLabels[2]),
),
BottomNavigationBarItem(
icon: const Icon(Icons.settings),
label: I18n.t(_navLabels[3]),
),
],
),
);
}
}
class PlaceholderScreen extends StatelessWidget {
final String title;
const PlaceholderScreen({super.key, required this.title});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
child: Text('$title - Coming Soon!'),
),
);
}
}

79
lib/l10n/i18n.dart Normal file
View File

@@ -0,0 +1,79 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;
/// Simple JSON-based internationalization service
class I18n {
static Map<String, String> _localizedStrings = {};
static const String _defaultLocale = 'en';
static String _loadedLocale = _defaultLocale;
/// Initialize the i18n system with the given locale
static Future<void> init(Locale locale) async {
_loadedLocale = locale.languageCode;
await _loadLanguage(locale.languageCode);
}
/// Load language strings from JSON asset
static Future<void> _loadLanguage(String languageCode) async {
try {
final String jsonString = await rootBundle.loadString(
'assets/lang/$languageCode.json',
);
final Map<String, dynamic> jsonMap = json.decode(jsonString);
_localizedStrings = jsonMap.map((key, value) {
return MapEntry(key, value.toString());
});
} catch (e) {
// Fallback to default locale if current locale fails
// ignore: avoid_print
print('Error loading language file for $languageCode: $e');
if (languageCode != _defaultLocale) {
_loadedLocale = _defaultLocale;
await _loadLanguage(_defaultLocale);
}
}
}
/// Get translated string for the given key
static String t(String key, [Map<String, String>? args]) {
String? translation = _localizedStrings[key];
if (translation == null) {
// Fallback to key itself if translation not found
// ignore: avoid_print
print('Translation key not found: $key');
return key;
}
// Replace placeholders if arguments provided
if (args != null && args.isNotEmpty) {
args.forEach((placeholder, value) {
translation = translation!.replaceAll('{$placeholder}', value);
});
}
return translation!;
}
/// Get the current locale code
static String get currentLocale => _loadedLocale;
/// Check if a translation key exists
static bool hasKey(String key) {
return _localizedStrings.containsKey(key);
}
/// Get all available translation keys
static Set<String> get keys => _localizedStrings.keys.toSet();
/// Get the number of loaded translations
static int get translationCount => _localizedStrings.length;
/// Clear loaded translations (useful for testing)
static void clear() {
_localizedStrings.clear();
_loadedLocale = _defaultLocale;
}
}

View File

@@ -0,0 +1,101 @@
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
/// Provider for managing app locale and language switching
class LocaleProvider extends ChangeNotifier {
static const String _languageKey = 'lang';
static const String _defaultLanguage = 'en';
Locale _locale = const Locale('en');
late SharedPreferences _prefs;
/// Get the current locale
Locale get locale => _locale;
/// Get the current language code
String get languageCode => _locale.languageCode;
/// Initialize the locale provider
Future<void> init() async {
_prefs = await SharedPreferences.getInstance();
final savedLanguage = _prefs.getString(_languageKey) ?? _defaultLanguage;
_locale = Locale(savedLanguage);
notifyListeners();
}
/// Set the locale and persist the change
Future<void> setLocale(Locale locale) async {
if (_locale == locale) return;
_locale = locale;
await _prefs.setString(_languageKey, locale.languageCode);
notifyListeners();
}
/// Toggle between English and Bahasa Malaysia
Future<void> toggleLanguage() async {
final newLanguage = _locale.languageCode == 'en' ? 'ms' : 'en';
await setLocale(Locale(newLanguage));
}
/// Set language to English
Future<void> setEnglish() async {
await setLocale(const Locale('en'));
}
/// Set language to Bahasa Malaysia
Future<void> setMalay() async {
await setLocale(const Locale('ms'));
}
/// Check if current language is English
bool get isEnglish => _locale.languageCode == 'en';
/// Check if current language is Bahasa Malaysia
bool get isMalay => _locale.languageCode == 'ms';
/// Get the display name for the current language
String get currentLanguageDisplayName {
switch (_locale.languageCode) {
case 'en':
return 'English';
case 'ms':
return 'Bahasa Malaysia';
default:
return 'English';
}
}
/// Get the native display name for the current language
String get currentLanguageNativeName {
switch (_locale.languageCode) {
case 'en':
return 'English';
case 'ms':
return 'Bahasa Malaysia';
default:
return 'English';
}
}
/// Get available locales
List<Locale> get availableLocales => const [
Locale('en'),
Locale('ms'),
];
/// Get available language codes
List<String> get availableLanguageCodes => ['en', 'ms'];
/// Clear saved language preference
Future<void> clearSavedLanguage() async {
await _prefs.remove(_languageKey);
_locale = const Locale(_defaultLanguage);
notifyListeners();
}
/// Reset to default language
Future<void> resetToDefault() async {
await setLocale(const Locale(_defaultLanguage));
}
}

View File

@@ -1,122 +1,24 @@
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// TRY THIS: Try running your application with "flutter run". You'll see
// the application has a purple toolbar. Then, without quitting the app,
// try changing the seedColor in the colorScheme below to Colors.green
// and then invoke "hot reload" (save your changes or press the "hot
// reload" button in a Flutter-supported IDE, or press "r" if you used
// the command line to start the app).
//
// Notice that the counter didn't reset back to zero; the application
// state is not lost during the reload. To reset the state, use hot
// restart instead.
//
// This works for code too, not just values: Most code changes can be
// tested with just a hot reload.
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// TRY THIS: Try changing the color here to a specific color (to
// Colors.amber, perhaps?) and trigger a hot reload to see the AppBar
// change color while the other colors stay the same.
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
//
// TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint"
// action in the IDE, or press "p" in the console), to see the
// wireframe for each widget.
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text('You have pushed the button this many times:'),
Text(
'$_counter',
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
import 'package:provider/provider.dart';
import 'app.dart';
import 'l10n/i18n.dart';
import 'l10n/locale_provider.dart';
export 'app.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// Initialize locale provider
final localeProvider = LocaleProvider();
await localeProvider.init();
// Initialize i18n with the current locale
await I18n.init(localeProvider.locale);
runApp(
ChangeNotifierProvider.value(
value: localeProvider,
child: const FixMateApp(),
),
);
}

206
lib/models/enums.dart Normal file
View File

@@ -0,0 +1,206 @@
import 'package:flutter/material.dart';
/// Categories for different types of issues that can be reported
enum Category {
pothole,
streetlight,
signage,
trash,
drainage,
other;
/// Get the string key for localization
String get key {
switch (this) {
case Category.pothole:
return 'category.pothole';
case Category.streetlight:
return 'category.streetlight';
case Category.signage:
return 'category.signage';
case Category.trash:
return 'category.trash';
case Category.drainage:
return 'category.drainage';
case Category.other:
return 'category.other';
}
}
/// Get the display name for this category
String get displayName {
switch (this) {
case Category.pothole:
return 'Pothole';
case Category.streetlight:
return 'Streetlight';
case Category.signage:
return 'Signage';
case Category.trash:
return 'Trash';
case Category.drainage:
return 'Drainage';
case Category.other:
return 'Other';
}
}
/// Get all categories as a list
static List<Category> get all => Category.values;
}
/// Severity levels for reported issues
enum Severity {
high,
medium,
low;
/// Get the string key for localization
String get key {
switch (this) {
case Severity.high:
return 'severity.high';
case Severity.medium:
return 'severity.medium';
case Severity.low:
return 'severity.low';
}
}
/// Get the display name for this severity
String get displayName {
switch (this) {
case Severity.high:
return 'High';
case Severity.medium:
return 'Medium';
case Severity.low:
return 'Low';
}
}
/// Get the color associated with this severity
Color get color {
switch (this) {
case Severity.high:
return const Color(0xFFD32F2F); // Red 700
case Severity.medium:
return const Color(0xFFF57C00); // Orange 700
case Severity.low:
return const Color(0xFF388E3C); // Green 700
}
}
/// Get all severities as a list
static List<Severity> get all => Severity.values;
}
/// Status of reported issues
enum Status {
submitted,
inProgress,
fixed;
/// Get the string key for localization
String get key {
switch (this) {
case Status.submitted:
return 'status.submitted';
case Status.inProgress:
return 'status.in_progress';
case Status.fixed:
return 'status.fixed';
}
}
/// Get the display name for this status
String get displayName {
switch (this) {
case Status.submitted:
return 'Submitted';
case Status.inProgress:
return 'In Progress';
case Status.fixed:
return 'Fixed';
}
}
/// Get the color associated with this status
Color get color {
switch (this) {
case Status.submitted:
return const Color(0xFF1976D2); // Blue 700
case Status.inProgress:
return const Color(0xFF7B1FA2); // Purple 700
case Status.fixed:
return const Color(0xFF455A64); // Blue Grey 700
}
}
/// Get the next status in the cycle
Status get next {
switch (this) {
case Status.submitted:
return Status.inProgress;
case Status.inProgress:
return Status.fixed;
case Status.fixed:
return Status.submitted; // Cycle back to submitted
}
}
/// Get all statuses as a list
static List<Status> get all => Status.values;
}
/// Helper extensions for enum parsing
extension CategoryParsing on String {
Category? toCategory() {
switch (toLowerCase()) {
case 'pothole':
return Category.pothole;
case 'streetlight':
return Category.streetlight;
case 'signage':
return Category.signage;
case 'trash':
return Category.trash;
case 'drainage':
return Category.drainage;
case 'other':
return Category.other;
default:
return null;
}
}
}
extension SeverityParsing on String {
Severity? toSeverity() {
switch (toLowerCase()) {
case 'high':
return Severity.high;
case 'medium':
return Severity.medium;
case 'low':
return Severity.low;
default:
return null;
}
}
}
extension StatusParsing on String {
Status? toStatus() {
switch (toLowerCase()) {
case 'submitted':
return Status.submitted;
case 'in_progress':
return Status.inProgress;
case 'fixed':
return Status.fixed;
default:
return null;
}
}
}

300
lib/models/report.dart Normal file
View File

@@ -0,0 +1,300 @@
import 'dart:math';
import 'enums.dart';
/// Represents a citizen report for community issues
class Report {
/// Unique identifier for the report
final String id;
/// Category of the issue
final Category category;
/// Severity level of the issue
final Severity severity;
/// Current status of the report
final Status status;
/// File path to the photo on mobile devices
final String? photoPath;
/// Base64 encoded photo for web platform
final String? base64Photo;
/// Geographic location where the issue was reported
final LocationData location;
/// When the report was created (ISO string)
final String createdAt;
/// When the report was last updated (ISO string)
final String updatedAt;
/// Unique device identifier
final String deviceId;
/// Optional notes from the user
final String? notes;
/// Address or location description (placeholder for future use)
final String? address;
/// Source of the photo ("camera" or "gallery")
final String source;
/// Whether the report can be edited
final bool editable;
/// Whether the report can be deleted
final bool deletable;
/// AI suggestion for category and severity
final AISuggestion aiSuggestion;
/// Schema version for data migration
final int schemaVersion;
const Report({
required this.id,
required this.category,
required this.severity,
required this.status,
this.photoPath,
this.base64Photo,
required this.location,
required this.createdAt,
required this.updatedAt,
required this.deviceId,
this.notes,
this.address,
required this.source,
this.editable = true,
this.deletable = true,
required this.aiSuggestion,
this.schemaVersion = 1,
});
/// Generate a simple unique ID
static String _generateId() {
final timestamp = DateTime.now().millisecondsSinceEpoch;
final random = Random().nextInt(999999);
return '$timestamp$random';
}
/// Create a new report with current timestamp and generated ID
factory Report.create({
required Category category,
required Severity severity,
required LocationData location,
String? photoPath,
String? base64Photo,
String? notes,
required String source,
required String deviceId,
required AISuggestion aiSuggestion,
}) {
final now = DateTime.now().toIso8601String();
return Report(
id: _generateId(),
category: category,
severity: severity,
status: Status.submitted,
photoPath: photoPath,
base64Photo: base64Photo,
location: location,
createdAt: now,
updatedAt: now,
deviceId: deviceId,
notes: notes,
source: source,
aiSuggestion: aiSuggestion,
);
}
/// Create a copy of this report with updated fields
Report copyWith({
Category? category,
Severity? severity,
Status? status,
String? photoPath,
String? base64Photo,
LocationData? location,
String? updatedAt,
String? notes,
String? address,
bool? editable,
bool? deletable,
AISuggestion? aiSuggestion,
}) {
return Report(
id: id,
category: category ?? this.category,
severity: severity ?? this.severity,
status: status ?? this.status,
photoPath: photoPath ?? this.photoPath,
base64Photo: base64Photo ?? this.base64Photo,
location: location ?? this.location,
createdAt: createdAt,
updatedAt: updatedAt ?? this.updatedAt,
deviceId: deviceId,
notes: notes ?? this.notes,
address: address ?? this.address,
source: source,
editable: editable ?? this.editable,
deletable: deletable ?? this.deletable,
aiSuggestion: aiSuggestion ?? this.aiSuggestion,
schemaVersion: schemaVersion,
);
}
/// Convert to JSON for storage
Map<String, dynamic> toJson() {
return {
'id': id,
'category': category.name,
'severity': severity.name,
'status': status.key,
'photoPath': photoPath,
'base64Photo': base64Photo,
'location': {
'lat': location.lat,
'lng': location.lng,
'accuracy': location.accuracy,
},
'createdAt': createdAt,
'updatedAt': updatedAt,
'deviceId': deviceId,
'notes': notes,
'address': address,
'source': source,
'editable': editable,
'deletable': deletable,
'aiSuggestion': {
'category': aiSuggestion.category.name,
'severity': aiSuggestion.severity.name,
'confidence': aiSuggestion.confidence,
},
'schemaVersion': schemaVersion,
};
}
/// Create from JSON for loading from storage
factory Report.fromJson(Map<String, dynamic> json) {
return Report(
id: json['id'] as String,
category: (json['category'] as String).toCategory() ?? Category.other,
severity: (json['severity'] as String).toSeverity() ?? Severity.medium,
status: (json['status'] as String).toStatus() ?? Status.submitted,
photoPath: json['photoPath'] as String?,
base64Photo: json['base64Photo'] as String?,
location: LocationData(
lat: (json['location']['lat'] as num).toDouble(),
lng: (json['location']['lng'] as num).toDouble(),
accuracy: json['location']['accuracy'] == null
? null
: (json['location']['accuracy'] as num).toDouble(),
),
createdAt: json['createdAt'] as String,
updatedAt: json['updatedAt'] as String,
deviceId: json['deviceId'] as String,
notes: json['notes'] as String?,
address: json['address'] as String?,
source: json['source'] as String,
editable: json['editable'] as bool? ?? true,
deletable: json['deletable'] as bool? ?? true,
aiSuggestion: AISuggestion(
category: (json['aiSuggestion']['category'] as String).toCategory() ?? Category.other,
severity: (json['aiSuggestion']['severity'] as String).toSeverity() ?? Severity.medium,
confidence: (json['aiSuggestion']['confidence'] as num).toDouble(),
),
schemaVersion: json['schemaVersion'] as int? ?? 1,
);
}
@override
String toString() {
return 'Report(id: $id, category: ${category.name}, severity: ${severity.name}, status: ${status.name})';
}
@override
bool operator ==(Object other) {
if (identical(this, other)) return true;
return other is Report && other.id == id;
}
@override
int get hashCode => id.hashCode;
}
/// Represents geographic location data
class LocationData {
/// Latitude coordinate
final double lat;
/// Longitude coordinate
final double lng;
/// Accuracy of the location in meters (optional)
final double? accuracy;
const LocationData({
required this.lat,
required this.lng,
this.accuracy,
});
@override
String toString() {
return 'LocationData(lat: $lat, lng: $lng, accuracy: $accuracy)';
}
@override
bool operator ==(Object other) {
if (identical(this, other)) return true;
return other is LocationData &&
other.lat == lat &&
other.lng == lng &&
other.accuracy == accuracy;
}
@override
int get hashCode => Object.hash(lat, lng, accuracy);
}
/// Represents AI suggestion for category and severity
class AISuggestion {
/// Suggested category
final Category category;
/// Suggested severity
final Severity severity;
/// Confidence score between 0.0 and 1.0
final double confidence;
const AISuggestion({
required this.category,
required this.severity,
required this.confidence,
});
/// Check if confidence is high enough to be considered reliable
bool get isReliable => confidence >= 0.7;
@override
String toString() {
return 'AISuggestion(category: ${category.name}, severity: ${severity.name}, confidence: ${confidence.toStringAsFixed(2)})';
}
@override
bool operator ==(Object other) {
if (identical(this, other)) return true;
return other is AISuggestion &&
other.category == category &&
other.severity == severity &&
other.confidence == confidence;
}
@override
int get hashCode => Object.hash(category, severity, confidence);
}

View File

@@ -0,0 +1,543 @@
import 'dart:convert';
import 'dart:io' show File;
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:flutter_map_marker_cluster/flutter_map_marker_cluster.dart';
import 'package:latlong2/latlong.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../l10n/i18n.dart';
import '../../models/enums.dart';
import '../../models/report.dart';
import '../../services/location_service.dart';
import '../../services/storage.dart';
import '../../widgets/severity_badge.dart';
import '../../widgets/status_badge.dart';
import '../my_reports/my_reports_screen.dart';
/// MapScreen - displays reports on an interactive OpenStreetMap with clustering
class MapScreen extends StatefulWidget {
const MapScreen({super.key});
@override
State<MapScreen> createState() => _MapScreenState();
}
class _MapScreenState extends State<MapScreen> {
final MapController _mapController = MapController();
List<Report> _allReports = [];
List<Report> _filteredReports = [];
bool _loading = true;
// In-memory filters
Set<Category> _filterCategories = Category.all.toSet();
Set<Severity> _filterSeverities = Severity.all.toSet();
Set<Status> _filterStatuses = Status.all.toSet();
DateTimeRange? _filterDateRange;
// Defaults
static final LatLng _defaultCenter = LatLng(3.1390, 101.6869); // Kuala Lumpur
static const double _defaultZoom = 13.0;
@override
void initState() {
super.initState();
_setDefaultDateRange();
_refresh();
}
void _setDefaultDateRange() {
final now = DateTime.now();
_filterDateRange = DateTimeRange(start: now.subtract(const Duration(days: 30)), end: now);
}
Future<void> _refresh() async {
setState(() => _loading = true);
final reports = await StorageService.getReports();
setState(() {
_allReports = reports;
_loading = false;
});
_applyFilters();
// If we have filtered reports, fit; otherwise try device location
if (_filteredReports.isNotEmpty) {
WidgetsBinding.instance.addPostFrameCallback((_) => _fitToBounds());
} else {
await _centerOnDeviceOrDefault();
}
}
Future<void> _centerOnDeviceOrDefault() async {
try {
final pos = await LocationService.getBestAvailablePosition();
if (pos != null) {
_mapController.move(LatLng(pos.latitude, pos.longitude), _defaultZoom);
return;
}
} catch (_) {}
// fallback
_mapController.move(_defaultCenter, _defaultZoom);
}
void _applyFilters() {
final range = _filterDateRange;
_filteredReports = _allReports.where((r) {
if (!_filterCategories.contains(r.category)) return false;
if (!_filterSeverities.contains(r.severity)) return false;
if (!_filterStatuses.contains(r.status)) return false;
if (range != null) {
final created = DateTime.tryParse(r.createdAt);
if (created == null) return false;
// include the end day fully
final endInclusive = DateTime(range.end.year, range.end.month, range.end.day, 23, 59, 59);
if (created.isBefore(range.start) || created.isAfter(endInclusive)) return false;
}
return true;
}).toList();
setState(() {});
if (_filteredReports.isNotEmpty) {
WidgetsBinding.instance.addPostFrameCallback((_) => _fitToBounds());
}
}
void _fitToBounds() {
if (_filteredReports.isEmpty) return;
final points = _filteredReports.map((r) => LatLng(r.location.lat, r.location.lng)).toList();
if (points.isEmpty) return;
final bounds = LatLngBounds.fromPoints(points);
try {
_mapController.fitCamera(
CameraFit.bounds(bounds: bounds, padding: const EdgeInsets.all(60)),
);
} catch (_) {
// ignore
}
}
List<Marker> _buildMarkers() {
return _filteredReports.map((r) {
final latlng = LatLng(r.location.lat, r.location.lng);
return Marker(
point: latlng,
width: 40,
height: 40,
child: GestureDetector(
onTap: () => _onMarkerTap(r),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.location_on, color: r.severity.color, size: 36),
],
),
),
);
}).toList();
}
void _onMarkerTap(Report r) {
showModalBottomSheet(
context: context,
isScrollControlled: true,
builder: (ctx) {
return SafeArea(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Wrap(
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_buildThumbnail(r),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(I18n.t(r.category.key), style: Theme.of(context).textTheme.titleLarge),
const SizedBox(height: 8),
Row(children: [
SeverityBadge(severity: r.severity, small: true),
const SizedBox(width: 8),
StatusBadge(status: r.status, small: true),
]),
const SizedBox(height: 8),
Text('${I18n.t('label.location')}: ${r.location.lat.toStringAsFixed(6)}, ${r.location.lng.toStringAsFixed(6)}'),
const SizedBox(height: 4),
Text('${I18n.t('label.createdAt')}: ${r.createdAt.split('T').first}'),
],
),
),
],
),
const SizedBox(height: 12),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
TextButton(
onPressed: () {
Navigator.of(ctx).pop(); // close sheet
// Navigate to My Reports tab/screen (simplest)
Navigator.push(context, MaterialPageRoute(builder: (_) => const MyReportsScreen()));
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(I18n.t('map.openedInMyReports') ?? I18n.t('nav.myReports'))),
);
},
child: Text(I18n.t('btn.viewDetails')),
),
const SizedBox(width: 8),
ElevatedButton(
onPressed: () => _openExternalMap(r.location.lat, r.location.lng),
child: Text(I18n.t('btn.openMap')),
),
],
),
],
),
),
);
},
);
}
Widget _buildThumbnail(Report r) {
final placeholder = Container(
width: 120,
height: 90,
color: Colors.grey.shade200,
alignment: Alignment.center,
child: Icon(Icons.photo, color: Colors.grey.shade600),
);
if (kIsWeb) {
if (r.base64Photo != null && r.base64Photo!.isNotEmpty) {
try {
final bytes = base64Decode(r.base64Photo!);
return Image.memory(bytes, width: 120, height: 90, fit: BoxFit.cover);
} catch (_) {
return placeholder;
}
}
return placeholder;
} else {
if (r.photoPath != null && r.photoPath!.isNotEmpty) {
final file = File(r.photoPath!);
if (file.existsSync()) {
return Image.file(file, width: 120, height: 90, fit: BoxFit.cover);
}
}
return placeholder;
}
}
Future<void> _openExternalMap(double lat, double lng) async {
final uri = Uri.parse('https://www.google.com/maps/search/?api=1&query=$lat,$lng');
try {
if (!await launchUrl(uri, mode: LaunchMode.externalApplication)) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(I18n.t('error.openMap'))));
}
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(I18n.t('error.openMap'))));
}
}
Future<void> _openFilterModal() async {
// Use current filters as initial values
final now = DateTime.now();
Set<Category> selCategories = Set.from(_filterCategories);
Set<Severity> selSeverities = Set.from(_filterSeverities);
Set<Status> selStatuses = Set.from(_filterStatuses);
DateTimeRange? selRange = _filterDateRange;
await showModalBottomSheet(
context: context,
isScrollControlled: true,
builder: (ctx) {
return StatefulBuilder(builder: (context, setModalState) {
return Padding(
padding: EdgeInsets.only(bottom: MediaQuery.of(ctx).viewInsets.bottom),
child: SafeArea(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(mainAxisSize: MainAxisSize.min, children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(I18n.t('btn.filter'), style: Theme.of(context).textTheme.titleMedium),
IconButton(
icon: const Icon(Icons.close),
onPressed: () => Navigator.pop(ctx),
)
],
),
const SizedBox(height: 8),
Align(alignment: Alignment.centerLeft, child: Text(I18n.t('filter.category'))),
const SizedBox(height: 8),
Wrap(
spacing: 8,
children: Category.all.map((c) {
final selected = selCategories.contains(c);
return FilterChip(
label: Text(I18n.t(c.key)),
selected: selected,
onSelected: (v) {
setModalState(() {
if (v) {
selCategories.add(c);
} else {
selCategories.remove(c);
}
});
},
);
}).toList(),
),
const SizedBox(height: 12),
Align(alignment: Alignment.centerLeft, child: Text(I18n.t('filter.severity'))),
const SizedBox(height: 8),
Wrap(
spacing: 8,
children: Severity.all.map((s) {
final selected = selSeverities.contains(s);
return FilterChip(
label: Text(I18n.t(s.key)),
selected: selected,
onSelected: (v) {
setModalState(() {
if (v) {
selSeverities.add(s);
} else {
selSeverities.remove(s);
}
});
},
);
}).toList(),
),
const SizedBox(height: 12),
Align(alignment: Alignment.centerLeft, child: Text(I18n.t('filter.status'))),
const SizedBox(height: 8),
Wrap(
spacing: 8,
children: Status.all.map((st) {
final selected = selStatuses.contains(st);
return FilterChip(
label: Text(I18n.t(st.key)),
selected: selected,
onSelected: (v) {
setModalState(() {
if (v) {
selStatuses.add(st);
} else {
selStatuses.remove(st);
}
});
},
);
}).toList(),
),
const SizedBox(height: 12),
Align(alignment: Alignment.centerLeft, child: Text(I18n.t('filter.dateRange'))),
const SizedBox(height: 8),
Row(children: [
Expanded(
child: OutlinedButton(
onPressed: () async {
final picked = await showDateRangePicker(
context: context,
firstDate: DateTime(2000),
lastDate: now,
initialDateRange: selRange ?? DateTimeRange(start: now.subtract(const Duration(days: 30)), end: now),
);
if (picked != null) {
setModalState(() => selRange = picked);
}
},
child: Text(selRange == null ? I18n.t('filter.dateRange') : '${selRange!.start.toLocal().toIso8601String().split('T').first} - ${selRange!.end.toLocal().toIso8601String().split('T').first}'),
),
),
]),
const SizedBox(height: 12),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
TextButton(
onPressed: () {
setModalState(() {
selCategories = Category.all.toSet();
selSeverities = Severity.all.toSet();
selStatuses = Status.all.toSet();
selRange = DateTimeRange(start: now.subtract(const Duration(days: 30)), end: now);
});
},
child: Text(I18n.t('btn.reset')),
),
ElevatedButton(
onPressed: () {
// Apply
setState(() {
_filterCategories = selCategories;
_filterSeverities = selSeverities;
_filterStatuses = selStatuses;
_filterDateRange = selRange;
});
_applyFilters();
Navigator.pop(ctx);
},
child: Text(I18n.t('btn.apply')),
),
],
),
]),
),
),
);
});
},
);
}
@override
Widget build(BuildContext context) {
final markers = _buildMarkers();
return Scaffold(
appBar: AppBar(
title: Text(I18n.t('nav.map')),
actions: [
IconButton(icon: const Icon(Icons.filter_list), onPressed: _openFilterModal),
IconButton(icon: const Icon(Icons.refresh), onPressed: _refresh),
],
),
body: _loading
? const Center(child: CircularProgressIndicator())
: _filteredReports.isEmpty
? Center(child: Text(I18n.t('map.noReports')))
: Stack(
children: [
FlutterMap(
mapController: _mapController,
options: MapOptions(
initialCenter: _filteredReports.isNotEmpty
? LatLng(_filteredReports.first.location.lat, _filteredReports.first.location.lng)
: _defaultCenter,
initialZoom: _defaultZoom,
minZoom: 3.0,
maxZoom: 18.0,
),
children: [
TileLayer(
urlTemplate: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
userAgentPackageName: 'com.example.citypulse',
),
if (markers.isNotEmpty)
MarkerClusterLayerWidget(
options: MarkerClusterLayerOptions(
maxClusterRadius: 60,
size: const Size(40, 40),
markers: markers,
spiderfyCircleRadius: 80,
showPolygon: false,
disableClusteringAtZoom: 16,
builder: (context, markers) {
return Container(
alignment: Alignment.center,
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.primary,
shape: BoxShape.circle,
),
child: Text(
markers.length.toString(),
style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
),
);
},
onClusterTap: (cluster) {
try {
final pts = cluster.markers.map((m) => m.point).toList();
final bounds = LatLngBounds.fromPoints(pts);
_mapController.fitCamera(
CameraFit.bounds(bounds: bounds, padding: const EdgeInsets.all(60)),
);
} catch (_) {}
},
),
),
],
),
// Legend overlay
Positioned(
top: 16,
right: 16,
child: Card(
elevation: 2,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
_legendItem(Severity.high, I18n.t('severity.high')),
const SizedBox(width: 8),
_legendItem(Severity.medium, I18n.t('severity.medium')),
const SizedBox(width: 8),
_legendItem(Severity.low, I18n.t('severity.low')),
],
),
),
),
),
],
),
);
}
Widget _legendItem(Severity s, String label) {
return Row(
children: [
Container(width: 12, height: 12, decoration: BoxDecoration(color: s.color, shape: BoxShape.circle)),
const SizedBox(width: 6),
Text(label, style: const TextStyle(fontSize: 12)),
],
);
}
}
/// Full screen report details used elsewhere in the app.
class MapReportDetails extends StatelessWidget {
final Report report;
const MapReportDetails({super.key, required this.report});
@override
Widget build(BuildContext context) {
final created = DateTime.tryParse(report.createdAt);
return Scaffold(
appBar: AppBar(title: Text(I18n.t('btn.details'))),
body: SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
if (kIsWeb && report.base64Photo != null)
Image.memory(base64Decode(report.base64Photo!))
else if (!kIsWeb && report.photoPath != null)
Image.file(File(report.photoPath!))
else
Container(height: 180, color: Colors.grey.shade200, alignment: Alignment.center, child: const Icon(Icons.photo, size: 64)),
const SizedBox(height: 12),
Text(I18n.t(report.category.key), style: Theme.of(context).textTheme.titleLarge),
const SizedBox(height: 8),
Row(children: [SeverityBadge(severity: report.severity), const SizedBox(width: 8), StatusBadge(status: report.status)]),
const SizedBox(height: 12),
Text('${I18n.t('label.location')}: ${report.location.lat.toStringAsFixed(6)}, ${report.location.lng.toStringAsFixed(6)}'),
const SizedBox(height: 8),
Text('${I18n.t('label.createdAt')}: ${created != null ? created.toLocal().toString() : report.createdAt}'),
const SizedBox(height: 8),
if (report.notes != null) Text('${I18n.t('label.notes')}: ${report.notes}'),
]),
),
);
}
}

View File

@@ -0,0 +1,85 @@
import 'package:flutter/material.dart';
import '../../services/storage.dart';
import '../../models/report.dart';
import '../../widgets/report_card.dart';
import '../map/map_screen.dart';
import '../../l10n/i18n.dart';
class MyReportsScreen extends StatefulWidget {
const MyReportsScreen({super.key});
@override
State<MyReportsScreen> createState() => _MyReportsScreenState();
}
class _MyReportsScreenState extends State<MyReportsScreen> {
List<Report> _reports = [];
bool _loading = true;
@override
void initState() {
super.initState();
_loadReports();
}
Future<void> _loadReports() async {
setState(() {
_loading = true;
});
final reports = await StorageService.getReports();
setState(() {
_reports = reports.reversed.toList(); // newest first
_loading = false;
});
}
void _onViewReport(Report r) {
Navigator.push(
context,
MaterialPageRoute(builder: (_) => MapReportDetails(report: r)),
);
}
void _onDeleted() async {
await _loadReports();
}
void _onUpdated(Report updated) async {
await _loadReports();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(I18n.t('nav.myReports')),
actions: [
IconButton(
icon: const Icon(Icons.refresh),
onPressed: _loadReports,
)
],
),
body: _loading
? const Center(child: CircularProgressIndicator())
: _reports.isEmpty
? Center(child: Text(I18n.t('map.noReports')))
: RefreshIndicator(
onRefresh: _loadReports,
child: ListView.builder(
padding: const EdgeInsets.symmetric(vertical: 8),
itemCount: _reports.length,
itemBuilder: (context, index) {
final r = _reports[index];
return ReportCard(
report: r,
onView: () => _onViewReport(r),
onDeleted: _onDeleted,
onUpdated: _onUpdated,
);
},
),
),
);
}
}

View File

@@ -0,0 +1,166 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import '../../l10n/i18n.dart';
import '../../services/location_service.dart';
import '../../services/mock_ai.dart';
import '../../models/report.dart';
import '../../models/enums.dart';
import 'review_screen.dart';
class CaptureScreen extends StatefulWidget {
const CaptureScreen({super.key});
@override
State<CaptureScreen> createState() => _CaptureScreenState();
}
class _CaptureScreenState extends State<CaptureScreen> {
final ImagePicker _picker = ImagePicker();
bool _isLoading = false;
Future<void> _pickImage(ImageSource source) async {
setState(() {
_isLoading = true;
});
try {
final XFile? image = await _picker.pickImage(
source: source,
maxWidth: 1920,
maxHeight: 1080,
imageQuality: 85,
);
if (image != null) {
await _processImage(image, source);
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Error picking image: $e')),
);
}
} finally {
if (mounted) {
setState(() {
_isLoading = false;
});
}
}
}
Future<void> _processImage(XFile image, ImageSource source) async {
try {
// Get current position (Geolocator.Position)
final position = await LocationService.getCurrentPosition();
if (position == null) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Unable to get location. Please try again.')),
);
}
return;
}
// Convert Position -> LocationData (app model)
final locationData = LocationService.positionToLocationData(position);
// Generate AI suggestion (seeded deterministic)
final aiSuggestion = MockAIService.generateSuggestion(
id: DateTime.now().millisecondsSinceEpoch.toString(),
createdAt: DateTime.now().toIso8601String(),
lat: locationData.lat,
lng: locationData.lng,
photoSizeBytes: await image.length(),
);
// Create report with AI suggestion
final report = Report(
id: DateTime.now().millisecondsSinceEpoch.toString(),
category: aiSuggestion.category,
severity: aiSuggestion.severity,
status: Status.submitted,
photoPath: image.path,
base64Photo: null, // Will be set on Web
location: locationData,
createdAt: DateTime.now().toIso8601String(),
updatedAt: DateTime.now().toIso8601String(),
deviceId: 'device_${DateTime.now().millisecondsSinceEpoch}',
notes: null,
address: null,
source: source == ImageSource.camera ? 'camera' : 'gallery',
editable: true,
deletable: true,
aiSuggestion: aiSuggestion,
schemaVersion: 1,
);
if (mounted) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ReviewScreen(report: report, imageFile: File(image.path)),
),
);
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Error processing image: $e')),
);
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(I18n.t('nav.report')),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Take a photo of the issue',
style: Theme.of(context).textTheme.headlineSmall,
textAlign: TextAlign.center,
),
const SizedBox(height: 32),
if (_isLoading)
const CircularProgressIndicator()
else ...[
SizedBox(
width: double.infinity,
child: ElevatedButton.icon(
onPressed: () => _pickImage(ImageSource.camera),
icon: const Icon(Icons.camera_alt),
label: Text(I18n.t('btn.camera')),
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 16),
),
),
),
const SizedBox(height: 16),
SizedBox(
width: double.infinity,
child: OutlinedButton.icon(
onPressed: () => _pickImage(ImageSource.gallery),
icon: const Icon(Icons.photo_library),
label: Text(I18n.t('btn.gallery')),
style: OutlinedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 16),
),
),
),
],
],
),
),
);
}
}

View File

@@ -0,0 +1,289 @@
import 'dart:io';
import 'package:flutter/material.dart';
import '../../l10n/i18n.dart';
import '../../models/report.dart';
import '../../models/enums.dart';
import '../../services/storage.dart';
class ReviewScreen extends StatefulWidget {
final Report report;
final File imageFile;
const ReviewScreen({
super.key,
required this.report,
required this.imageFile,
});
@override
State<ReviewScreen> createState() => _ReviewScreenState();
}
class _ReviewScreenState extends State<ReviewScreen> {
late Category _selectedCategory;
late Severity _selectedSeverity;
late TextEditingController _notesController;
bool _isSubmitting = false;
@override
void initState() {
super.initState();
_selectedCategory = widget.report.category;
_selectedSeverity = widget.report.severity;
_notesController = TextEditingController(text: widget.report.notes ?? '');
}
@override
void dispose() {
_notesController.dispose();
super.dispose();
}
Future<void> _submitReport() async {
setState(() {
_isSubmitting = true;
});
try {
// Update report with user selections
final updatedReport = widget.report.copyWith(
category: _selectedCategory,
severity: _selectedSeverity,
notes: _notesController.text.isEmpty ? null : _notesController.text,
updatedAt: DateTime.now().toIso8601String(),
);
// Save to storage
await StorageService.saveReport(updatedReport);
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(I18n.t('toast.reportSaved'))),
);
// Navigate back to main screen
Navigator.of(context).popUntil((route) => route.isFirst);
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Error saving report: $e')),
);
}
} finally {
if (mounted) {
setState(() {
_isSubmitting = false;
});
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(I18n.t('btn.submit')),
actions: [
TextButton(
onPressed: _isSubmitting ? null : _submitReport,
child: _isSubmitting
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(strokeWidth: 2),
)
: Text(I18n.t('btn.submit')),
),
],
),
body: SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Image preview
Container(
height: 200,
width: double.infinity,
decoration: BoxDecoration(
border: Border.all(color: Colors.grey),
borderRadius: BorderRadius.circular(8),
),
child: Image.file(
widget.imageFile,
fit: BoxFit.cover,
),
),
const SizedBox(height: 24),
// AI Suggestion Card
Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Icon(
Icons.lightbulb,
color: Theme.of(context).primaryColor,
),
const SizedBox(width: 8),
Text(
I18n.t('label.aiSuggestion'),
style: Theme.of(context).textTheme.titleMedium,
),
],
),
const SizedBox(height: 12),
Row(
children: [
_buildSuggestionChip(
widget.report.aiSuggestion.category.displayName,
Colors.blue.shade100,
),
const SizedBox(width: 8),
_buildSuggestionChip(
widget.report.aiSuggestion.severity.displayName,
_getSeverityColor(widget.report.aiSuggestion.severity),
),
const SizedBox(width: 8),
_buildSuggestionChip(
'${(widget.report.aiSuggestion.confidence * 100).round()}%',
Colors.grey.shade100,
),
],
),
const SizedBox(height: 12),
Row(
children: [
Expanded(
child: ElevatedButton(
onPressed: () {
setState(() {
_selectedCategory = widget.report.aiSuggestion.category;
_selectedSeverity = widget.report.aiSuggestion.severity;
});
},
child: Text(I18n.t('btn.useSuggestion')),
),
),
const SizedBox(width: 8),
Expanded(
child: OutlinedButton(
onPressed: () {
// Keep manual selections
},
child: Text(I18n.t('btn.keepManual')),
),
),
],
),
],
),
),
),
const SizedBox(height: 24),
// Category Selection
Text(
I18n.t('label.category'),
style: Theme.of(context).textTheme.titleMedium,
),
const SizedBox(height: 8),
Wrap(
spacing: 8,
children: Category.values.map((category) {
return ChoiceChip(
label: Text(category.displayName),
selected: _selectedCategory == category,
onSelected: (selected) {
if (selected) {
setState(() {
_selectedCategory = category;
});
}
},
);
}).toList(),
),
const SizedBox(height: 24),
// Severity Selection
Text(
I18n.t('label.severity'),
style: Theme.of(context).textTheme.titleMedium,
),
const SizedBox(height: 8),
Wrap(
spacing: 8,
children: Severity.values.map((severity) {
return ChoiceChip(
label: Text(severity.displayName),
selected: _selectedSeverity == severity,
onSelected: (selected) {
if (selected) {
setState(() {
_selectedSeverity = severity;
});
}
},
);
}).toList(),
),
const SizedBox(height: 24),
// Notes
Text(
I18n.t('label.notes'),
style: Theme.of(context).textTheme.titleMedium,
),
const SizedBox(height: 8),
TextField(
controller: _notesController,
decoration: InputDecoration(
hintText: 'Add any additional notes...',
border: const OutlineInputBorder(),
),
maxLines: 3,
),
const SizedBox(height: 24),
// Location info
Text(
I18n.t('label.location'),
style: Theme.of(context).textTheme.titleMedium,
),
const SizedBox(height: 8),
Text(
'Lat: ${widget.report.location.lat.toStringAsFixed(6)}, '
'Lng: ${widget.report.location.lng.toStringAsFixed(6)}',
),
if (widget.report.location.accuracy != null)
Text('Accuracy: ${widget.report.location.accuracy!.toStringAsFixed(1)}m'),
],
),
),
);
}
Widget _buildSuggestionChip(String label, Color color) {
return Chip(
label: Text(label),
backgroundColor: color,
);
}
Color _getSeverityColor(Severity severity) {
switch (severity) {
case Severity.high:
return Colors.red.shade100;
case Severity.medium:
return Colors.orange.shade100;
case Severity.low:
return Colors.green.shade100;
}
}
}

View File

@@ -0,0 +1,134 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../l10n/i18n.dart';
import '../../l10n/locale_provider.dart';
import '../../services/storage.dart';
class SettingsScreen extends StatefulWidget {
const SettingsScreen({super.key});
@override
State<SettingsScreen> createState() => _SettingsScreenState();
}
class _SettingsScreenState extends State<SettingsScreen> {
StorageStats? _stats;
bool _loadingStats = true;
bool _clearing = false;
@override
void initState() {
super.initState();
_loadStats();
}
Future<void> _loadStats() async {
setState(() {
_loadingStats = true;
});
final stats = await StorageService.getStorageStats();
if (mounted) {
setState(() {
_stats = stats;
_loadingStats = false;
});
}
}
Future<void> _confirmAndClearAll(BuildContext context) async {
final confirmed = await showDialog<bool>(
context: context,
builder: (ctx) => AlertDialog(
title: Text(I18n.t('confirm.clearData.title')),
content: Text(I18n.t('confirm.clearData.message')),
actions: [
TextButton(onPressed: () => Navigator.pop(ctx, false), child: Text(I18n.t('btn.no'))),
TextButton(onPressed: () => Navigator.pop(ctx, true), child: Text(I18n.t('btn.yes'))),
],
),
);
if (confirmed == true) {
setState(() {
_clearing = true;
});
final ok = await StorageService.clearAllReports();
setState(() {
_clearing = false;
});
if (ok) {
await _loadStats();
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(I18n.t('toast.storageCleared'))));
}
} else {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Failed to clear data')));
}
}
}
}
@override
Widget build(BuildContext context) {
final localeProvider = Provider.of<LocaleProvider>(context);
final isEnglish = localeProvider.isEnglish;
return Scaffold(
appBar: AppBar(
title: Text(I18n.t('nav.settings')),
),
body: ListView(
padding: const EdgeInsets.all(16),
children: [
ListTile(
title: Text(I18n.t('settings.language')),
subtitle: Text(isEnglish ? I18n.t('lang.en') : I18n.t('lang.ms')),
trailing: Switch(
value: isEnglish,
onChanged: (v) async {
// toggle language and reload translations
if (v) {
await localeProvider.setEnglish();
} else {
await localeProvider.setMalay();
}
await I18n.init(localeProvider.locale);
// Force rebuild
setState(() {});
},
),
),
const Divider(),
ListTile(
title: Text(I18n.t('settings.theme')),
subtitle: Text(I18n.t('settings.theme.light')),
trailing: const Icon(Icons.light_mode),
enabled: false,
),
const Divider(),
ListTile(
title: Text(I18n.t('settings.diagnostics')),
subtitle: _loadingStats
? const Text('Loading...')
: Text('${I18n.t('toast.reportSaved')}: ${_stats?.reportCount ?? 0}${_stats?.formattedPhotoSize ?? "0 B"}'),
),
const SizedBox(height: 8),
ElevatedButton.icon(
onPressed: _clearing ? null : () => _confirmAndClearAll(context),
icon: const Icon(Icons.delete_forever),
label: _clearing ? const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2)) : Text(I18n.t('btn.clearAll')),
style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
),
const SizedBox(height: 16),
Text('App', style: Theme.of(context).textTheme.titleMedium),
const SizedBox(height: 8),
ListTile(
title: Text(I18n.t('app.name')),
subtitle: Text('v1.0.0'),
),
],
),
);
}
}

View File

@@ -0,0 +1,202 @@
import 'package:flutter/foundation.dart';
import 'package:geolocator/geolocator.dart';
import '../models/report.dart';
/// Service for handling location operations and permissions
class LocationService {
/// Check if location services are enabled
static Future<bool> isLocationServiceEnabled() async {
try {
return await Geolocator.isLocationServiceEnabled();
} catch (e) {
print('Error checking location service: $e');
return false;
}
}
/// Check location permissions
static Future<LocationPermission> checkPermission() async {
try {
return await Geolocator.checkPermission();
} catch (e) {
print('Error checking location permission: $e');
return LocationPermission.denied;
}
}
/// Request location permissions
static Future<LocationPermission> requestPermission() async {
try {
return await Geolocator.requestPermission();
} catch (e) {
print('Error requesting location permission: $e');
return LocationPermission.denied;
}
}
/// Get current position with high accuracy
static Future<Position?> getCurrentPosition() async {
try {
// Check if location services are enabled
final serviceEnabled = await isLocationServiceEnabled();
if (!serviceEnabled) {
print('Location services are disabled');
return null;
}
// Check permissions
var permission = await checkPermission();
if (permission == LocationPermission.denied) {
permission = await requestPermission();
if (permission == LocationPermission.denied) {
print('Location permission denied');
return null;
}
}
if (permission == LocationPermission.deniedForever) {
print('Location permission permanently denied');
return null;
}
// Get current position
return await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high,
timeLimit: const Duration(seconds: 30),
);
} catch (e) {
print('Error getting current position: $e');
return null;
}
}
/// Get current position with best available accuracy
static Future<Position?> getBestAvailablePosition() async {
try {
// Check if location services are enabled
final serviceEnabled = await isLocationServiceEnabled();
if (!serviceEnabled) {
print('Location services are disabled');
return null;
}
// Check permissions
var permission = await checkPermission();
if (permission == LocationPermission.denied) {
permission = await requestPermission();
if (permission == LocationPermission.denied) {
print('Location permission denied');
return null;
}
}
if (permission == LocationPermission.deniedForever) {
print('Location permission permanently denied');
return null;
}
// Try high accuracy first, fallback to medium if it takes too long
try {
return await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high,
timeLimit: const Duration(seconds: 15),
);
} catch (e) {
print('High accuracy failed, trying medium accuracy: $e');
return await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.medium,
timeLimit: const Duration(seconds: 10),
);
}
} catch (e) {
print('Error getting best available position: $e');
return null;
}
}
/// Convert Position to LocationData
static LocationData positionToLocationData(Position position) {
return LocationData(
lat: position.latitude,
lng: position.longitude,
accuracy: position.accuracy,
);
}
/// Get location accuracy description
static String getAccuracyDescription(double? accuracy) {
if (accuracy == null) return 'Unknown';
if (accuracy <= 3) {
return 'Very High';
} else if (accuracy <= 10) {
return 'High';
} else if (accuracy <= 50) {
return 'Medium';
} else if (accuracy <= 100) {
return 'Low';
} else {
return 'Very Low';
}
}
/// Check if location accuracy is good enough for reporting
static bool isAccuracyGoodForReporting(double? accuracy) {
if (accuracy == null) return false;
return accuracy <= 50; // Within 50 meters is acceptable
}
/// Get user-friendly location permission status message
static String getPermissionStatusMessage(LocationPermission permission) {
switch (permission) {
case LocationPermission.denied:
return 'Location permission denied. Please enable location access to attach GPS coordinates to your reports.';
case LocationPermission.deniedForever:
return 'Location permission permanently denied. Please enable location access in your device settings to use this feature.';
case LocationPermission.whileInUse:
case LocationPermission.always:
return 'Location permission granted.';
case LocationPermission.unableToDetermine:
return 'Unable to determine location permission status.';
}
}
/// Open device location settings
static Future<bool> openLocationSettings() async {
try {
return await Geolocator.openLocationSettings();
} catch (e) {
print('Error opening location settings: $e');
return false;
}
}
/// Calculate distance between two points in meters
static double calculateDistance(LocationData point1, LocationData point2) {
return Geolocator.distanceBetween(
point1.lat,
point1.lng,
point2.lat,
point2.lng,
);
}
/// Get address from coordinates (placeholder - would need geocoding service)
static Future<String?> getAddressFromCoordinates(double lat, double lng) async {
// This is a placeholder implementation
// In a real app, you would use a geocoding service like Google Maps API
// or OpenStreetMap Nominatim API
return null;
}
/// Validate location data
static bool isValidLocation(LocationData location) {
final acc = location.accuracy;
return location.lat >= -90 &&
location.lat <= 90 &&
location.lng >= -180 &&
location.lng <= 180 &&
acc != null &&
acc >= 0;
}
}

116
lib/services/mock_ai.dart Normal file
View File

@@ -0,0 +1,116 @@
import 'dart:math';
import 'package:flutter/foundation.dart' hide Category;
import '../models/enums.dart';
import '../models/report.dart';
/// Service for generating deterministic AI suggestions for reports
class MockAIService {
/// Generate a deterministic seed based on report parameters
static int _generateSeed(String id, String createdAt, double lat, double lng, int? photoSizeBytes) {
final combined = '$id$createdAt$lat$lng${photoSizeBytes ?? 0}';
var hash = 0;
for (var i = 0; i < combined.length; i++) {
hash = ((hash << 5) - hash) + combined.codeUnitAt(i);
hash = hash & hash; // Convert to 32-bit integer
}
return hash.abs();
}
/// Generate AI suggestion for a report
static AISuggestion generateSuggestion({
required String id,
required String createdAt,
required double lat,
required double lng,
int? photoSizeBytes,
}) {
final seed = _generateSeed(id, createdAt, lat, lng, photoSizeBytes);
final random = Random(seed);
// Category selection with weighted probabilities
final categoryWeights = {
Category.pothole: 0.35,
Category.trash: 0.25,
Category.streetlight: 0.15,
Category.signage: 0.10,
Category.drainage: 0.10,
Category.other: 0.05,
};
// Apply heuristics based on image dimensions (if available)
final aspectRatio = photoSizeBytes != null ? (random.nextDouble() * 2) : 1.0;
if (aspectRatio > 1.2) {
// Wide image - likely signage
categoryWeights[Category.signage] = categoryWeights[Category.signage]! * 2;
categoryWeights[Category.pothole] = categoryWeights[Category.pothole]! * 0.5;
}
// Select category based on weights
final categoryRand = random.nextDouble();
double cumulative = 0.0;
Category selectedCategory = Category.pothole;
for (final entry in categoryWeights.entries) {
cumulative += entry.value;
if (categoryRand <= cumulative) {
selectedCategory = entry.key;
break;
}
}
// Severity selection with weighted probabilities
final severityWeights = {
Severity.medium: 0.45,
Severity.high: 0.30,
Severity.low: 0.25,
};
// Apply location accuracy heuristic
final accuracy = random.nextDouble() * 50; // Simulate accuracy 0-50m
final isNight = random.nextBool(); // Simulate night time
if (accuracy <= 10 && isNight) {
// High accuracy at night - bump high severity
severityWeights[Severity.high] = severityWeights[Severity.high]! * 1.5;
severityWeights[Severity.medium] = severityWeights[Severity.medium]! * 0.8;
}
// Select severity based on weights
final severityRand = random.nextDouble();
cumulative = 0.0;
Severity selectedSeverity = Severity.medium;
for (final entry in severityWeights.entries) {
cumulative += entry.value;
if (severityRand <= cumulative) {
selectedSeverity = entry.key;
break;
}
}
// Generate confidence score (0.6 - 0.9)
final confidence = 0.6 + (random.nextDouble() * 0.3);
return AISuggestion(
category: selectedCategory,
severity: selectedSeverity,
confidence: confidence,
);
}
/// Check if the AI suggestion is reliable enough to use
static bool isSuggestionReliable(AISuggestion suggestion) {
return suggestion.confidence >= 0.7;
}
/// Get confidence level description
static String getConfidenceDescription(double confidence) {
if (confidence >= 0.8) {
return 'High confidence';
} else if (confidence >= 0.7) {
return 'Medium confidence';
} else {
return 'Low confidence';
}
}
}

231
lib/services/storage.dart Normal file
View File

@@ -0,0 +1,231 @@
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:path_provider/path_provider.dart';
import '../models/report.dart';
/// Service for persisting reports and managing local storage
class StorageService {
static const String _reportsKey = 'reports_v1';
/// Get all reports from storage
static Future<List<Report>> getReports() async {
try {
final prefs = await SharedPreferences.getInstance();
final reportsJson = prefs.getString(_reportsKey);
if (reportsJson == null || reportsJson.isEmpty) {
return [];
}
final List<dynamic> reportsList = json.decode(reportsJson);
return reportsList.map((json) => Report.fromJson(json)).toList();
} catch (e) {
print('Error loading reports: $e');
return [];
}
}
/// Save a single report to storage
static Future<bool> saveReport(Report report) async {
try {
final reports = await getReports();
final existingIndex = reports.indexWhere((r) => r.id == report.id);
if (existingIndex >= 0) {
reports[existingIndex] = report;
} else {
reports.add(report);
}
return await _saveReportsList(reports);
} catch (e) {
print('Error saving report: $e');
return false;
}
}
/// Delete a report from storage
static Future<bool> deleteReport(String reportId) async {
try {
final reports = await getReports();
final updatedReports = reports.where((r) => r.id != reportId).toList();
// Delete photo file if it exists
if (kIsWeb) {
// On web, base64 is stored in memory, no file to delete
} else {
await _deletePhotoFile(reportId);
}
return await _saveReportsList(updatedReports);
} catch (e) {
print('Error deleting report: $e');
return false;
}
}
/// Clear all reports from storage
static Future<bool> clearAllReports() async {
try {
final prefs = await SharedPreferences.getInstance();
await prefs.remove(_reportsKey);
// Delete all photo files
if (!kIsWeb) {
await _deleteAllPhotoFiles();
}
return true;
} catch (e) {
print('Error clearing reports: $e');
return false;
}
}
/// Save reports list to SharedPreferences
static Future<bool> _saveReportsList(List<Report> reports) async {
try {
final prefs = await SharedPreferences.getInstance();
// Convert reports to JSON, excluding photo data for mobile
final reportsForStorage = reports.map((report) {
final json = report.toJson();
if (!kIsWeb) {
// On mobile, remove base64Photo to save space
json.remove('base64Photo');
}
return json;
}).toList();
final reportsJson = json.encode(reportsForStorage);
return await prefs.setString(_reportsKey, reportsJson);
} catch (e) {
print('Error saving reports list: $e');
return false;
}
}
/// Get the photo file for a report
static Future<File?> getPhotoFile(String reportId) async {
if (kIsWeb) return null;
try {
final appDir = await getApplicationDocumentsDirectory();
final photoFile = File('${appDir.path}/$reportId.jpg');
if (await photoFile.exists()) {
return photoFile;
}
return null;
} catch (e) {
print('Error getting photo file: $e');
return null;
}
}
/// Save photo file for a report
static Future<bool> savePhotoFile(String reportId, List<int> photoBytes) async {
if (kIsWeb) return false;
try {
final appDir = await getApplicationDocumentsDirectory();
final photoFile = File('${appDir.path}/$reportId.jpg');
await photoFile.writeAsBytes(photoBytes);
return true;
} catch (e) {
print('Error saving photo file: $e');
return false;
}
}
/// Delete photo file for a report
static Future<bool> _deletePhotoFile(String reportId) async {
if (kIsWeb) return true;
try {
final appDir = await getApplicationDocumentsDirectory();
final photoFile = File('${appDir.path}/$reportId.jpg');
if (await photoFile.exists()) {
await photoFile.delete();
}
return true;
} catch (e) {
print('Error deleting photo file: $e');
return false;
}
}
/// Delete all photo files
static Future<void> _deleteAllPhotoFiles() async {
if (kIsWeb) return;
try {
final appDir = await getApplicationDocumentsDirectory();
final reports = await getReports();
for (final report in reports) {
final photoFile = File('${appDir.path}/${report.id}.jpg');
if (await photoFile.exists()) {
await photoFile.delete();
}
}
} catch (e) {
print('Error deleting all photo files: $e');
}
}
/// Get storage statistics
static Future<StorageStats> getStorageStats() async {
try {
final reports = await getReports();
int photoFilesSize = 0;
if (!kIsWeb) {
final appDir = await getApplicationDocumentsDirectory();
final reportsDir = Directory(appDir.path);
if (await reportsDir.exists()) {
final files = reportsDir.listSync().whereType<File>();
photoFilesSize = files
.where((file) => file.path.endsWith('.jpg'))
.fold(0, (sum, file) => sum + file.lengthSync());
}
}
return StorageStats(
reportCount: reports.length,
photoFilesSize: photoFilesSize,
);
} catch (e) {
print('Error getting storage stats: $e');
return StorageStats(reportCount: 0, photoFilesSize: 0);
}
}
}
/// Storage statistics model
class StorageStats {
final int reportCount;
final int photoFilesSize; // in bytes
const StorageStats({
required this.reportCount,
required this.photoFilesSize,
});
String get formattedPhotoSize {
const units = ['B', 'KB', 'MB', 'GB'];
double size = photoFilesSize.toDouble();
int unitIndex = 0;
while (size >= 1024 && unitIndex < units.length - 1) {
size /= 1024;
unitIndex++;
}
return '${size.toStringAsFixed(1)} ${units[unitIndex]}';
}
}

View File

@@ -0,0 +1,136 @@
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import '../models/report.dart';
import '../services/storage.dart';
import 'severity_badge.dart';
import 'status_badge.dart';
import '../l10n/i18n.dart';
class ReportCard extends StatelessWidget {
final Report report;
final VoidCallback? onView;
final VoidCallback? onDeleted;
final ValueChanged<Report>? onUpdated;
const ReportCard({
super.key,
required this.report,
this.onView,
this.onDeleted,
this.onUpdated,
});
Widget _buildThumbnail() {
if (kIsWeb && report.base64Photo != null) {
try {
final bytes = base64Decode(report.base64Photo!);
return ClipRRect(
borderRadius: BorderRadius.circular(8),
child: Image.memory(bytes, width: 72, height: 72, fit: BoxFit.cover),
);
} catch (_) {}
} else if (report.photoPath != null) {
final file = File(report.photoPath!);
return ClipRRect(
borderRadius: BorderRadius.circular(8),
child: Image.file(file, width: 72, height: 72, fit: BoxFit.cover),
);
}
return Container(
width: 72,
height: 72,
decoration: BoxDecoration(
color: Colors.grey.shade200,
borderRadius: BorderRadius.circular(8),
),
child: Icon(Icons.image, color: Colors.grey.shade600),
);
}
String _formatTime(String iso) {
try {
final dt = DateTime.parse(iso).toLocal();
return '${dt.year}-${dt.month.toString().padLeft(2,'0')}-${dt.day.toString().padLeft(2,'0')} ${dt.hour.toString().padLeft(2,'0')}:${dt.minute.toString().padLeft(2,'0')}';
} catch (_) {
return iso;
}
}
Future<void> _confirmAndDelete(BuildContext context) async {
final ok = await showDialog<bool>(
context: context,
builder: (ctx) => AlertDialog(
title: Text(I18n.t('confirm.deleteReport.title')),
content: Text(I18n.t('confirm.deleteReport.message')),
actions: [
TextButton(onPressed: () => Navigator.pop(ctx, false), child: Text(I18n.t('btn.no'))),
TextButton(onPressed: () => Navigator.pop(ctx, true), child: Text(I18n.t('btn.yes'))),
],
),
);
if (ok == true) {
final success = await StorageService.deleteReport(report.id);
if (success) {
if (onDeleted != null) onDeleted!();
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(I18n.t('toast.reportDeleted'))));
}
}
}
Future<void> _cycleStatus(BuildContext context) async {
final next = report.status.next;
final updated = report.copyWith(status: next, updatedAt: DateTime.now().toIso8601String());
final ok = await StorageService.saveReport(updated);
if (ok) {
if (onUpdated != null) onUpdated!(updated);
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(I18n.t('btn.changeStatus'))));
}
}
@override
Widget build(BuildContext context) {
return Card(
margin: const EdgeInsets.symmetric(vertical: 8, horizontal: 12),
child: ListTile(
leading: _buildThumbnail(),
title: Text(report.category.displayName),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(height: 6),
Row(
children: [
SeverityBadge(severity: report.severity, small: true),
const SizedBox(width: 8),
StatusBadge(status: report.status),
const SizedBox(width: 8),
Text(_formatTime(report.createdAt), style: TextStyle(fontSize: 12, color: Colors.grey.shade600)),
],
),
],
),
isThreeLine: true,
trailing: PopupMenuButton<int>(
onSelected: (v) async {
if (v == 0) {
if (onView != null) onView!();
} else if (v == 1) {
await _cycleStatus(context);
} else if (v == 2) {
await _confirmAndDelete(context);
}
},
itemBuilder: (_) => [
PopupMenuItem(value: 0, child: Text(I18n.t('btn.view'))),
PopupMenuItem(value: 1, child: Text(I18n.t('btn.changeStatus'))),
PopupMenuItem(value: 2, child: Text(I18n.t('btn.delete'))),
],
),
),
);
}
}

View File

@@ -0,0 +1,25 @@
import 'package:flutter/material.dart';
import '../models/enums.dart';
class SeverityBadge extends StatelessWidget {
final Severity severity;
final bool small;
const SeverityBadge({super.key, required this.severity, this.small = false});
@override
Widget build(BuildContext context) {
final color = severity.color;
return Container(
padding: EdgeInsets.symmetric(horizontal: small ? 8 : 12, vertical: small ? 4 : 6),
decoration: BoxDecoration(
color: color.withOpacity(0.12),
borderRadius: BorderRadius.circular(12),
),
child: Text(
severity.displayName,
style: TextStyle(color: color, fontSize: small ? 12 : 14),
),
);
}
}

View File

@@ -0,0 +1,45 @@
import 'package:flutter/material.dart';
import '../models/enums.dart';
class StatusBadge extends StatelessWidget {
final Status status;
final bool small;
const StatusBadge({Key? key, required this.status, this.small = false}) : super(key: key);
@override
Widget build(BuildContext context) {
final color = status.color;
return Chip(
backgroundColor: color.withOpacity(0.12),
avatar: CircleAvatar(
backgroundColor: color,
radius: small ? 10 : 12,
child: Icon(
_iconForStatus(status),
color: Colors.white,
size: small ? 12 : 14,
),
),
label: Text(
status.displayName,
style: TextStyle(
color: color,
fontSize: small ? 12 : 14,
),
),
padding: EdgeInsets.symmetric(horizontal: small ? 8 : 12, vertical: 0),
);
}
IconData _iconForStatus(Status s) {
switch (s) {
case Status.submitted:
return Icons.send;
case Status.inProgress:
return Icons.autorenew;
case Status.fixed:
return Icons.check;
}
}
}