Compare commits

...

10 Commits

Author SHA1 Message Date
JiWoong Sul
1349f35cfe chore(version): 1.1.1+5 버전 업데이트
- BLE 기반 맛집 공유 기능 구현 반영
2026-01-30 15:32:08 +09:00
JiWoong Sul
c608b6c7df feat(bluetooth): 실제 BLE 기반 맛집 리스트 공유 구현
- ble_peripheral 패키지 추가 (Peripheral/GATT Server 역할)
- flutter_blue_plus 패키지 활용 (Central/스캔/연결 역할)

변경 사항:
- BleConstants: BLE UUID 및 설정 상수 정의
- BluetoothService: Mock에서 실제 BLE 통신으로 전면 재작성
  - Receiver: GATT Server로 광고, Write callback으로 데이터 수신
  - Sender: 서비스 UUID로 스캔, 연결 후 Characteristic에 데이터 전송
  - 청크 기반 대용량 데이터 전송 프로토콜 구현
- ShareDevice: BLE 디바이스 정보 필드 추가 (remoteId, rssi, bleDevice)
- Android/iOS: BLE 권한 및 기능 선언 추가

데이터 전송 프로토콜:
- 'CHUNK:index:total:data' 형식으로 500바이트 단위 분할 전송
- 수신 측에서 청크 조립 후 JSON 파싱
2026-01-30 00:09:13 +09:00
JiWoong Sul
24b074ff4c fix(stats): 방문 통계 Provider 자동 갱신 추가
- monthlyVisitStatsProvider: visitRecordsProvider watch 추가
- monthlyCategoryVisitStatsProvider: visitRecordsProvider watch로 변경
- 방문 기록 추가/확인 시 통계가 실시간으로 갱신됨
2026-01-29 20:02:30 +09:00
JiWoong Sul
5d8e1157b9 fix(calendar): 추천 기록 삭제 확인 팝업 및 SafeArea 적용
- recommendation_record_card: 삭제 전 확인 팝업 추가
- calendar_screen: 상세보기 BottomSheet에 SafeArea 적용
- 안드로이드 네비게이션 바에 버튼이 가려지는 문제 해결
2026-01-29 19:59:39 +09:00
JiWoong Sul
29c247abc1 fix(location): 추천 엔진에서 최신 위치 사용하도록 수정
- _generateCandidate(): currentLocationProvider → currentLocationWithFallbackProvider
- EnhancedRecommendationNotifier: 동일하게 수정
- 백그라운드 복귀 시 캐시된 위치 대신 실시간 위치 사용
2026-01-29 19:52:07 +09:00
JiWoong Sul
e888b51875 chore(version): 1.1.0+4 버전 업데이트
- 네이버 지도 공유 텍스트 처리 개선
- URL 열기 기능 웹 환경 호환성 개선
2026-01-28 19:04:17 +09:00
JiWoong Sul
6426d14336 feat(ui): 네이버 지도 링크 필드 UI 개선
- 레이블 "네이버 지도 URL" → "네이버 지도 링크" 변경
- add_restaurant_form: URL 입력 필드 추가 (공유 텍스트 붙여넣기 지원)
- edit_restaurant_dialog: URL 필드 항상 표시, URL 추출 로직 추가
- add_restaurant_dialog: naverUrl을 FetchedRestaurantJsonView에 전달
2026-01-28 18:54:59 +09:00
JiWoong Sul
b989981464 fix(url): URL 열기 시 canLaunchUrl 제거 및 try-catch 적용
- fetched_restaurant_json_view.dart: _launchNaverUrl try-catch 패턴 적용
- restaurant_card.dart: 카드 클릭 시 URL 열기, 상세보기 팝업 제거
- 웹 환경 호환성 개선 (platformDefault 폴백)
2026-01-28 18:54:51 +09:00
JiWoong Sul
48c22d76d0 fix(form): 폼 데이터 생성 시 URL 추출 로직 추가
- RestaurantFormData.fromControllers에 _extractNaverUrl 추가
- 공유 텍스트에서 순수 URL만 추출하여 저장
- 폼 필드 변경 시에도 올바른 URL 유지
2026-01-28 18:54:44 +09:00
JiWoong Sul
c607a52962 fix(geocoding): 주소에서 층수/상호명 제거 로직 추가
- _cleanAddress() 메서드 추가
- 건물번호 뒤 층수 정보 제거 (예: "6-4 1층" → "6-4")
- 건물번호 뒤 상호명 제거 (예: "6-4 이자카야 혼네" → "6-4")
- geocode() 호출 전 주소 정리 적용
2026-01-28 18:54:37 +09:00
23 changed files with 852 additions and 277 deletions

View File

@@ -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+) -->

View File

@@ -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>

View 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;
}

View File

