Compare commits
15 Commits
32e25aeb07
...
codex/feat
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1349f35cfe | ||
|
|
c608b6c7df | ||
|
|
24b074ff4c | ||
|
|
5d8e1157b9 | ||
|
|
29c247abc1 | ||
|
|
e888b51875 | ||
|
|
6426d14336 | ||
|
|
b989981464 | ||
|
|
48c22d76d0 | ||
|
|
c607a52962 | ||
|
|
f5a02f581e | ||
|
|
1cbf9ca82c | ||
|
|
a9fb5695fb | ||
|
|
6f45c7b456 | ||
|
|
21941443ee |
@@ -1,4 +1,7 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<!-- BLE 기능 선언 (필수 아님으로 설정) -->
|
||||
<uses-feature android:name="android.hardware.bluetooth_le" android:required="false" />
|
||||
|
||||
<!-- 알림 권한 (Android 13+) -->
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<!-- 정확한 알람 권한 (Android 12+) -->
|
||||
|
||||
@@ -520,7 +520,7 @@ class _SplashScreenState extends State<SplashScreen> with TickerProviderStateMix
|
||||
left: 0,
|
||||
right: 0,
|
||||
child: Text(
|
||||
'© 2025. NatureBridgeAI. All rights reserved.',
|
||||
'© 2025. NatureBridgeAI & cclabs. All rights reserved.',
|
||||
style: AppTypography.caption(isDark).copyWith(
|
||||
color: (isDark ? AppColors.darkTextSecondary : AppColors.lightTextSecondary)
|
||||
.withOpacity(0.5),
|
||||
|
||||
@@ -54,6 +54,10 @@
|
||||
<string>맛집과의 거리 계산을 위해 위치 정보가 필요합니다.</string>
|
||||
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
|
||||
<string>맛집과의 거리 계산을 위해 위치 정보가 필요합니다.</string>
|
||||
<key>NSBluetoothAlwaysUsageDescription</key>
|
||||
<string>맛집 리스트를 다른 사용자와 공유하기 위해 블루투스 권한이 필요합니다.</string>
|
||||
<key>NSBluetoothPeripheralUsageDescription</key>
|
||||
<string>맛집 리스트를 다른 사용자로부터 받기 위해 블루투스 권한이 필요합니다.</string>
|
||||
<key>GADApplicationIdentifier</key>
|
||||
<string>$(GAD_APPLICATION_ID)</string>
|
||||
</dict>
|
||||
|
||||
@@ -4,7 +4,7 @@ class AppConstants {
|
||||
static const String appDescription = '점심 메뉴 추천 앱';
|
||||
static const String appVersion = '1.0.0';
|
||||
static const String appCopyright =
|
||||
'© 2025. NatureBridgeAI. All rights reserved.';
|
||||
'© 2025. NatureBridgeAI & cclabs. All rights reserved.';
|
||||
|
||||
// Animation Durations
|
||||
static const Duration splashAnimationDuration = Duration(seconds: 3);
|
||||
|
||||
55
lib/core/constants/app_dimensions.dart
Normal file
55
lib/core/constants/app_dimensions.dart
Normal file
@@ -0,0 +1,55 @@
|
||||
/// UI 관련 상수 정의
|
||||
/// 하드코딩된 패딩, 마진, 크기 값들을 중앙 집중화
|
||||
class AppDimensions {
|
||||
AppDimensions._();
|
||||
|
||||
// Padding & Margin
|
||||
static const double paddingXs = 4.0;
|
||||
static const double paddingSm = 8.0;
|
||||
static const double paddingMd = 12.0;
|
||||
static const double paddingDefault = 16.0;
|
||||
static const double paddingLg = 20.0;
|
||||
static const double paddingXl = 24.0;
|
||||
|
||||
// Border Radius
|
||||
static const double radiusSm = 8.0;
|
||||
static const double radiusMd = 12.0;
|
||||
static const double radiusLg = 16.0;
|
||||
static const double radiusXl = 20.0;
|
||||
static const double radiusRound = 999.0;
|
||||
|
||||
// Icon Sizes
|
||||
static const double iconSm = 16.0;
|
||||
static const double iconMd = 24.0;
|
||||
static const double iconLg = 32.0;
|
||||
static const double iconXl = 48.0;
|
||||
static const double iconXxl = 64.0;
|
||||
static const double iconHuge = 80.0;
|
||||
|
||||
// Card Sizes
|
||||
static const double cardIconSize = 48.0;
|
||||
static const double cardMinHeight = 80.0;
|
||||
|
||||
// Ad Settings
|
||||
static const int adInterval = 6; // 5리스트 후 1광고
|
||||
static const int adOffset = 5; // 광고 시작 위치
|
||||
static const double adHeightSmall = 100.0;
|
||||
static const double adHeightMedium = 320.0;
|
||||
|
||||
// Distance Settings
|
||||
static const double maxSearchDistance = 2000.0; // meters
|
||||
static const int distanceSliderDivisions = 19;
|
||||
|
||||
// List Settings
|
||||
static const double listItemSpacing = 8.0;
|
||||
static const double sectionSpacing = 16.0;
|
||||
|
||||
// Bottom Sheet
|
||||
static const double bottomSheetHandleWidth = 40.0;
|
||||
static const double bottomSheetHandleHeight = 4.0;
|
||||
|
||||
// Avatar/Profile
|
||||
static const double avatarSm = 32.0;
|
||||
static const double avatarMd = 48.0;
|
||||
static const double avatarLg = 64.0;
|
||||
}
|
||||
32
lib/core/constants/ble_constants.dart
Normal file
32
lib/core/constants/ble_constants.dart
Normal file
@@ -0,0 +1,32 @@
|
||||
/// BLE 공유 기능에서 사용하는 상수 정의
|
||||
class BleConstants {
|
||||
BleConstants._();
|
||||
|
||||
/// LunchPick 전용 서비스 UUID
|
||||
static const String serviceUuid = 'a1b2c3d4-e5f6-7890-abcd-ef1234567890';
|
||||
|
||||
/// 맛집 데이터 전송용 Characteristic UUID
|
||||
static const String dataCharacteristicUuid =
|
||||
'a1b2c3d4-e5f6-7890-abcd-ef1234567891';
|
||||
|
||||
/// 공유 코드 확인용 Characteristic UUID (매칭용)
|
||||
static const String codeCharacteristicUuid =
|
||||
'a1b2c3d4-e5f6-7890-abcd-ef1234567892';
|
||||
|
||||
/// 청크 사이즈 (MTU - 3, 보수적으로 설정)
|
||||
/// BLE 표준 MTU는 23바이트지만, 협상을 통해 더 커질 수 있음
|
||||
/// 안전하게 500바이트로 설정
|
||||
static const int chunkSize = 500;
|
||||
|
||||
/// 광고 이름 prefix
|
||||
static const String advertiseNamePrefix = 'LP-';
|
||||
|
||||
/// 스캔 타임아웃 (초)
|
||||
static const int scanTimeoutSeconds = 10;
|
||||
|
||||
/// 연결 타임아웃 (초)
|
||||
static const int connectionTimeoutSeconds = 15;
|
||||
|
||||
/// 청크 전송 간 딜레이 (밀리초)
|
||||
static const int chunkDelayMs = 50;
|
||||
}
|
||||
@@ -1,89 +1,452 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:math';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:ble_peripheral/ble_peripheral.dart' as ble_peripheral;
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
|
||||
import 'package:lunchpick/core/constants/ble_constants.dart';
|
||||
import 'package:lunchpick/domain/entities/restaurant.dart';
|
||||
import 'package:lunchpick/domain/entities/share_device.dart';
|
||||
|
||||
/// 실제 Bluetooth 통신을 대체하는 간단한 모의(Mock) 서비스.
|
||||
/// BLE 기반 맛집 리스트 공유 서비스
|
||||
///
|
||||
/// - Receiver (공유받기): ble_peripheral 패키지로 GATT Server 역할
|
||||
/// - Sender (공유하기): flutter_blue_plus 패키지로 Central 역할
|
||||
class BluetoothService {
|
||||
// === Peripheral (Receiver) 관련 ===
|
||||
bool _isPeripheralInitialized = false;
|
||||
String? _currentShareCode;
|
||||
final _incomingDataController = StreamController<String>.broadcast();
|
||||
final Map<String, ShareDevice> _listeningDevices = {};
|
||||
final Random _random = Random();
|
||||
final _receivedChunks = <int, String>{};
|
||||
// ignore: unused_field - 디버깅 및 진행률 표시용
|
||||
int _expectedTotalChunks = 0;
|
||||
|
||||
// === Central (Sender) 관련 ===
|
||||
final List<ShareDevice> _discoveredDevices = [];
|
||||
StreamSubscription<List<ScanResult>>? _scanSubscription;
|
||||
BluetoothDevice? _connectedDevice;
|
||||
|
||||
// === 진행 상태 콜백 ===
|
||||
Function(int current, int total)? onSendProgress;
|
||||
Function(int current, int total)? onReceiveProgress;
|
||||
|
||||
/// 수신된 데이터 스트림
|
||||
Stream<String> get onDataReceived => _incomingDataController.stream;
|
||||
|
||||
/// 특정 코드로 수신 대기를 시작한다.
|
||||
Future<void> startListening(String code) async {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 300));
|
||||
stopListening();
|
||||
final shareDevice = ShareDevice(
|
||||
code: code,
|
||||
deviceId: 'LP-${_random.nextInt(900000) + 100000}',
|
||||
discoveredAt: DateTime.now(),
|
||||
);
|
||||
_listeningDevices[code] = shareDevice;
|
||||
}
|
||||
/// 현재 광고 중인 공유 코드
|
||||
String? get currentShareCode => _currentShareCode;
|
||||
|
||||
/// 더 이상 수신 대기하지 않는다.
|
||||
void stopListening() {
|
||||
if (_listeningDevices.isEmpty) return;
|
||||
final codes = List<String>.from(_listeningDevices.keys);
|
||||
for (final code in codes) {
|
||||
_listeningDevices.remove(code);
|
||||
/// BLE 지원 여부 확인
|
||||
Future<bool> get isSupported async {
|
||||
if (!Platform.isAndroid && !Platform.isIOS) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
return await FlutterBluePlus.isSupported;
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// 현재 주변에서 수신 대기 중인 기기 목록을 반환한다.
|
||||
Future<List<ShareDevice>> scanNearbyDevices() async {
|
||||
await Future<void>.delayed(const Duration(seconds: 1));
|
||||
return _listeningDevices.values.toList();
|
||||
/// Bluetooth 어댑터 상태 확인
|
||||
Future<bool> get isBluetoothOn async {
|
||||
try {
|
||||
final state = await FlutterBluePlus.adapterState.first;
|
||||
return state == BluetoothAdapterState.on;
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// 대상 코드로 맛집 리스트를 전송한다. 실제 BT 대신 JSON 문자열을 브로드캐스트한다.
|
||||
// =========================================================================
|
||||
// Receiver (Peripheral) 메서드 - ble_peripheral 사용
|
||||
// =========================================================================
|
||||
|
||||
/// Peripheral 초기화
|
||||
Future<void> initializePeripheral() async {
|
||||
if (_isPeripheralInitialized) return;
|
||||
if (!Platform.isAndroid && !Platform.isIOS) {
|
||||
throw UnsupportedError('BLE Peripheral은 Android/iOS에서만 지원됩니다.');
|
||||
}
|
||||
|
||||
try {
|
||||
await ble_peripheral.BlePeripheral.initialize();
|
||||
_setupWriteCallback();
|
||||
_isPeripheralInitialized = true;
|
||||
debugPrint('[BLE] Peripheral 초기화 완료');
|
||||
} catch (e) {
|
||||
debugPrint('[BLE] Peripheral 초기화 실패: $e');
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
/// 공유 코드로 수신 대기 시작
|
||||
Future<void> startListening(String code) async {
|
||||
await initializePeripheral();
|
||||
|
||||
// 기존 서비스 정리
|
||||
await _cleanupPeripheral();
|
||||
|
||||
_currentShareCode = code;
|
||||
_receivedChunks.clear();
|
||||
_expectedTotalChunks = 0;
|
||||
|
||||
try {
|
||||
// GATT 서비스 추가
|
||||
await ble_peripheral.BlePeripheral.addService(
|
||||
ble_peripheral.BleService(
|
||||
uuid: BleConstants.serviceUuid,
|
||||
primary: true,
|
||||
characteristics: [
|
||||
// 데이터 수신용 Characteristic (writable)
|
||||
ble_peripheral.BleCharacteristic(
|
||||
uuid: BleConstants.dataCharacteristicUuid,
|
||||
properties: [
|
||||
ble_peripheral.CharacteristicProperties.write.index,
|
||||
ble_peripheral.CharacteristicProperties.writeWithoutResponse.index,
|
||||
],
|
||||
permissions: [ble_peripheral.AttributePermissions.writeable.index],
|
||||
value: null,
|
||||
),
|
||||
// 공유 코드 확인용 Characteristic (readable)
|
||||
ble_peripheral.BleCharacteristic(
|
||||
uuid: BleConstants.codeCharacteristicUuid,
|
||||
properties: [ble_peripheral.CharacteristicProperties.read.index],
|
||||
permissions: [ble_peripheral.AttributePermissions.readable.index],
|
||||
value: Uint8List.fromList(utf8.encode(code)),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
// 광고 시작
|
||||
await ble_peripheral.BlePeripheral.startAdvertising(
|
||||
services: [BleConstants.serviceUuid],
|
||||
localName: '${BleConstants.advertiseNamePrefix}$code',
|
||||
);
|
||||
|
||||
debugPrint('[BLE] 광고 시작: ${BleConstants.advertiseNamePrefix}$code');
|
||||
} catch (e) {
|
||||
debugPrint('[BLE] 광고 시작 실패: $e');
|
||||
_currentShareCode = null;
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
/// Write 콜백 설정
|
||||
void _setupWriteCallback() {
|
||||
ble_peripheral.BlePeripheral.setWriteRequestCallback((
|
||||
deviceId,
|
||||
characteristicId,
|
||||
offset,
|
||||
value,
|
||||
) {
|
||||
if (characteristicId.toLowerCase() ==
|
||||
BleConstants.dataCharacteristicUuid.toLowerCase()) {
|
||||
_handleReceivedChunk(value ?? Uint8List(0));
|
||||
}
|
||||
// null 반환 = 성공 (ble_peripheral 패키지 규약)
|
||||
return null;
|
||||
});
|
||||
|
||||
debugPrint('[BLE] Write 콜백 설정 완료');
|
||||
}
|
||||
|
||||
/// 수신된 청크 처리
|
||||
void _handleReceivedChunk(Uint8List data) {
|
||||
try {
|
||||
final decoded = utf8.decode(data);
|
||||
debugPrint('[BLE] 청크 수신: ${decoded.substring(0, decoded.length.clamp(0, 50))}...');
|
||||
|
||||
// 프로토콜: "CHUNK:index:total:data"
|
||||
if (decoded.startsWith('CHUNK:')) {
|
||||
final colonIndex1 = decoded.indexOf(':', 6);
|
||||
final colonIndex2 = decoded.indexOf(':', colonIndex1 + 1);
|
||||
|
||||
if (colonIndex1 == -1 || colonIndex2 == -1) {
|
||||
debugPrint('[BLE] 잘못된 청크 형식');
|
||||
return;
|
||||
}
|
||||
|
||||
final index = int.tryParse(decoded.substring(6, colonIndex1));
|
||||
final total = int.tryParse(decoded.substring(colonIndex1 + 1, colonIndex2));
|
||||
final chunkData = decoded.substring(colonIndex2 + 1);
|
||||
|
||||
if (index == null || total == null) {
|
||||
debugPrint('[BLE] 청크 인덱스/전체 파싱 실패');
|
||||
return;
|
||||
}
|
||||
|
||||
_expectedTotalChunks = total;
|
||||
_receivedChunks[index] = chunkData;
|
||||
|
||||
// 진행 상태 콜백
|
||||
onReceiveProgress?.call(_receivedChunks.length, total);
|
||||
|
||||
debugPrint('[BLE] 청크 $index/$total 수신 완료');
|
||||
|
||||
// 모든 청크 수신 완료
|
||||
if (_receivedChunks.length == total) {
|
||||
_assembleAndEmit();
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint('[BLE] 청크 처리 오류: $e');
|
||||
}
|
||||
}
|
||||
|
||||
/// 청크 조립 후 스트림으로 전송
|
||||
void _assembleAndEmit() {
|
||||
final sorted = _receivedChunks.entries.toList()
|
||||
..sort((a, b) => a.key.compareTo(b.key));
|
||||
final fullData = sorted.map((e) => e.value).join();
|
||||
|
||||
debugPrint('[BLE] 데이터 조립 완료: ${fullData.length} bytes');
|
||||
|
||||
_incomingDataController.add(fullData);
|
||||
_receivedChunks.clear();
|
||||
_expectedTotalChunks = 0;
|
||||
}
|
||||
|
||||
/// Peripheral 정리
|
||||
Future<void> _cleanupPeripheral() async {
|
||||
try {
|
||||
await ble_peripheral.BlePeripheral.stopAdvertising();
|
||||
await ble_peripheral.BlePeripheral.clearServices();
|
||||
} catch (e) {
|
||||
debugPrint('[BLE] Peripheral 정리 중 오류 (무시됨): $e');
|
||||
}
|
||||
}
|
||||
|
||||
/// 수신 대기 중지
|
||||
Future<void> stopListening() async {
|
||||
await _cleanupPeripheral();
|
||||
_currentShareCode = null;
|
||||
_receivedChunks.clear();
|
||||
_expectedTotalChunks = 0;
|
||||
debugPrint('[BLE] 광고 중지');
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Sender (Central) 메서드 - flutter_blue_plus 사용
|
||||
// =========================================================================
|
||||
|
||||
/// 주변 LunchPick 기기 스캔
|
||||
Future<List<ShareDevice>> scanNearbyDevices() async {
|
||||
_discoveredDevices.clear();
|
||||
|
||||
// Bluetooth 상태 확인
|
||||
if (!await isBluetoothOn) {
|
||||
throw Exception('블루투스가 꺼져 있습니다. 블루투스를 켜주세요.');
|
||||
}
|
||||
|
||||
debugPrint('[BLE] 스캔 시작...');
|
||||
|
||||
// 스캔 결과 리스닝
|
||||
_scanSubscription = FlutterBluePlus.scanResults.listen(
|
||||
(results) {
|
||||
for (final result in results) {
|
||||
_processScannedDevice(result);
|
||||
}
|
||||
},
|
||||
onError: (e) {
|
||||
debugPrint('[BLE] 스캔 오류: $e');
|
||||
},
|
||||
);
|
||||
|
||||
try {
|
||||
// 서비스 UUID로 필터링하여 스캔
|
||||
await FlutterBluePlus.startScan(
|
||||
withServices: [Guid(BleConstants.serviceUuid)],
|
||||
timeout: Duration(seconds: BleConstants.scanTimeoutSeconds),
|
||||
);
|
||||
|
||||
// 스캔 완료 대기
|
||||
await Future.delayed(
|
||||
Duration(seconds: BleConstants.scanTimeoutSeconds + 1),
|
||||
);
|
||||
} catch (e) {
|
||||
debugPrint('[BLE] 스캔 시작 오류: $e');
|
||||
} finally {
|
||||
await _scanSubscription?.cancel();
|
||||
_scanSubscription = null;
|
||||
}
|
||||
|
||||
debugPrint('[BLE] 스캔 완료: ${_discoveredDevices.length}개 기기 발견');
|
||||
return List.from(_discoveredDevices);
|
||||
}
|
||||
|
||||
/// 스캔된 디바이스 처리
|
||||
void _processScannedDevice(ScanResult result) {
|
||||
// 서비스 UUID 확인
|
||||
final hasService = result.advertisementData.serviceUuids.any(
|
||||
(uuid) =>
|
||||
uuid.toString().toLowerCase() ==
|
||||
BleConstants.serviceUuid.toLowerCase(),
|
||||
);
|
||||
|
||||
if (!hasService) return;
|
||||
|
||||
// 광고 이름에서 공유 코드 추출
|
||||
final name = result.advertisementData.advName;
|
||||
if (name.isEmpty) return;
|
||||
|
||||
final code = name.startsWith(BleConstants.advertiseNamePrefix)
|
||||
? name.substring(BleConstants.advertiseNamePrefix.length)
|
||||
: name;
|
||||
|
||||
// 중복 방지
|
||||
if (_discoveredDevices.any((d) => d.deviceId == result.device.remoteId.str)) {
|
||||
return;
|
||||
}
|
||||
|
||||
final device = ShareDevice(
|
||||
code: code,
|
||||
deviceId: result.device.remoteId.str,
|
||||
remoteId: result.device.remoteId.str,
|
||||
rssi: result.rssi,
|
||||
discoveredAt: DateTime.now(),
|
||||
bleDevice: result.device,
|
||||
);
|
||||
|
||||
_discoveredDevices.add(device);
|
||||
debugPrint('[BLE] 기기 발견: $code (RSSI: ${result.rssi})');
|
||||
}
|
||||
|
||||
/// 맛집 리스트 전송
|
||||
Future<void> sendRestaurantList(
|
||||
String targetCode,
|
||||
List<Restaurant> restaurants,
|
||||
) async {
|
||||
await Future<void>.delayed(const Duration(seconds: 1));
|
||||
if (!_listeningDevices.containsKey(targetCode)) {
|
||||
throw Exception('해당 코드를 찾을 수 없습니다.');
|
||||
// 대상 디바이스 찾기
|
||||
final targetDevice = _discoveredDevices.firstWhere(
|
||||
(d) => d.code == targetCode,
|
||||
orElse: () => throw Exception('대상 기기를 찾을 수 없습니다: $targetCode'),
|
||||
);
|
||||
|
||||
final bleDevice = targetDevice.bleDevice;
|
||||
if (bleDevice == null) {
|
||||
throw Exception('BLE 디바이스 정보가 없습니다.');
|
||||
}
|
||||
|
||||
final payload = jsonEncode(
|
||||
restaurants
|
||||
.map((restaurant) => _serializeRestaurant(restaurant))
|
||||
.toList(),
|
||||
debugPrint('[BLE] 연결 시작: $targetCode');
|
||||
|
||||
// 연결
|
||||
await bleDevice.connect(
|
||||
timeout: Duration(seconds: BleConstants.connectionTimeoutSeconds),
|
||||
);
|
||||
_incomingDataController.add(payload);
|
||||
_connectedDevice = bleDevice;
|
||||
|
||||
try {
|
||||
// 서비스 탐색
|
||||
debugPrint('[BLE] 서비스 탐색 중...');
|
||||
final services = await bleDevice.discoverServices();
|
||||
|
||||
final targetService = services.firstWhere(
|
||||
(s) =>
|
||||
s.uuid.toString().toLowerCase() ==
|
||||
BleConstants.serviceUuid.toLowerCase(),
|
||||
orElse: () => throw Exception('LunchPick 서비스를 찾을 수 없습니다.'),
|
||||
);
|
||||
|
||||
final dataCharacteristic = targetService.characteristics.firstWhere(
|
||||
(c) =>
|
||||
c.uuid.toString().toLowerCase() ==
|
||||
BleConstants.dataCharacteristicUuid.toLowerCase(),
|
||||
orElse: () => throw Exception('데이터 Characteristic을 찾을 수 없습니다.'),
|
||||
);
|
||||
|
||||
// JSON 직렬화
|
||||
final payload = jsonEncode(
|
||||
restaurants.map(_serializeRestaurant).toList(),
|
||||
);
|
||||
|
||||
debugPrint('[BLE] 전송 데이터 크기: ${payload.length} bytes');
|
||||
|
||||
// 청킹 및 전송
|
||||
final chunks = _splitIntoChunks(payload, BleConstants.chunkSize);
|
||||
debugPrint('[BLE] 청크 수: ${chunks.length}');
|
||||
|
||||
for (var i = 0; i < chunks.length; i++) {
|
||||
final chunkMessage = 'CHUNK:$i:${chunks.length}:${chunks[i]}';
|
||||
final data = utf8.encode(chunkMessage);
|
||||
|
||||
await dataCharacteristic.write(
|
||||
data,
|
||||
withoutResponse: false,
|
||||
);
|
||||
|
||||
// 진행 상태 콜백
|
||||
onSendProgress?.call(i + 1, chunks.length);
|
||||
|
||||
debugPrint('[BLE] 청크 ${i + 1}/${chunks.length} 전송 완료');
|
||||
|
||||
// 청크 간 딜레이
|
||||
if (i < chunks.length - 1) {
|
||||
await Future.delayed(
|
||||
Duration(milliseconds: BleConstants.chunkDelayMs),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
debugPrint('[BLE] 전송 완료!');
|
||||
} finally {
|
||||
// 연결 해제
|
||||
await bleDevice.disconnect();
|
||||
_connectedDevice = null;
|
||||
debugPrint('[BLE] 연결 해제');
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, dynamic> _serializeRestaurant(Restaurant restaurant) {
|
||||
return {
|
||||
'id': restaurant.id,
|
||||
'name': restaurant.name,
|
||||
'category': restaurant.category,
|
||||
'subCategory': restaurant.subCategory,
|
||||
'description': restaurant.description,
|
||||
'phoneNumber': restaurant.phoneNumber,
|
||||
'roadAddress': restaurant.roadAddress,
|
||||
'jibunAddress': restaurant.jibunAddress,
|
||||
'latitude': restaurant.latitude,
|
||||
'longitude': restaurant.longitude,
|
||||
'lastVisitDate': restaurant.lastVisitDate?.toIso8601String(),
|
||||
'source': restaurant.source.name,
|
||||
'createdAt': restaurant.createdAt.toIso8601String(),
|
||||
'updatedAt': restaurant.updatedAt.toIso8601String(),
|
||||
'naverPlaceId': restaurant.naverPlaceId,
|
||||
'naverUrl': restaurant.naverUrl,
|
||||
'businessHours': restaurant.businessHours,
|
||||
'lastVisited': restaurant.lastVisited?.toIso8601String(),
|
||||
'visitCount': restaurant.visitCount,
|
||||
};
|
||||
/// 문자열을 청크로 분할
|
||||
List<String> _splitIntoChunks(String data, int chunkSize) {
|
||||
final chunks = <String>[];
|
||||
for (var i = 0; i < data.length; i += chunkSize) {
|
||||
final end = (i + chunkSize > data.length) ? data.length : i + chunkSize;
|
||||
chunks.add(data.substring(i, end));
|
||||
}
|
||||
return chunks;
|
||||
}
|
||||
|
||||
/// Restaurant를 JSON Map으로 변환
|
||||
Map<String, dynamic> _serializeRestaurant(Restaurant r) => {
|
||||
'id': r.id,
|
||||
'name': r.name,
|
||||
'category': r.category,
|
||||
'subCategory': r.subCategory,
|
||||
'description': r.description,
|
||||
'phoneNumber': r.phoneNumber,
|
||||
'roadAddress': r.roadAddress,
|
||||
'jibunAddress': r.jibunAddress,
|
||||
'latitude': r.latitude,
|
||||
'longitude': r.longitude,
|
||||
'lastVisitDate': r.lastVisitDate?.toIso8601String(),
|
||||
'source': r.source.name,
|
||||
'createdAt': r.createdAt.toIso8601String(),
|
||||
'updatedAt': r.updatedAt.toIso8601String(),
|
||||
'naverPlaceId': r.naverPlaceId,
|
||||
'naverUrl': r.naverUrl,
|
||||
'businessHours': r.businessHours,
|
||||
'lastVisited': r.lastVisited?.toIso8601String(),
|
||||
'visitCount': r.visitCount,
|
||||
};
|
||||
|
||||
/// 스캔 중지
|
||||
Future<void> stopScan() async {
|
||||
await FlutterBluePlus.stopScan();
|
||||
await _scanSubscription?.cancel();
|
||||
_scanSubscription = null;
|
||||
_discoveredDevices.clear();
|
||||
debugPrint('[BLE] 스캔 중지');
|
||||
}
|
||||
|
||||
/// 리소스 정리
|
||||
void dispose() {
|
||||
_incomingDataController.close();
|
||||
_listeningDevices.clear();
|
||||
_scanSubscription?.cancel();
|
||||
_connectedDevice?.disconnect();
|
||||
_cleanupPeripheral();
|
||||
debugPrint('[BLE] BluetoothService disposed');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,8 +17,11 @@ class GeocodingService {
|
||||
Future<({double latitude, double longitude})?> geocode(String address) async {
|
||||
if (address.trim().isEmpty) return null;
|
||||
|
||||
// 주소 전처리: 상세 주소(층수, 상호명 등) 제거
|
||||
final cleanedAddress = _cleanAddress(address);
|
||||
|
||||
// 1차: VWorld 지오코딩 시도 (키가 존재할 때만)
|
||||
final vworldResult = await _geocodeWithVworld(address);
|
||||
final vworldResult = await _geocodeWithVworld(cleanedAddress);
|
||||
if (vworldResult != null) {
|
||||
return vworldResult;
|
||||
}
|
||||
@@ -26,7 +29,7 @@ class GeocodingService {
|
||||
// 2차: Nominatim (fallback)
|
||||
try {
|
||||
final uri = Uri.parse(
|
||||
'$_endpoint?format=json&limit=1&q=${Uri.encodeQueryComponent(address)}',
|
||||
'$_endpoint?format=json&limit=1&q=${Uri.encodeQueryComponent(cleanedAddress)}',
|
||||
);
|
||||
|
||||
// Nominatim은 User-Agent 헤더를 요구한다.
|
||||
@@ -121,4 +124,39 @@ class GeocodingService {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// 주소에서 상세 주소(층수, 상호명 등)를 제거하여 순수 도로명 주소만 추출한다.
|
||||
///
|
||||
/// 예시:
|
||||
/// - "서울 관악구 관악로14길 6-4 1층 이자카야 혼네" → "서울 관악구 관악로14길 6-4"
|
||||
/// - "서울특별시 강남구 테헤란로 123 B1 스타벅스" → "서울특별시 강남구 테헤란로 123"
|
||||
String _cleanAddress(String address) {
|
||||
final trimmed = address.trim();
|
||||
|
||||
// 패턴 1: 건물번호 뒤에 층수 정보가 있는 경우 (1층, B1, 지하1층 등)
|
||||
// 도로명 주소의 건물번호는 숫자 또는 숫자-숫자 형태
|
||||
final floorPattern = RegExp(
|
||||
r'(\d+(?:-\d+)?)\s+(?:\d+층|[Bb]\d+|지하\d*층?).*$',
|
||||
);
|
||||
final floorMatch = floorPattern.firstMatch(trimmed);
|
||||
if (floorMatch != null) {
|
||||
final buildingNumber = floorMatch.group(1);
|
||||
final beforeMatch = trimmed.substring(0, floorMatch.start);
|
||||
return '$beforeMatch$buildingNumber'.trim();
|
||||
}
|
||||
|
||||
// 패턴 2: 건물번호 뒤에 상호명이 바로 오는 경우 (공백 + 한글/영문)
|
||||
// 단, 구/동/로/길 같은 주소 구성요소는 제외
|
||||
final namePattern = RegExp(
|
||||
r'(\d+(?:-\d+)?)\s+(?![가-힣]+[구동로길읍면리]\s)([가-힣a-zA-Z&]+.*)$',
|
||||
);
|
||||
final nameMatch = namePattern.firstMatch(trimmed);
|
||||
if (nameMatch != null) {
|
||||
final buildingNumber = nameMatch.group(1);
|
||||
final beforeMatch = trimmed.substring(0, nameMatch.start);
|
||||
return '$beforeMatch$buildingNumber'.trim();
|
||||
}
|
||||
|
||||
return trimmed;
|
||||
}
|
||||
}
|
||||
|
||||
58
lib/core/widgets/info_row.dart
Normal file
58
lib/core/widgets/info_row.dart
Normal file
@@ -0,0 +1,58 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../constants/app_dimensions.dart';
|
||||
import '../constants/app_typography.dart';
|
||||
|
||||
/// 상세 정보를 표시하는 공통 행 위젯
|
||||
/// [label]과 [value]를 수직 또는 수평으로 배치
|
||||
class InfoRow extends StatelessWidget {
|
||||
final String label;
|
||||
final String value;
|
||||
final bool isDark;
|
||||
|
||||
/// true: 수평 배치 (레이블 | 값), false: 수직 배치 (레이블 위, 값 아래)
|
||||
final bool horizontal;
|
||||
|
||||
/// 수평 배치 시 레이블 영역 너비
|
||||
final double? labelWidth;
|
||||
|
||||
const InfoRow({
|
||||
super.key,
|
||||
required this.label,
|
||||
required this.value,
|
||||
required this.isDark,
|
||||
this.horizontal = false,
|
||||
this.labelWidth = 80,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (horizontal) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: AppDimensions.paddingXs),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
SizedBox(
|
||||
width: labelWidth,
|
||||
child: Text(label, style: AppTypography.caption(isDark)),
|
||||
),
|
||||
const SizedBox(width: AppDimensions.paddingSm),
|
||||
Expanded(child: Text(value, style: AppTypography.body2(isDark))),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: AppDimensions.paddingXs),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(label, style: AppTypography.caption(isDark)),
|
||||
const SizedBox(height: 2),
|
||||
Text(value, style: AppTypography.body2(isDark)),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
147
lib/core/widgets/skeleton_loader.dart
Normal file
147
lib/core/widgets/skeleton_loader.dart
Normal file
@@ -0,0 +1,147 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../constants/app_colors.dart';
|
||||
import '../constants/app_dimensions.dart';
|
||||
|
||||
/// Shimmer 효과를 가진 스켈톤 로더
|
||||
class SkeletonLoader extends StatefulWidget {
|
||||
final double width;
|
||||
final double height;
|
||||
final double borderRadius;
|
||||
|
||||
const SkeletonLoader({
|
||||
super.key,
|
||||
this.width = double.infinity,
|
||||
required this.height,
|
||||
this.borderRadius = AppDimensions.radiusSm,
|
||||
});
|
||||
|
||||
@override
|
||||
State<SkeletonLoader> createState() => _SkeletonLoaderState();
|
||||
}
|
||||
|
||||
class _SkeletonLoaderState extends State<SkeletonLoader>
|
||||
with SingleTickerProviderStateMixin {
|
||||
late AnimationController _controller;
|
||||
late Animation<double> _animation;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_controller = AnimationController(
|
||||
duration: const Duration(milliseconds: 1500),
|
||||
vsync: this,
|
||||
)..repeat();
|
||||
|
||||
_animation = Tween<double>(begin: -1.0, end: 2.0).animate(
|
||||
CurvedAnimation(parent: _controller, curve: Curves.easeInOutSine),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
final baseColor = isDark
|
||||
? AppColors.darkSurface.withValues(alpha: 0.6)
|
||||
: Colors.grey.shade300;
|
||||
final highlightColor = isDark
|
||||
? AppColors.darkSurface.withValues(alpha: 0.9)
|
||||
: Colors.grey.shade100;
|
||||
|
||||
return AnimatedBuilder(
|
||||
animation: _animation,
|
||||
builder: (context, child) {
|
||||
return Container(
|
||||
width: widget.width,
|
||||
height: widget.height,
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(widget.borderRadius),
|
||||
gradient: LinearGradient(
|
||||
begin: Alignment.centerLeft,
|
||||
end: Alignment.centerRight,
|
||||
colors: [baseColor, highlightColor, baseColor],
|
||||
stops: [
|
||||
(_animation.value - 1).clamp(0.0, 1.0),
|
||||
_animation.value.clamp(0.0, 1.0),
|
||||
(_animation.value + 1).clamp(0.0, 1.0),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 맛집 카드 스켈톤
|
||||
class RestaurantCardSkeleton extends StatelessWidget {
|
||||
const RestaurantCardSkeleton({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
|
||||
return Card(
|
||||
margin: const EdgeInsets.symmetric(
|
||||
horizontal: AppDimensions.paddingDefault,
|
||||
vertical: AppDimensions.paddingSm,
|
||||
),
|
||||
color: isDark ? AppColors.darkSurface : AppColors.lightSurface,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(AppDimensions.paddingDefault),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
// 카테고리 아이콘 영역
|
||||
const SkeletonLoader(
|
||||
width: AppDimensions.cardIconSize,
|
||||
height: AppDimensions.cardIconSize,
|
||||
),
|
||||
const SizedBox(width: AppDimensions.paddingMd),
|
||||
// 가게 정보 영역
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const SkeletonLoader(height: 20, width: 150),
|
||||
const SizedBox(height: AppDimensions.paddingXs),
|
||||
const SkeletonLoader(height: 14, width: 100),
|
||||
],
|
||||
),
|
||||
),
|
||||
// 거리 배지
|
||||
const SkeletonLoader(width: 60, height: 28, borderRadius: 14),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: AppDimensions.paddingMd),
|
||||
// 주소
|
||||
const SkeletonLoader(height: 14),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 맛집 리스트 스켈톤
|
||||
class RestaurantListSkeleton extends StatelessWidget {
|
||||
final int itemCount;
|
||||
|
||||
const RestaurantListSkeleton({super.key, this.itemCount = 5});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ListView.builder(
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
itemCount: itemCount,
|
||||
itemBuilder: (context, index) => const RestaurantCardSkeleton(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,68 @@
|
||||
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
|
||||
|
||||
/// BLE 공유를 위한 디바이스 정보
|
||||
class ShareDevice {
|
||||
/// 공유 코드 (6자리 숫자)
|
||||
final String code;
|
||||
|
||||
/// 디바이스 고유 ID
|
||||
final String deviceId;
|
||||
|
||||
/// BLE Remote ID (MAC 주소 또는 UUID)
|
||||
final String? remoteId;
|
||||
|
||||
/// 신호 강도 (RSSI)
|
||||
final int? rssi;
|
||||
|
||||
/// 발견 시각
|
||||
final DateTime discoveredAt;
|
||||
|
||||
/// flutter_blue_plus BluetoothDevice 참조
|
||||
/// 실제 BLE 연결 시 사용
|
||||
final BluetoothDevice? bleDevice;
|
||||
|
||||
ShareDevice({
|
||||
required this.code,
|
||||
required this.deviceId,
|
||||
this.remoteId,
|
||||
this.rssi,
|
||||
required this.discoveredAt,
|
||||
this.bleDevice,
|
||||
});
|
||||
|
||||
/// 신호 강도 레벨 (0-4)
|
||||
/// RSSI 값을 기반으로 계산
|
||||
int get signalLevel {
|
||||
if (rssi == null) return 0;
|
||||
if (rssi! >= -50) return 4; // 매우 강함
|
||||
if (rssi! >= -60) return 3; // 강함
|
||||
if (rssi! >= -70) return 2; // 보통
|
||||
if (rssi! >= -80) return 1; // 약함
|
||||
return 0; // 매우 약함
|
||||
}
|
||||
|
||||
/// 디버그용 문자열
|
||||
@override
|
||||
String toString() {
|
||||
return 'ShareDevice(code: $code, deviceId: $deviceId, rssi: $rssi)';
|
||||
}
|
||||
|
||||
/// 복사본 생성
|
||||
ShareDevice copyWith({
|
||||
String? code,
|
||||
String? deviceId,
|
||||
String? remoteId,
|
||||
int? rssi,
|
||||
DateTime? discoveredAt,
|
||||
BluetoothDevice? bleDevice,
|
||||
}) {
|
||||
return ShareDevice(
|
||||
code: code ?? this.code,
|
||||
deviceId: deviceId ?? this.deviceId,
|
||||
remoteId: remoteId ?? this.remoteId,
|
||||
rssi: rssi ?? this.rssi,
|
||||
discoveredAt: discoveredAt ?? this.discoveredAt,
|
||||
bleDevice: bleDevice ?? this.bleDevice,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,14 +22,28 @@ import 'data/sample/sample_data_initializer.dart';
|
||||
void main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
if (AdHelper.isMobilePlatform) {
|
||||
await MobileAds.instance.initialize();
|
||||
}
|
||||
|
||||
// Initialize timezone
|
||||
// Initialize timezone (동기, 빠름)
|
||||
tz.initializeTimeZones();
|
||||
|
||||
// Initialize Hive
|
||||
// 광고 SDK와 Hive 초기화를 병렬 처리
|
||||
await Future.wait([
|
||||
if (AdHelper.isMobilePlatform) MobileAds.instance.initialize(),
|
||||
_initializeHive(),
|
||||
]);
|
||||
|
||||
// Hive 초기화 후 병렬 처리 가능한 작업들
|
||||
await Future.wait([
|
||||
SampleDataInitializer.seedInitialData(),
|
||||
_initializeNotifications(),
|
||||
AdaptiveTheme.getThemeMode(),
|
||||
]).then((results) {
|
||||
final savedThemeMode = results[2] as AdaptiveThemeMode?;
|
||||
runApp(ProviderScope(child: LunchPickApp(savedThemeMode: savedThemeMode)));
|
||||
});
|
||||
}
|
||||
|
||||
/// Hive 초기화 및 Box 오픈
|
||||
Future<void> _initializeHive() async {
|
||||
await Hive.initFlutter();
|
||||
|
||||
// Register Hive Adapters
|
||||
@@ -39,24 +53,21 @@ void main() async {
|
||||
Hive.registerAdapter(RecommendationRecordAdapter());
|
||||
Hive.registerAdapter(UserSettingsAdapter());
|
||||
|
||||
// Open Hive Boxes
|
||||
await Hive.openBox<Restaurant>(AppConstants.restaurantBox);
|
||||
await Hive.openBox<VisitRecord>(AppConstants.visitRecordBox);
|
||||
await Hive.openBox<RecommendationRecord>(AppConstants.recommendationBox);
|
||||
await Hive.openBox(AppConstants.settingsBox);
|
||||
await Hive.openBox<UserSettings>('user_settings');
|
||||
await SampleDataInitializer.seedInitialData();
|
||||
// Open Hive Boxes (병렬 오픈)
|
||||
await Future.wait([
|
||||
Hive.openBox<Restaurant>(AppConstants.restaurantBox),
|
||||
Hive.openBox<VisitRecord>(AppConstants.visitRecordBox),
|
||||
Hive.openBox<RecommendationRecord>(AppConstants.recommendationBox),
|
||||
Hive.openBox(AppConstants.settingsBox),
|
||||
Hive.openBox<UserSettings>('user_settings'),
|
||||
]);
|
||||
}
|
||||
|
||||
// Initialize Notification Service (only for non-web platforms)
|
||||
if (!kIsWeb) {
|
||||
final notificationService = NotificationService();
|
||||
await notificationService.ensureInitialized(requestPermission: true);
|
||||
}
|
||||
|
||||
// Get saved theme mode
|
||||
final savedThemeMode = await AdaptiveTheme.getThemeMode();
|
||||
|
||||
runApp(ProviderScope(child: LunchPickApp(savedThemeMode: savedThemeMode)));
|
||||
/// 알림 서비스 초기화 (비-웹 플랫폼)
|
||||
Future<void> _initializeNotifications() async {
|
||||
if (kIsWeb) return;
|
||||
final notificationService = NotificationService();
|
||||
await notificationService.ensureInitialized(requestPermission: true);
|
||||
}
|
||||
|
||||
class LunchPickApp extends StatelessWidget {
|
||||
|
||||
@@ -3,6 +3,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:table_calendar/table_calendar.dart';
|
||||
import '../../../core/constants/app_colors.dart';
|
||||
import '../../../core/constants/app_typography.dart';
|
||||
import '../../../core/widgets/info_row.dart';
|
||||
import '../../../domain/entities/restaurant.dart';
|
||||
import '../../../domain/entities/recommendation_record.dart';
|
||||
import '../../../domain/entities/visit_record.dart';
|
||||
@@ -585,9 +586,11 @@ class _CalendarScreenState extends ConsumerState<CalendarScreen>
|
||||
final recoTime = recommendationRecord?.recommendationDate;
|
||||
final isVisitConfirmed = visitRecord?.isConfirmed == true;
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 12, 16, 20),
|
||||
child: Column(
|
||||
return SafeArea(
|
||||
top: false,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 12, 16, 20),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
@@ -607,18 +610,25 @@ class _CalendarScreenState extends ConsumerState<CalendarScreen>
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
_buildInfoRow('주소', restaurant.roadAddress, isDark),
|
||||
InfoRow(
|
||||
label: '주소',
|
||||
value: restaurant.roadAddress,
|
||||
isDark: isDark,
|
||||
horizontal: true,
|
||||
),
|
||||
if (visitTime != null)
|
||||
_buildInfoRow(
|
||||
isVisitConfirmed ? '방문 완료' : '방문 예정',
|
||||
_formatFullDateTime(visitTime),
|
||||
isDark,
|
||||
InfoRow(
|
||||
label: isVisitConfirmed ? '방문 완료' : '방문 예정',
|
||||
value: _formatFullDateTime(visitTime),
|
||||
isDark: isDark,
|
||||
horizontal: true,
|
||||
),
|
||||
if (recoTime != null)
|
||||
_buildInfoRow(
|
||||
'추천 시각',
|
||||
_formatFullDateTime(recoTime),
|
||||
isDark,
|
||||
InfoRow(
|
||||
label: '추천 시각',
|
||||
value: _formatFullDateTime(recoTime),
|
||||
isDark: isDark,
|
||||
horizontal: true,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Wrap(
|
||||
@@ -681,7 +691,8 @@ class _CalendarScreenState extends ConsumerState<CalendarScreen>
|
||||
label: const Text('추천 방문 기록으로 저장'),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
@@ -703,23 +714,6 @@ class _CalendarScreenState extends ConsumerState<CalendarScreen>
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildInfoRow(String label, String value, bool isDark) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 4),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
SizedBox(
|
||||
width: 80,
|
||||
child: Text(label, style: AppTypography.caption(isDark)),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(child: Text(value, style: AppTypography.body2(isDark))),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _showRestaurantDetailDialog(
|
||||
BuildContext context,
|
||||
bool isDark,
|
||||
@@ -737,18 +731,39 @@ class _CalendarScreenState extends ConsumerState<CalendarScreen>
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
_buildInfoRow(
|
||||
'카테고리',
|
||||
'${restaurant.category} > ${restaurant.subCategory}',
|
||||
isDark,
|
||||
InfoRow(
|
||||
label: '카테고리',
|
||||
value: '${restaurant.category} > ${restaurant.subCategory}',
|
||||
isDark: isDark,
|
||||
horizontal: true,
|
||||
),
|
||||
if (restaurant.phoneNumber != null)
|
||||
_buildInfoRow('전화번호', restaurant.phoneNumber!, isDark),
|
||||
_buildInfoRow('도로명', restaurant.roadAddress, isDark),
|
||||
_buildInfoRow('지번', restaurant.jibunAddress, isDark),
|
||||
InfoRow(
|
||||
label: '전화번호',
|
||||
value: restaurant.phoneNumber!,
|
||||
isDark: isDark,
|
||||
horizontal: true,
|
||||
),
|
||||
InfoRow(
|
||||
label: '도로명',
|
||||
value: restaurant.roadAddress,
|
||||
isDark: isDark,
|
||||
horizontal: true,
|
||||
),
|
||||
InfoRow(
|
||||
label: '지번',
|
||||
value: restaurant.jibunAddress,
|
||||
isDark: isDark,
|
||||
horizontal: true,
|
||||
),
|
||||
if (restaurant.description != null &&
|
||||
restaurant.description!.isNotEmpty)
|
||||
_buildInfoRow('메모', restaurant.description!, isDark),
|
||||
InfoRow(
|
||||
label: '메모',
|
||||
value: restaurant.description!,
|
||||
isDark: isDark,
|
||||
horizontal: true,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
@@ -27,6 +27,33 @@ class RecommendationRecordCard extends ConsumerWidget {
|
||||
return '$hour:$minute';
|
||||
}
|
||||
|
||||
Future<void> _showDeleteConfirmation(BuildContext context) async {
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: const Text('추천 기록 삭제'),
|
||||
content: const Text('이 추천 기록을 삭제하시겠습니까?'),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(false),
|
||||
child: const Text('취소'),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(true),
|
||||
style: TextButton.styleFrom(
|
||||
foregroundColor: AppColors.lightError,
|
||||
),
|
||||
child: const Text('삭제'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
if (confirmed == true) {
|
||||
onDelete();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
@@ -166,7 +193,7 @@ class RecommendationRecordCard extends ConsumerWidget {
|
||||
Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: TextButton(
|
||||
onPressed: onDelete,
|
||||
onPressed: () => _showDeleteConfirmation(context),
|
||||
style: TextButton.styleFrom(
|
||||
foregroundColor: Colors.redAccent,
|
||||
padding: const EdgeInsets.only(top: 6),
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:geolocator/geolocator.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
import '../../../core/constants/app_colors.dart';
|
||||
import '../../../core/constants/app_dimensions.dart';
|
||||
import '../../../core/constants/app_typography.dart';
|
||||
import '../../../core/utils/category_mapper.dart';
|
||||
import '../../../domain/entities/restaurant.dart';
|
||||
@@ -306,8 +308,8 @@ class _RandomSelectionScreenState extends ConsumerState<RandomSelectionScreen> {
|
||||
child: Slider(
|
||||
value: _distanceValue,
|
||||
min: 100,
|
||||
max: 2000,
|
||||
divisions: 19,
|
||||
max: AppDimensions.maxSearchDistance,
|
||||
divisions: AppDimensions.distanceSliderDivisions,
|
||||
onChanged: (value) {
|
||||
setState(() => _distanceValue = value);
|
||||
},
|
||||
@@ -739,6 +741,9 @@ class _RandomSelectionScreenState extends ConsumerState<RandomSelectionScreen> {
|
||||
}) async {
|
||||
if (_isProcessingRecommendation) return;
|
||||
|
||||
// 버튼 터치 햅틱 피드백
|
||||
HapticFeedback.mediumImpact();
|
||||
|
||||
if (!isReroll) {
|
||||
_excludedRestaurantIds.clear();
|
||||
}
|
||||
@@ -769,6 +774,10 @@ class _RandomSelectionScreenState extends ConsumerState<RandomSelectionScreen> {
|
||||
}
|
||||
|
||||
if (!mounted) return;
|
||||
|
||||
// 추천 결과 햅틱 피드백
|
||||
HapticFeedback.heavyImpact();
|
||||
|
||||
await _showRecommendationDialog(candidate, recommendedAt: recommendedAt);
|
||||
} catch (_) {
|
||||
_showSnack('추천을 준비하는 중 문제가 발생했습니다.', type: _SnackType.error);
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import '../../../core/constants/app_colors.dart';
|
||||
import '../../../core/constants/app_dimensions.dart';
|
||||
import '../../../core/constants/app_typography.dart';
|
||||
import '../../../core/widgets/skeleton_loader.dart';
|
||||
import '../../../core/utils/category_mapper.dart';
|
||||
import '../../../core/utils/app_logger.dart';
|
||||
import '../../providers/restaurant_provider.dart';
|
||||
import '../../providers/settings_provider.dart';
|
||||
import '../../providers/visit_provider.dart';
|
||||
import '../../widgets/category_selector.dart';
|
||||
import '../../widgets/native_ad_placeholder.dart';
|
||||
import 'manual_restaurant_input_screen.dart';
|
||||
@@ -40,6 +43,8 @@ class _RestaurantListScreenState extends ConsumerState<RestaurantListScreen> {
|
||||
.maybeWhen(data: (value) => value, orElse: () => false);
|
||||
final isFiltered = searchQuery.isNotEmpty || selectedCategory != null;
|
||||
final restaurantsAsync = ref.watch(sortedRestaurantsByDistanceProvider);
|
||||
final lastVisitDates =
|
||||
ref.watch(allLastVisitDatesProvider).valueOrNull ?? {};
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: isDark
|
||||
@@ -70,6 +75,7 @@ class _RestaurantListScreenState extends ConsumerState<RestaurantListScreen> {
|
||||
if (_isSearching) ...[
|
||||
IconButton(
|
||||
icon: const Icon(Icons.close),
|
||||
tooltip: '검색 닫기',
|
||||
onPressed: () {
|
||||
setState(() {
|
||||
_isSearching = false;
|
||||
@@ -81,6 +87,7 @@ class _RestaurantListScreenState extends ConsumerState<RestaurantListScreen> {
|
||||
] else ...[
|
||||
IconButton(
|
||||
icon: const Icon(Icons.search),
|
||||
tooltip: '맛집 검색',
|
||||
onPressed: () {
|
||||
setState(() {
|
||||
_isSearching = true;
|
||||
@@ -149,8 +156,8 @@ class _RestaurantListScreenState extends ConsumerState<RestaurantListScreen> {
|
||||
return _buildEmptyState(isDark);
|
||||
}
|
||||
|
||||
const adInterval = 6; // 5리스트 후 1광고
|
||||
const adOffset = 5; // 1~5 리스트 이후 6 광고 시작
|
||||
const adInterval = AppDimensions.adInterval;
|
||||
const adOffset = AppDimensions.adOffset;
|
||||
final adCount = (items.length ~/ adOffset);
|
||||
final totalCount = items.length + adCount;
|
||||
|
||||
@@ -180,48 +187,70 @@ class _RestaurantListScreenState extends ConsumerState<RestaurantListScreen> {
|
||||
return RestaurantCard(
|
||||
restaurant: item.restaurant,
|
||||
distanceKm: item.distanceKm,
|
||||
lastVisitDate: lastVisitDates[item.restaurant.id],
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
loading: () {
|
||||
AppLogger.debug('[restaurant_list_ui] loading...');
|
||||
return const Center(
|
||||
child: CircularProgressIndicator(
|
||||
color: AppColors.lightPrimary,
|
||||
),
|
||||
);
|
||||
return const RestaurantListSkeleton();
|
||||
},
|
||||
error: (error, stack) => Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.error_outline,
|
||||
size: 64,
|
||||
color: isDark
|
||||
? AppColors.darkError
|
||||
: AppColors.lightError,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text('오류가 발생했습니다', style: AppTypography.heading2(isDark)),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
error.toString(),
|
||||
style: AppTypography.body2(isDark),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(AppDimensions.paddingDefault),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.error_outline,
|
||||
size: AppDimensions.iconXxl,
|
||||
color: isDark
|
||||
? AppColors.darkError
|
||||
: AppColors.lightError,
|
||||
),
|
||||
const SizedBox(height: AppDimensions.paddingDefault),
|
||||
Text('오류가 발생했습니다', style: AppTypography.heading2(isDark)),
|
||||
const SizedBox(height: AppDimensions.paddingSm),
|
||||
Text(
|
||||
error.toString(),
|
||||
style: AppTypography.body2(isDark),
|
||||
textAlign: TextAlign.center,
|
||||
maxLines: 3,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
const SizedBox(height: AppDimensions.paddingLg),
|
||||
ElevatedButton.icon(
|
||||
onPressed: () =>
|
||||
ref.invalidate(sortedRestaurantsByDistanceProvider),
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: AppColors.lightPrimary,
|
||||
foregroundColor: Colors.white,
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: AppDimensions.paddingXl,
|
||||
vertical: AppDimensions.paddingMd,
|
||||
),
|
||||
),
|
||||
icon: const Icon(Icons.refresh),
|
||||
label: const Text('다시 시도'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
floatingActionButton: FloatingActionButton(
|
||||
onPressed: _showAddOptions,
|
||||
backgroundColor: AppColors.lightPrimary,
|
||||
child: const Icon(Icons.add, color: Colors.white),
|
||||
floatingActionButton: Semantics(
|
||||
label: '맛집 추가하기',
|
||||
button: true,
|
||||
child: FloatingActionButton(
|
||||
onPressed: _showAddOptions,
|
||||
tooltip: '맛집 추가',
|
||||
backgroundColor: AppColors.lightPrimary,
|
||||
child: const Icon(Icons.add, color: Colors.white),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -124,7 +124,7 @@ class _AddRestaurantDialogState extends ConsumerState<AddRestaurantDialog> {
|
||||
_jibunAddressController.text = formData.jibunAddress;
|
||||
_latitudeController.text = formData.latitude;
|
||||
_longitudeController.text = formData.longitude;
|
||||
_naverUrlController.text = formData.naverUrl;
|
||||
// naverUrlController는 사용자 입력을 그대로 유지
|
||||
}
|
||||
|
||||
Future<void> _saveRestaurant() async {
|
||||
@@ -234,6 +234,7 @@ class _AddRestaurantDialogState extends ConsumerState<AddRestaurantDialog> {
|
||||
longitudeController: _longitudeController,
|
||||
naverUrlController: _naverUrlController,
|
||||
onFieldChanged: _onFormDataChanged,
|
||||
naverUrl: state.formData.naverUrl,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
|
||||
import '../../../services/restaurant_form_validator.dart';
|
||||
|
||||
/// 식당 추가 폼 위젯
|
||||
@@ -18,6 +20,7 @@ class AddRestaurantForm extends StatefulWidget {
|
||||
final List<String> categories;
|
||||
final List<String> subCategories;
|
||||
final String geocodingStatus;
|
||||
final TextEditingController? naverUrlController; // 네이버 지도 URL 입력
|
||||
|
||||
const AddRestaurantForm({
|
||||
super.key,
|
||||
@@ -35,6 +38,7 @@ class AddRestaurantForm extends StatefulWidget {
|
||||
this.categories = const <String>[],
|
||||
this.subCategories = const <String>[],
|
||||
this.geocodingStatus = '',
|
||||
this.naverUrlController,
|
||||
});
|
||||
|
||||
@override
|
||||
@@ -196,90 +200,22 @@ class _AddRestaurantFormState extends State<AddRestaurantForm> {
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// 위도/경도 입력
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: TextFormField(
|
||||
controller: widget.latitudeController,
|
||||
keyboardType: const TextInputType.numberWithOptions(
|
||||
decimal: true,
|
||||
),
|
||||
decoration: InputDecoration(
|
||||
labelText: '위도',
|
||||
hintText: '37.5665',
|
||||
prefixIcon: const Icon(Icons.explore),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
),
|
||||
onChanged: widget.onFieldChanged,
|
||||
validator: (value) {
|
||||
if (value != null && value.isNotEmpty) {
|
||||
final latitude = double.tryParse(value);
|
||||
if (latitude == null || latitude < -90 || latitude > 90) {
|
||||
return '올바른 위도값을 입력해주세요';
|
||||
}
|
||||
}
|
||||
return null;
|
||||
},
|
||||
// 네이버 지도 URL (컨트롤러가 있는 경우 항상 표시)
|
||||
if (widget.naverUrlController != null)
|
||||
_buildNaverUrlField(context),
|
||||
|
||||
if (widget.geocodingStatus.isNotEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 8),
|
||||
child: Text(
|
||||
widget.geocodingStatus,
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: Colors.blueGrey,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: TextFormField(
|
||||
controller: widget.longitudeController,
|
||||
keyboardType: const TextInputType.numberWithOptions(
|
||||
decimal: true,
|
||||
),
|
||||
decoration: InputDecoration(
|
||||
labelText: '경도',
|
||||
hintText: '126.9780',
|
||||
prefixIcon: const Icon(Icons.explore),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
),
|
||||
onChanged: widget.onFieldChanged,
|
||||
validator: (value) {
|
||||
if (value != null && value.isNotEmpty) {
|
||||
final longitude = double.tryParse(value);
|
||||
if (longitude == null ||
|
||||
longitude < -180 ||
|
||||
longitude > 180) {
|
||||
return '올바른 경도값을 입력해주세요';
|
||||
}
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.center,
|
||||
children: [
|
||||
Text(
|
||||
'주소가 정확하지 않을 경우 위도/경도를 현재 위치로 입력합니다.',
|
||||
style: Theme.of(
|
||||
context,
|
||||
).textTheme.bodySmall?.copyWith(color: Colors.grey),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
if (widget.geocodingStatus.isNotEmpty) ...[
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
widget.geocodingStatus,
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: Colors.blueGrey,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
@@ -459,4 +395,66 @@ class _AddRestaurantFormState extends State<AddRestaurantForm> {
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildNaverUrlField(BuildContext context) {
|
||||
final url = widget.naverUrlController!.text.trim();
|
||||
final hasUrl = url.isNotEmpty && url.startsWith('http');
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
TextFormField(
|
||||
controller: widget.naverUrlController,
|
||||
keyboardType: TextInputType.multiline,
|
||||
minLines: 1,
|
||||
maxLines: 4,
|
||||
decoration: InputDecoration(
|
||||
labelText: '네이버 지도 링크',
|
||||
hintText: '네이버 지도 공유 링크를 붙여넣으세요',
|
||||
prefixIcon: const Icon(Icons.link),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
suffixIcon: hasUrl
|
||||
? IconButton(
|
||||
icon: Icon(Icons.open_in_new, color: Colors.blue[700]),
|
||||
onPressed: () => _launchNaverUrl(url),
|
||||
tooltip: '네이버 지도에서 열기',
|
||||
)
|
||||
: null,
|
||||
),
|
||||
onChanged: widget.onFieldChanged,
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'공유 텍스트 전체를 붙여넣으면 URL만 자동 추출됩니다.',
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: Colors.grey,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _launchNaverUrl(String text) async {
|
||||
// URL 추출
|
||||
final urlRegex = RegExp(
|
||||
r'(https?://(?:map\.naver\.com|naver\.me)[^\s]+)',
|
||||
caseSensitive: false,
|
||||
);
|
||||
final match = urlRegex.firstMatch(text);
|
||||
final url = match?.group(0) ?? text;
|
||||
|
||||
final uri = Uri.tryParse(url);
|
||||
if (uri == null) return;
|
||||
|
||||
try {
|
||||
await launchUrl(uri, mode: LaunchMode.externalApplication);
|
||||
} catch (_) {
|
||||
await launchUrl(uri, mode: LaunchMode.platformDefault);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,7 +75,7 @@ class AddRestaurantUrlTab extends StatelessWidget {
|
||||
minLines: 1,
|
||||
maxLines: 6,
|
||||
decoration: InputDecoration(
|
||||
labelText: '네이버 지도 URL',
|
||||
labelText: '네이버 지도 링크',
|
||||
hintText: kIsWeb
|
||||
? 'https://map.naver.com/...'
|
||||
: 'https://naver.me/...',
|
||||
|
||||
@@ -32,6 +32,7 @@ class _EditRestaurantDialogState extends ConsumerState<EditRestaurantDialog> {
|
||||
late final TextEditingController _jibunAddressController;
|
||||
late final TextEditingController _latitudeController;
|
||||
late final TextEditingController _longitudeController;
|
||||
late final TextEditingController _naverUrlController;
|
||||
|
||||
bool _isSaving = false;
|
||||
late final String _originalRoadAddress;
|
||||
@@ -64,6 +65,9 @@ class _EditRestaurantDialogState extends ConsumerState<EditRestaurantDialog> {
|
||||
_longitudeController = TextEditingController(
|
||||
text: restaurant.longitude.toString(),
|
||||
);
|
||||
_naverUrlController = TextEditingController(
|
||||
text: restaurant.naverUrl ?? '',
|
||||
);
|
||||
_originalRoadAddress = restaurant.roadAddress;
|
||||
_originalJibunAddress = restaurant.jibunAddress;
|
||||
}
|
||||
@@ -79,6 +83,7 @@ class _EditRestaurantDialogState extends ConsumerState<EditRestaurantDialog> {
|
||||
_jibunAddressController.dispose();
|
||||
_latitudeController.dispose();
|
||||
_longitudeController.dispose();
|
||||
_naverUrlController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@@ -107,6 +112,9 @@ class _EditRestaurantDialogState extends ConsumerState<EditRestaurantDialog> {
|
||||
_latitudeController.text = coords.latitude.toString();
|
||||
_longitudeController.text = coords.longitude.toString();
|
||||
|
||||
// URL 추출: 공유 텍스트에서 URL만 추출
|
||||
final extractedUrl = _extractNaverUrl(_naverUrlController.text.trim());
|
||||
|
||||
final updatedRestaurant = widget.restaurant.copyWith(
|
||||
name: _nameController.text.trim(),
|
||||
category: _categoryController.text.trim(),
|
||||
@@ -125,6 +133,7 @@ class _EditRestaurantDialogState extends ConsumerState<EditRestaurantDialog> {
|
||||
: _jibunAddressController.text.trim(),
|
||||
latitude: coords.latitude,
|
||||
longitude: coords.longitude,
|
||||
naverUrl: extractedUrl.isEmpty ? null : extractedUrl,
|
||||
updatedAt: DateTime.now(),
|
||||
needsAddressVerification: coords.usedCurrentLocation,
|
||||
);
|
||||
@@ -201,6 +210,7 @@ class _EditRestaurantDialogState extends ConsumerState<EditRestaurantDialog> {
|
||||
onFieldChanged: _onFieldChanged,
|
||||
categories: categories,
|
||||
subCategories: subCategories,
|
||||
naverUrlController: _naverUrlController,
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
Row(
|
||||
@@ -288,4 +298,17 @@ class _EditRestaurantDialogState extends ConsumerState<EditRestaurantDialog> {
|
||||
usedCurrentLocation: true,
|
||||
);
|
||||
}
|
||||
|
||||
/// 공유 텍스트에서 네이버 지도 URL만 추출
|
||||
String _extractNaverUrl(String text) {
|
||||
if (text.isEmpty) return '';
|
||||
|
||||
// URL 패턴 추출
|
||||
final urlRegex = RegExp(
|
||||
r'(https?://(?:map\.naver\.com|naver\.me)[^\s]+)',
|
||||
caseSensitive: false,
|
||||
);
|
||||
final match = urlRegex.firstMatch(text);
|
||||
return match?.group(0) ?? text;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
|
||||
import '../../../../core/constants/app_colors.dart';
|
||||
import '../../../../core/constants/app_typography.dart';
|
||||
@@ -17,6 +18,7 @@ class FetchedRestaurantJsonView extends StatefulWidget {
|
||||
final TextEditingController longitudeController;
|
||||
final TextEditingController naverUrlController;
|
||||
final ValueChanged<String> onFieldChanged;
|
||||
final String? naverUrl; // 순수 URL (클릭 가능한 링크용)
|
||||
|
||||
const FetchedRestaurantJsonView({
|
||||
super.key,
|
||||
@@ -32,6 +34,7 @@ class FetchedRestaurantJsonView extends StatefulWidget {
|
||||
required this.longitudeController,
|
||||
required this.naverUrlController,
|
||||
required this.onFieldChanged,
|
||||
this.naverUrl,
|
||||
});
|
||||
|
||||
@override
|
||||
@@ -126,7 +129,7 @@ class _FetchedRestaurantJsonViewState extends State<FetchedRestaurantJsonView> {
|
||||
controller: widget.jibunAddressController,
|
||||
icon: Icons.map,
|
||||
),
|
||||
_buildCoordinateFields(context),
|
||||
_buildNaverUrlField(context),
|
||||
_buildJsonField(
|
||||
context,
|
||||
label: '전화번호',
|
||||
@@ -154,78 +157,79 @@ class _FetchedRestaurantJsonViewState extends State<FetchedRestaurantJsonView> {
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildCoordinateFields(BuildContext context) {
|
||||
final border = OutlineInputBorder(borderRadius: BorderRadius.circular(8));
|
||||
Widget _buildNaverUrlField(BuildContext context) {
|
||||
final url = widget.naverUrl ?? '';
|
||||
if (url.isEmpty) return const SizedBox.shrink();
|
||||
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: const [
|
||||
Icon(Icons.my_location, size: 16),
|
||||
SizedBox(width: 8),
|
||||
Text('좌표'),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: TextFormField(
|
||||
controller: widget.latitudeController,
|
||||
keyboardType: const TextInputType.numberWithOptions(
|
||||
decimal: true,
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 12),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: const [
|
||||
Icon(Icons.link, size: 16),
|
||||
SizedBox(width: 8),
|
||||
Text('네이버 지도:'),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
InkWell(
|
||||
onTap: () => _launchNaverUrl(url),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
child: Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 14),
|
||||
decoration: BoxDecoration(
|
||||
border: Border.all(
|
||||
color: widget.isDark
|
||||
? AppColors.darkDivider
|
||||
: AppColors.lightDivider,
|
||||
),
|
||||
decoration: InputDecoration(
|
||||
labelText: '위도',
|
||||
border: border,
|
||||
isDense: true,
|
||||
),
|
||||
onChanged: widget.onFieldChanged,
|
||||
validator: (value) {
|
||||
if (value != null && value.isNotEmpty) {
|
||||
final latitude = double.tryParse(value);
|
||||
if (latitude == null || latitude < -90 || latitude > 90) {
|
||||
return '올바른 위도값을 입력해주세요';
|
||||
}
|
||||
}
|
||||
return null;
|
||||
},
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
color: widget.isDark
|
||||
? AppColors.darkSurface
|
||||
: AppColors.lightSurface,
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
url,
|
||||
style: TextStyle(
|
||||
color: Colors.blue[700],
|
||||
decoration: TextDecoration.underline,
|
||||
),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Icon(
|
||||
Icons.open_in_new,
|
||||
size: 18,
|
||||
color: Colors.blue[700],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: TextFormField(
|
||||
controller: widget.longitudeController,
|
||||
keyboardType: const TextInputType.numberWithOptions(
|
||||
decimal: true,
|
||||
),
|
||||
decoration: InputDecoration(
|
||||
labelText: '경도',
|
||||
border: border,
|
||||
isDense: true,
|
||||
),
|
||||
onChanged: widget.onFieldChanged,
|
||||
validator: (value) {
|
||||
if (value != null && value.isNotEmpty) {
|
||||
final longitude = double.tryParse(value);
|
||||
if (longitude == null ||
|
||||
longitude < -180 ||
|
||||
longitude > 180) {
|
||||
return '올바른 경도값을 입력해주세요';
|
||||
}
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _launchNaverUrl(String url) async {
|
||||
final uri = Uri.tryParse(url);
|
||||
if (uri == null) return;
|
||||
|
||||
try {
|
||||
await launchUrl(uri, mode: LaunchMode.externalApplication);
|
||||
} catch (_) {
|
||||
// 웹 환경에서 실패 시 platformDefault 모드로 재시도
|
||||
await launchUrl(uri, mode: LaunchMode.platformDefault);
|
||||
}
|
||||
}
|
||||
|
||||
Widget _buildCategoryField(BuildContext context) {
|
||||
return RawAutocomplete<String>(
|
||||
textEditingController: widget.categoryController,
|
||||
|
||||
@@ -1,27 +1,38 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
|
||||
import 'package:lunchpick/core/constants/app_colors.dart';
|
||||
import 'package:lunchpick/core/constants/app_typography.dart';
|
||||
import 'package:lunchpick/domain/entities/restaurant.dart';
|
||||
import 'package:lunchpick/presentation/providers/restaurant_provider.dart';
|
||||
import 'package:lunchpick/presentation/providers/visit_provider.dart';
|
||||
import 'edit_restaurant_dialog.dart';
|
||||
|
||||
/// 맛집 카드 위젯
|
||||
/// [lastVisitDate]를 외부에서 주입받아 리스트 렌더링 최적화
|
||||
class RestaurantCard extends ConsumerWidget {
|
||||
final Restaurant restaurant;
|
||||
final double? distanceKm;
|
||||
final DateTime? lastVisitDate;
|
||||
|
||||
const RestaurantCard({super.key, required this.restaurant, this.distanceKm});
|
||||
const RestaurantCard({
|
||||
super.key,
|
||||
required this.restaurant,
|
||||
this.distanceKm,
|
||||
this.lastVisitDate,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
final lastVisitAsync = ref.watch(lastVisitDateProvider(restaurant.id));
|
||||
|
||||
final hasNaverUrl = restaurant.naverUrl != null &&
|
||||
restaurant.naverUrl!.isNotEmpty;
|
||||
|
||||
return Card(
|
||||
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
child: InkWell(
|
||||
onTap: () => _showRestaurantDetail(context, isDark),
|
||||
onTap: hasNaverUrl ? () => _openNaverUrl(restaurant.naverUrl!) : null,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
@@ -177,39 +188,26 @@ class RestaurantCard extends ConsumerWidget {
|
||||
),
|
||||
|
||||
// 마지막 방문일
|
||||
lastVisitAsync.when(
|
||||
data: (lastVisit) {
|
||||
if (lastVisit != null) {
|
||||
final daysSinceVisit = DateTime.now()
|
||||
.difference(lastVisit)
|
||||
.inDays;
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(top: 8),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.schedule,
|
||||
size: 16,
|
||||
color: isDark
|
||||
? AppColors.darkTextSecondary
|
||||
: AppColors.lightTextSecondary,
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
daysSinceVisit == 0
|
||||
? '오늘 방문'
|
||||
: '$daysSinceVisit일 전 방문',
|
||||
style: AppTypography.caption(isDark),
|
||||
),
|
||||
],
|
||||
if (lastVisitDate != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 8),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.schedule,
|
||||
size: 16,
|
||||
color: isDark
|
||||
? AppColors.darkTextSecondary
|
||||
: AppColors.lightTextSecondary,
|
||||
),
|
||||
);
|
||||
}
|
||||
return const SizedBox.shrink();
|
||||
},
|
||||
loading: () => const SizedBox.shrink(),
|
||||
error: (_, __) => const SizedBox.shrink(),
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
_formatLastVisit(lastVisitDate!),
|
||||
style: AppTypography.caption(isDark),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
@@ -217,6 +215,18 @@ class RestaurantCard extends ConsumerWidget {
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _openNaverUrl(String url) async {
|
||||
final uri = Uri.tryParse(url);
|
||||
if (uri == null) return;
|
||||
|
||||
try {
|
||||
await launchUrl(uri, mode: LaunchMode.externalApplication);
|
||||
} catch (_) {
|
||||
// 웹 환경에서 실패 시 platformDefault 모드로 재시도
|
||||
await launchUrl(uri, mode: LaunchMode.platformDefault);
|
||||
}
|
||||
}
|
||||
|
||||
IconData _getCategoryIcon(String category) {
|
||||
switch (category) {
|
||||
case '한식':
|
||||
@@ -240,59 +250,9 @@ class RestaurantCard extends ConsumerWidget {
|
||||
}
|
||||
}
|
||||
|
||||
void _showRestaurantDetail(BuildContext context, bool isDark) {
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
backgroundColor: isDark
|
||||
? AppColors.darkSurface
|
||||
: AppColors.lightSurface,
|
||||
title: Text(restaurant.name),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
_buildDetailRow(
|
||||
'카테고리',
|
||||
'${restaurant.category} > ${restaurant.subCategory}',
|
||||
isDark,
|
||||
),
|
||||
if (restaurant.description != null)
|
||||
_buildDetailRow('설명', restaurant.description!, isDark),
|
||||
if (restaurant.phoneNumber != null)
|
||||
_buildDetailRow('전화번호', restaurant.phoneNumber!, isDark),
|
||||
_buildDetailRow('도로명 주소', restaurant.roadAddress, isDark),
|
||||
_buildDetailRow('지번 주소', restaurant.jibunAddress, isDark),
|
||||
if (restaurant.lastVisitDate != null)
|
||||
_buildDetailRow(
|
||||
'마지막 방문',
|
||||
'${restaurant.lastVisitDate!.year}년 ${restaurant.lastVisitDate!.month}월 ${restaurant.lastVisitDate!.day}일',
|
||||
isDark,
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context),
|
||||
child: const Text('닫기'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildDetailRow(String label, String value, bool isDark) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 4),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(label, style: AppTypography.caption(isDark)),
|
||||
const SizedBox(height: 2),
|
||||
Text(value, style: AppTypography.body2(isDark)),
|
||||
],
|
||||
),
|
||||
);
|
||||
String _formatLastVisit(DateTime date) {
|
||||
final daysSinceVisit = DateTime.now().difference(date).inDays;
|
||||
return daysSinceVisit == 0 ? '오늘 방문' : '$daysSinceVisit일 전 방문';
|
||||
}
|
||||
|
||||
void _handleMenuAction(
|
||||
|
||||
@@ -211,11 +211,11 @@ class _ShareScreenState extends ConsumerState<ShareScreen> {
|
||||
Text('이 코드를 상대방에게 알려주세요', style: AppTypography.caption(isDark)),
|
||||
const SizedBox(height: 16),
|
||||
TextButton.icon(
|
||||
onPressed: () {
|
||||
onPressed: () async {
|
||||
setState(() {
|
||||
_shareCode = null;
|
||||
});
|
||||
ref.read(bluetoothServiceProvider).stopListening();
|
||||
await ref.read(bluetoothServiceProvider).stopListening();
|
||||
},
|
||||
icon: const Icon(Icons.close),
|
||||
label: const Text('취소'),
|
||||
@@ -551,7 +551,7 @@ class _ShareScreenState extends ConsumerState<ShareScreen> {
|
||||
setState(() {
|
||||
_shareCode = null;
|
||||
});
|
||||
ref.read(bluetoothServiceProvider).stopListening();
|
||||
await ref.read(bluetoothServiceProvider).stopListening();
|
||||
}
|
||||
|
||||
void _showLoadingDialog(String message) {
|
||||
|
||||
@@ -15,10 +15,8 @@ class SplashScreen extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _SplashScreenState extends State<SplashScreen>
|
||||
with TickerProviderStateMixin {
|
||||
late List<AnimationController> _foodControllers;
|
||||
late AnimationController _questionMarkController;
|
||||
late AnimationController _centerIconController;
|
||||
with SingleTickerProviderStateMixin {
|
||||
late AnimationController _animationController;
|
||||
List<Offset>? _iconPositions;
|
||||
Size? _lastScreenSize;
|
||||
|
||||
@@ -42,24 +40,9 @@ class _SplashScreenState extends State<SplashScreen>
|
||||
}
|
||||
|
||||
void _initializeAnimations() {
|
||||
// 음식 아이콘 애니메이션 (여러 개)
|
||||
_foodControllers = List.generate(
|
||||
foodIcons.length,
|
||||
(index) => AnimationController(
|
||||
duration: Duration(seconds: 2 + index % 3),
|
||||
vsync: this,
|
||||
)..repeat(reverse: true),
|
||||
);
|
||||
|
||||
// 물음표 애니메이션
|
||||
_questionMarkController = AnimationController(
|
||||
duration: const Duration(milliseconds: 500),
|
||||
vsync: this,
|
||||
)..repeat();
|
||||
|
||||
// 중앙 아이콘 애니메이션
|
||||
_centerIconController = AnimationController(
|
||||
duration: const Duration(seconds: 1),
|
||||
// 단일 컨트롤러로 모든 애니메이션 제어 (메모리 최적화)
|
||||
_animationController = AnimationController(
|
||||
duration: const Duration(seconds: 2),
|
||||
vsync: this,
|
||||
)..repeat(reverse: true);
|
||||
}
|
||||
@@ -142,9 +125,9 @@ class _SplashScreenState extends State<SplashScreen>
|
||||
children: [
|
||||
// 선택 아이콘
|
||||
ScaleTransition(
|
||||
scale: Tween(begin: 0.8, end: 1.2).animate(
|
||||
scale: Tween(begin: 0.9, end: 1.1).animate(
|
||||
CurvedAnimation(
|
||||
parent: _centerIconController,
|
||||
parent: _animationController,
|
||||
curve: Curves.easeInOut,
|
||||
),
|
||||
),
|
||||
@@ -164,11 +147,11 @@ class _SplashScreenState extends State<SplashScreen>
|
||||
children: [
|
||||
Text('오늘 뭐 먹Z', style: AppTypography.heading1(isDark)),
|
||||
AnimatedBuilder(
|
||||
animation: _questionMarkController,
|
||||
animation: _animationController,
|
||||
builder: (context, child) {
|
||||
final questionMarks =
|
||||
'?' *
|
||||
(((_questionMarkController.value * 3).floor() % 3) +
|
||||
(((_animationController.value * 3).floor() % 3) +
|
||||
1);
|
||||
return Text(
|
||||
questionMarks,
|
||||
@@ -217,29 +200,30 @@ class _SplashScreenState extends State<SplashScreen>
|
||||
|
||||
return List.generate(foodIcons.length, (index) {
|
||||
final position = _iconPositions![index];
|
||||
// 각 아이콘마다 위상(phase)을 다르게 적용
|
||||
final phase = index / foodIcons.length;
|
||||
|
||||
return Positioned(
|
||||
left: position.dx,
|
||||
top: position.dy,
|
||||
child: FadeTransition(
|
||||
opacity: Tween(begin: 0.2, end: 0.8).animate(
|
||||
CurvedAnimation(
|
||||
parent: _foodControllers[index],
|
||||
curve: Curves.easeInOut,
|
||||
),
|
||||
),
|
||||
child: ScaleTransition(
|
||||
scale: Tween(begin: 0.5, end: 1.5).animate(
|
||||
CurvedAnimation(
|
||||
parent: _foodControllers[index],
|
||||
curve: Curves.easeInOut,
|
||||
child: AnimatedBuilder(
|
||||
animation: _animationController,
|
||||
builder: (context, child) {
|
||||
// 위상 차이로 각 아이콘이 다른 타이밍에 애니메이션
|
||||
final value =
|
||||
((_animationController.value + phase) % 1.0 - 0.5).abs() * 2;
|
||||
return Opacity(
|
||||
opacity: 0.2 + value * 0.4,
|
||||
child: Transform.scale(
|
||||
scale: 0.7 + value * 0.5,
|
||||
child: child,
|
||||
),
|
||||
),
|
||||
child: Icon(
|
||||
foodIcons[index],
|
||||
size: 40,
|
||||
color: AppColors.lightPrimary.withOpacity(0.3),
|
||||
),
|
||||
);
|
||||
},
|
||||
child: Icon(
|
||||
foodIcons[index],
|
||||
size: 40,
|
||||
color: AppColors.lightPrimary.withValues(alpha: 0.3),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -274,11 +258,7 @@ class _SplashScreenState extends State<SplashScreen>
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
for (final controller in _foodControllers) {
|
||||
controller.dispose();
|
||||
}
|
||||
_questionMarkController.dispose();
|
||||
_centerIconController.dispose();
|
||||
_animationController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -166,8 +166,8 @@ class RecommendationNotifier extends StateNotifier<AsyncValue<Restaurant?>> {
|
||||
required List<String> selectedCategories,
|
||||
List<String> excludedRestaurantIds = const [],
|
||||
}) async {
|
||||
// 현재 위치 가져오기
|
||||
final location = await _ref.read(currentLocationProvider.future);
|
||||
// 현재 위치 가져오기 (StreamProvider에서 최신 위치 사용)
|
||||
final location = _ref.read(currentLocationWithFallbackProvider).valueOrNull;
|
||||
if (location == null) {
|
||||
throw Exception('위치 정보를 가져올 수 없습니다');
|
||||
}
|
||||
@@ -382,8 +382,8 @@ class EnhancedRecommendationNotifier
|
||||
return;
|
||||
}
|
||||
|
||||
// 현재 위치 가져오기
|
||||
final location = await _ref.read(currentLocationProvider.future);
|
||||
// 현재 위치 가져오기 (StreamProvider에서 최신 위치 사용)
|
||||
final location = _ref.read(currentLocationWithFallbackProvider).valueOrNull;
|
||||
if (location == null) {
|
||||
state = state.copyWith(error: '위치 정보를 가져올 수 없습니다', isLoading: false);
|
||||
return;
|
||||
|
||||
@@ -31,6 +31,9 @@ final monthlyVisitStatsProvider =
|
||||
ref,
|
||||
params,
|
||||
) async {
|
||||
// visitRecordsProvider를 watch하여 방문 기록 변경 시 자동 갱신
|
||||
await ref.watch(visitRecordsProvider.future);
|
||||
|
||||
final repository = ref.watch(visitRepositoryProvider);
|
||||
return repository.getMonthlyVisitStats(params.year, params.month);
|
||||
});
|
||||
@@ -41,13 +44,19 @@ final monthlyCategoryVisitStatsProvider =
|
||||
ref,
|
||||
params,
|
||||
) async {
|
||||
final repository = ref.watch(visitRepositoryProvider);
|
||||
// visitRecordsProvider를 watch하여 방문 기록 변경 시 자동 갱신
|
||||
final allRecords = await ref.watch(visitRecordsProvider.future);
|
||||
final restaurants = await ref.watch(restaurantListProvider.future);
|
||||
|
||||
final records = await repository.getVisitRecordsByDateRange(
|
||||
startDate: DateTime(params.year, params.month, 1),
|
||||
endDate: DateTime(params.year, params.month + 1, 0),
|
||||
);
|
||||
// 해당 월의 기록만 필터링
|
||||
final startDate = DateTime(params.year, params.month, 1);
|
||||
final endDate = DateTime(params.year, params.month + 1, 0);
|
||||
final records = allRecords.where((record) {
|
||||
return record.visitDate.isAfter(
|
||||
startDate.subtract(const Duration(days: 1)),
|
||||
) &&
|
||||
record.visitDate.isBefore(endDate.add(const Duration(days: 1)));
|
||||
}).toList();
|
||||
|
||||
final categoryCount = <String, int>{};
|
||||
for (final record in records) {
|
||||
@@ -157,6 +166,23 @@ final lastVisitDateProvider = FutureProvider.family<DateTime?, String>((
|
||||
return repository.getLastVisitDate(restaurantId);
|
||||
});
|
||||
|
||||
/// 모든 맛집의 마지막 방문일을 한 번에 조회 (리스트 최적화용)
|
||||
final allLastVisitDatesProvider =
|
||||
FutureProvider<Map<String, DateTime?>>((ref) async {
|
||||
final records = await ref.watch(visitRecordsProvider.future);
|
||||
|
||||
// restaurantId별 가장 최근 방문일 계산
|
||||
final lastVisitMap = <String, DateTime>{};
|
||||
for (final record in records) {
|
||||
final existing = lastVisitMap[record.restaurantId];
|
||||
if (existing == null || record.visitDate.isAfter(existing)) {
|
||||
lastVisitMap[record.restaurantId] = record.visitDate;
|
||||
}
|
||||
}
|
||||
|
||||
return lastVisitMap;
|
||||
});
|
||||
|
||||
/// 기간별 방문 기록 Provider
|
||||
final visitRecordsByPeriodProvider =
|
||||
FutureProvider.family<
|
||||
|
||||
@@ -8,6 +8,15 @@ import '../providers/di_providers.dart';
|
||||
import '../providers/restaurant_provider.dart';
|
||||
import '../providers/location_provider.dart';
|
||||
|
||||
/// 지오코딩 실패 시 발생하는 예외
|
||||
class GeocodingException implements Exception {
|
||||
final String message;
|
||||
const GeocodingException(this.message);
|
||||
|
||||
@override
|
||||
String toString() => message;
|
||||
}
|
||||
|
||||
/// 식당 추가 화면의 상태 모델
|
||||
class AddRestaurantState {
|
||||
final bool isLoading;
|
||||
@@ -128,10 +137,23 @@ class RestaurantFormData {
|
||||
jibunAddress: jibunAddressController.text.trim(),
|
||||
latitude: latitudeController.text.trim(),
|
||||
longitude: longitudeController.text.trim(),
|
||||
naverUrl: naverUrlController.text.trim(),
|
||||
naverUrl: _extractNaverUrl(naverUrlController.text.trim()),
|
||||
);
|
||||
}
|
||||
|
||||
/// 공유 텍스트에서 네이버 지도 URL만 추출
|
||||
static String _extractNaverUrl(String text) {
|
||||
if (text.isEmpty) return '';
|
||||
|
||||
// URL 패턴 추출
|
||||
final urlRegex = RegExp(
|
||||
r'(https?://(?:map\.naver\.com|naver\.me)[^\s]+)',
|
||||
caseSensitive: false,
|
||||
);
|
||||
final match = urlRegex.firstMatch(text);
|
||||
return match?.group(0) ?? text;
|
||||
}
|
||||
|
||||
/// Restaurant 엔티티로부터 폼 데이터 생성
|
||||
factory RestaurantFormData.fromRestaurant(Restaurant restaurant) {
|
||||
return RestaurantFormData(
|
||||
@@ -351,7 +373,11 @@ class AddRestaurantViewModel extends StateNotifier<AddRestaurantState> {
|
||||
state = state.copyWith(isLoading: false);
|
||||
return true;
|
||||
} catch (e) {
|
||||
state = state.copyWith(isLoading: false, errorMessage: e.toString());
|
||||
// GeocodingException은 이미 사용자 친화적 메시지가 설정됨
|
||||
final message = e is GeocodingException
|
||||
? e.message
|
||||
: '저장 중 오류가 발생했습니다. 다시 시도해주세요.';
|
||||
state = state.copyWith(isLoading: false, errorMessage: message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -474,12 +500,9 @@ class AddRestaurantViewModel extends StateNotifier<AddRestaurantState> {
|
||||
);
|
||||
|
||||
if (!allowFallbackWhenGeocodingFails) {
|
||||
state = state.copyWith(
|
||||
errorMessage:
|
||||
'주소가 지도에서 인식되지 않습니다. '
|
||||
'도로명 주소 전체를 정확히 입력했는지 확인해 주세요.',
|
||||
);
|
||||
throw Exception('지오코딩 실패: $address');
|
||||
const userMessage = '위치 정보를 가져올 수 없습니다. 주소를 확인해주세요.';
|
||||
state = state.copyWith(errorMessage: userMessage);
|
||||
throw GeocodingException(userMessage);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -144,19 +144,22 @@ class _NativeAdPlaceholderState extends State<NativeAdPlaceholder> {
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
return NativeTemplateStyle(
|
||||
templateType: templateType,
|
||||
mainBackgroundColor: isDark ? AppColors.darkSurface : Colors.white,
|
||||
mainBackgroundColor:
|
||||
isDark ? AppColors.darkSurface : AppColors.lightSurface,
|
||||
cornerRadius: 0,
|
||||
callToActionTextStyle: NativeTemplateTextStyle(
|
||||
textColor: Colors.white,
|
||||
textColor: AppColors.lightSurface,
|
||||
backgroundColor: AppColors.lightPrimary,
|
||||
style: NativeTemplateFontStyle.bold,
|
||||
),
|
||||
primaryTextStyle: NativeTemplateTextStyle(
|
||||
textColor: isDark ? Colors.white : Colors.black87,
|
||||
textColor:
|
||||
isDark ? AppColors.darkTextPrimary : AppColors.lightTextPrimary,
|
||||
style: NativeTemplateFontStyle.bold,
|
||||
),
|
||||
secondaryTextStyle: NativeTemplateTextStyle(
|
||||
textColor: isDark ? Colors.white70 : Colors.black54,
|
||||
textColor:
|
||||
isDark ? AppColors.darkTextSecondary : AppColors.lightTextSecondary,
|
||||
style: NativeTemplateFontStyle.normal,
|
||||
),
|
||||
);
|
||||
@@ -250,14 +253,15 @@ class _NativeAdPlaceholderState extends State<NativeAdPlaceholder> {
|
||||
|
||||
BoxDecoration _decoration(bool isDark) {
|
||||
return BoxDecoration(
|
||||
color: isDark ? AppColors.darkSurface : Colors.white,
|
||||
color: isDark ? AppColors.darkSurface : AppColors.lightSurface,
|
||||
border: Border.all(
|
||||
color: isDark ? AppColors.darkDivider : AppColors.lightDivider,
|
||||
width: 2,
|
||||
),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: (isDark ? Colors.black : Colors.grey).withOpacity(0.08),
|
||||
color: (isDark ? AppColors.darkBackground : AppColors.lightDivider)
|
||||
.withValues(alpha: 0.3),
|
||||
blurRadius: 8,
|
||||
offset: const Offset(0, 4),
|
||||
),
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
import FlutterMacOS
|
||||
import Foundation
|
||||
|
||||
import ble_peripheral
|
||||
import flutter_blue_plus_darwin
|
||||
import flutter_local_notifications
|
||||
import geolocator_apple
|
||||
@@ -15,6 +16,7 @@ import url_launcher_macos
|
||||
import webview_flutter_wkwebview
|
||||
|
||||
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
|
||||
BlePeripheralPlugin.register(with: registry.registrar(forPlugin: "BlePeripheralPlugin"))
|
||||
FlutterBluePlusPlugin.register(with: registry.registrar(forPlugin: "FlutterBluePlusPlugin"))
|
||||
FlutterLocalNotificationsPlugin.register(with: registry.registrar(forPlugin: "FlutterLocalNotificationsPlugin"))
|
||||
GeolocatorPlugin.register(with: registry.registrar(forPlugin: "GeolocatorPlugin"))
|
||||
|
||||
@@ -49,6 +49,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.13.0"
|
||||
ble_peripheral:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: ble_peripheral
|
||||
sha256: "858d370709507155bbf69e6160e9cb81d802e664f133a649a38b9ca04439884c"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.4.0"
|
||||
bluez:
|
||||
dependency: transitive
|
||||
description:
|
||||
|
||||
@@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev
|
||||
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
|
||||
# In Windows, build-name is used as the major, minor, and patch parts
|
||||
# of the product and file versions while build-number is used as the build suffix.
|
||||
version: 1.0.0+1
|
||||
version: 1.1.1+5
|
||||
|
||||
environment:
|
||||
sdk: ^3.8.1
|
||||
@@ -63,6 +63,7 @@ dependencies:
|
||||
|
||||
# Bluetooth
|
||||
flutter_blue_plus: ^1.31.0
|
||||
ble_peripheral: ^2.4.0 # Peripheral 역할 (Receiver)
|
||||
|
||||
# Utilities
|
||||
uuid: ^4.2.1
|
||||
|
||||
@@ -6,12 +6,15 @@
|
||||
|
||||
#include "generated_plugin_registrant.h"
|
||||
|
||||
#include <ble_peripheral/ble_peripheral_plugin_c_api.h>
|
||||
#include <geolocator_windows/geolocator_windows.h>
|
||||
#include <permission_handler_windows/permission_handler_windows_plugin.h>
|
||||
#include <share_plus/share_plus_windows_plugin_c_api.h>
|
||||
#include <url_launcher_windows/url_launcher_windows.h>
|
||||
|
||||
void RegisterPlugins(flutter::PluginRegistry* registry) {
|
||||
BlePeripheralPluginCApiRegisterWithRegistrar(
|
||||
registry->GetRegistrarForPlugin("BlePeripheralPluginCApi"));
|
||||
GeolocatorWindowsRegisterWithRegistrar(
|
||||
registry->GetRegistrarForPlugin("GeolocatorWindows"));
|
||||
PermissionHandlerWindowsPluginRegisterWithRegistrar(
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#
|
||||
|
||||
list(APPEND FLUTTER_PLUGIN_LIST
|
||||
ble_peripheral
|
||||
geolocator_windows
|
||||
permission_handler_windows
|
||||
share_plus
|
||||
|
||||
Reference in New Issue
Block a user