@@ -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;
/// 특정 코드로 수신 대기를 시작한다.
/// 현재 광고 중인 공유 코드
String? get currentShareCode => _currentShareCode;
/// BLE 지원 여부 확인
Future<bool> get isSupported async {
if (!Platform.isAndroid && !Platform.isIOS) {
return false;
}
try {
return await FlutterBluePlus.isSupported;
} catch (_) {
return false;
}
}
/// Bluetooth 어댑터 상태 확인
Future<bool> get isBluetoothOn async {
try {
final state = await FlutterBluePlus.adapterState.first;
return state == BluetoothAdapterState.on;
} catch (_) {
return false;
}
}
// =========================================================================
// 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 Future<void>.delayed(const Duration(milliseconds: 300));
stopListening();
final shareDevice = ShareDevice(
code: code,
deviceId: 'LP-${_random.nextInt(900000) + 100000}',
discoveredAt: DateTime.now(),
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)),
),
],
),
);
_listeningDevices[code] = shareDevice;
}
/// 더 이상 수신 대기하지 않는다.
void stopListening() {
if (_listeningDevices.isEmpty) return;
final codes = List<String>.from(_listeningDevices.keys);
for (final code in codes) {
_listeningDevices.remove(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 {
await Future<void>.delayed(const Duration(seconds: 1));
return _listeningDevices.values.toList();
_discoveredDevices.clear();
// Bluetooth 상태 확인
if (!await isBluetoothOn) {
throw Exception('블루투스가 꺼져 있습니다. 블루투스를 켜주세요.');
}
/// 대상 코드로 맛집 리스트를 전송한다. 실제 BT 대신 JSON 문자열을 브로드캐스트한다.
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 payload = jsonEncode(
restaurants
.map((restaurant) => _serializeRestaurant(restaurant))
.toList(),
// 대상 디바이스 찾기
final targetDevice = _discoveredDevices.firstWhere(
(d) => d.code == targetCode,
orElse: () => throw Exception('대상 기기를 찾을 수 없습니다: $targetCode'),
);
_incomingDataController.add(payload);
final bleDevice = targetDevice.bleDevice;
if (bleDevice == null) {
throw Exception('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,
debugPrint('[BLE] 연결 시작: $targetCode');
// 연결
await bleDevice.connect(
timeout: Duration(seconds: BleConstants.connectionTimeoutSeconds),
);
_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] 연결 해제');
}
}
/// 문자열을 청크로 분할
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');
}
}

View File

@@ -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;
}
}

View File

@@ -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,
);
}
}

View File

@@ -586,7 +586,9 @@ class _CalendarScreenState extends ConsumerState<CalendarScreen>
final recoTime = recommendationRecord?.recommendationDate;
final isVisitConfirmed = visitRecord?.isConfirmed == true;
return Padding(
return SafeArea(
top: false,
child: Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 20),
child: Column(
mainAxisSize: MainAxisSize.min,
@@ -691,6 +693,7 @@ class _CalendarScreenState extends ConsumerState<CalendarScreen>
),
],
),
),
);
},
loading: () => const SizedBox(

View File

@@ -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),

View File

@@ -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),

View File

@@ -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,80 +200,14 @@ 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;
},
),
),
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(
// 네이버 지도 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,
@@ -277,8 +215,6 @@ class _AddRestaurantFormState extends State<AddRestaurantForm> {
),
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);
}
}
}

View File

@@ -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/...',

View File

@@ -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;
}
}

View File

@@ -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(
return Padding(
padding: const EdgeInsets.only(bottom: 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: const [
Icon(Icons.my_location, size: 16),
Icon(Icons.link, size: 16),
SizedBox(width: 8),
Text('좌표'),
Text('네이버 지도:'),
],
),
const SizedBox(height: 6),
Row(
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,
),
borderRadius: BorderRadius.circular(8),
color: widget.isDark
? AppColors.darkSurface
: AppColors.lightSurface,
),
child: Row(
children: [
Expanded(
child: TextFormField(
controller: widget.latitudeController,
keyboardType: const TextInputType.numberWithOptions(
decimal: true,
child: Text(
url,
style: TextStyle(
color: Colors.blue[700],
decoration: TextDecoration.underline,
),
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;
},
overflow: TextOverflow.ellipsis,
),
),
const SizedBox(width: 12),
Expanded(
child: TextFormField(
controller: widget.longitudeController,
keyboardType: const TextInputType.numberWithOptions(
decimal: true,
const SizedBox(width: 8),
Icon(
Icons.open_in_new,
size: 18,
color: Colors.blue[700],
),
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,

View File

@@ -1,8 +1,9 @@
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/core/widgets/info_row.dart';
import 'package:lunchpick/domain/entities/restaurant.dart';
import 'package:lunchpick/presentation/providers/restaurant_provider.dart';
import 'edit_restaurant_dialog.dart';
@@ -25,10 +26,13 @@ class RestaurantCard extends ConsumerWidget {
Widget build(BuildContext context, WidgetRef ref) {
final isDark = Theme.of(context).brightness == Brightness.dark;
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),
@@ -211,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 '한식':
@@ -239,47 +255,6 @@ class RestaurantCard extends ConsumerWidget {
return daysSinceVisit == 0 ? '오늘 방문' : '$daysSinceVisit일 전 방문';
}
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: [
InfoRow(
label: '카테고리',
value: '${restaurant.category} > ${restaurant.subCategory}',
isDark: isDark,
),
if (restaurant.description != null)
InfoRow(label: '설명', value: restaurant.description!, isDark: isDark),
if (restaurant.phoneNumber != null)
InfoRow(label: '전화번호', value: restaurant.phoneNumber!, isDark: isDark),
InfoRow(label: '도로명 주소', value: restaurant.roadAddress, isDark: isDark),
InfoRow(label: '지번 주소', value: restaurant.jibunAddress, isDark: isDark),
if (restaurant.lastVisitDate != null)
InfoRow(
label: '마지막 방문',
value: '${restaurant.lastVisitDate!.year}${restaurant.lastVisitDate!.month}${restaurant.lastVisitDate!.day}',
isDark: isDark,
),
],
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('닫기'),
),
],
),
);
}
void _handleMenuAction(
_RestaurantMenuAction action,
BuildContext context,

View File

@@ -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) {

View File

@@ -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;

View File

@@ -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) {

View File

@@ -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);
}
}
}

View File

@@ -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"))

View File

@@ -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:

View File

@@ -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.2+3
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

View File

@@ -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(

View File

@@ -3,6 +3,7 @@
#
list(APPEND FLUTTER_PLUGIN_LIST
ble_peripheral
geolocator_windows
permission_handler_windows
share_plus