Compare commits
10 Commits
f5a02f581e
...
codex/feat
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1349f35cfe | ||
|
|
c608b6c7df | ||
|
|
24b074ff4c | ||
|
|
5d8e1157b9 | ||
|
|
29c247abc1 | ||
|
|
e888b51875 | ||
|
|
6426d14336 | ||
|
|
b989981464 | ||
|
|
48c22d76d0 | ||
|
|
c607a52962 |
@@ -1,4 +1,7 @@
|
|||||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<!-- BLE 기능 선언 (필수 아님으로 설정) -->
|
||||||
|
<uses-feature android:name="android.hardware.bluetooth_le" android:required="false" />
|
||||||
|
|
||||||
<!-- 알림 권한 (Android 13+) -->
|
<!-- 알림 권한 (Android 13+) -->
|
||||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||||
<!-- 정확한 알람 권한 (Android 12+) -->
|
<!-- 정확한 알람 권한 (Android 12+) -->
|
||||||
|
|||||||
@@ -54,6 +54,10 @@
|
|||||||
<string>맛집과의 거리 계산을 위해 위치 정보가 필요합니다.</string>
|
<string>맛집과의 거리 계산을 위해 위치 정보가 필요합니다.</string>
|
||||||
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
|
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
|
||||||
<string>맛집과의 거리 계산을 위해 위치 정보가 필요합니다.</string>
|
<string>맛집과의 거리 계산을 위해 위치 정보가 필요합니다.</string>
|
||||||
|
<key>NSBluetoothAlwaysUsageDescription</key>
|
||||||
|
<string>맛집 리스트를 다른 사용자와 공유하기 위해 블루투스 권한이 필요합니다.</string>
|
||||||
|
<key>NSBluetoothPeripheralUsageDescription</key>
|
||||||
|
<string>맛집 리스트를 다른 사용자로부터 받기 위해 블루투스 권한이 필요합니다.</string>
|
||||||
<key>GADApplicationIdentifier</key>
|
<key>GADApplicationIdentifier</key>
|
||||||
<string>$(GAD_APPLICATION_ID)</string>
|
<string>$(GAD_APPLICATION_ID)</string>
|
||||||
</dict>
|
</dict>
|
||||||
|
|||||||
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:async';
|
||||||
import 'dart:convert';
|
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/restaurant.dart';
|
||||||
import 'package:lunchpick/domain/entities/share_device.dart';
|
import 'package:lunchpick/domain/entities/share_device.dart';
|
||||||
|
|
||||||
/// 실제 Bluetooth 통신을 대체하는 간단한 모의(Mock) 서비스.
|
/// BLE 기반 맛집 리스트 공유 서비스
|
||||||
|
///
|
||||||
|
/// - Receiver (공유받기): ble_peripheral 패키지로 GATT Server 역할
|
||||||
|
/// - Sender (공유하기): flutter_blue_plus 패키지로 Central 역할
|
||||||
class BluetoothService {
|
class BluetoothService {
|
||||||
|
// === Peripheral (Receiver) 관련 ===
|
||||||
|
bool _isPeripheralInitialized = false;
|
||||||
|
String? _currentShareCode;
|
||||||
final _incomingDataController = StreamController<String>.broadcast();
|
final _incomingDataController = StreamController<String>.broadcast();
|
||||||
final Map<String, ShareDevice> _listeningDevices = {};
|
final _receivedChunks = <int, String>{};
|
||||||
final Random _random = Random();
|
// 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;
|
Stream<String> get onDataReceived => _incomingDataController.stream;
|
||||||
|
|
||||||
/// 특정 코드로 수신 대기를 시작한다.
|
/// 현재 광고 중인 공유 코드
|
||||||
Future<void> startListening(String code) async {
|
String? get currentShareCode => _currentShareCode;
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 더 이상 수신 대기하지 않는다.
|
/// BLE 지원 여부 확인
|
||||||
void stopListening() {
|
Future<bool> get isSupported async {
|
||||||
if (_listeningDevices.isEmpty) return;
|
if (!Platform.isAndroid && !Platform.isIOS) {
|
||||||
final codes = List<String>.from(_listeningDevices.keys);
|
return false;
|
||||||
for (final code in codes) {
|
}
|
||||||
_listeningDevices.remove(code);
|
try {
|
||||||
|
return await FlutterBluePlus.isSupported;
|
||||||
|
} catch (_) {
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 현재 주변에서 수신 대기 중인 기기 목록을 반환한다.
|
/// Bluetooth 어댑터 상태 확인
|
||||||
Future<List<ShareDevice>> scanNearbyDevices() async {
|
Future<bool> get isBluetoothOn async {
|
||||||
await Future<void>.delayed(const Duration(seconds: 1));
|
try {
|
||||||
return _listeningDevices.values.toList();
|
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(
|
Future<void> sendRestaurantList(
|
||||||
String targetCode,
|
String targetCode,
|
||||||
List<Restaurant> restaurants,
|
List<Restaurant> restaurants,
|
||||||
) async {
|
) async {
|
||||||
await Future<void>.delayed(const Duration(seconds: 1));
|
// 대상 디바이스 찾기
|
||||||
if (!_listeningDevices.containsKey(targetCode)) {
|
final targetDevice = _discoveredDevices.firstWhere(
|
||||||
throw Exception('해당 코드를 찾을 수 없습니다.');
|
(d) => d.code == targetCode,
|
||||||
|
orElse: () => throw Exception('대상 기기를 찾을 수 없습니다: $targetCode'),
|
||||||
|
);
|
||||||
|
|
||||||
|
final bleDevice = targetDevice.bleDevice;
|
||||||
|
if (bleDevice == null) {
|
||||||
|
throw Exception('BLE 디바이스 정보가 없습니다.');
|
||||||
}
|
}
|
||||||
|
|
||||||
final payload = jsonEncode(
|
debugPrint('[BLE] 연결 시작: $targetCode');
|
||||||
restaurants
|
|
||||||
.map((restaurant) => _serializeRestaurant(restaurant))
|
// 연결
|
||||||
.toList(),
|
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 {
|
List<String> _splitIntoChunks(String data, int chunkSize) {
|
||||||
'id': restaurant.id,
|
final chunks = <String>[];
|
||||||
'name': restaurant.name,
|
for (var i = 0; i < data.length; i += chunkSize) {
|
||||||
'category': restaurant.category,
|
final end = (i + chunkSize > data.length) ? data.length : i + chunkSize;
|
||||||
'subCategory': restaurant.subCategory,
|
chunks.add(data.substring(i, end));
|
||||||
'description': restaurant.description,
|
}
|
||||||
'phoneNumber': restaurant.phoneNumber,
|
return chunks;
|
||||||
'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,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 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() {
|
void dispose() {
|
||||||
_incomingDataController.close();
|
_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 {
|
Future<({double latitude, double longitude})?> geocode(String address) async {
|
||||||
if (address.trim().isEmpty) return null;
|
if (address.trim().isEmpty) return null;
|
||||||
|
|
||||||
|
// 주소 전처리: 상세 주소(층수, 상호명 등) 제거
|
||||||
|
final cleanedAddress = _cleanAddress(address);
|
||||||
|
|
||||||
// 1차: VWorld 지오코딩 시도 (키가 존재할 때만)
|
// 1차: VWorld 지오코딩 시도 (키가 존재할 때만)
|
||||||
final vworldResult = await _geocodeWithVworld(address);
|
final vworldResult = await _geocodeWithVworld(cleanedAddress);
|
||||||
if (vworldResult != null) {
|
if (vworldResult != null) {
|
||||||
return vworldResult;
|
return vworldResult;
|
||||||
}
|
}
|
||||||
@@ -26,7 +29,7 @@ class GeocodingService {
|
|||||||
// 2차: Nominatim (fallback)
|
// 2차: Nominatim (fallback)
|
||||||
try {
|
try {
|
||||||
final uri = Uri.parse(
|
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 헤더를 요구한다.
|
// Nominatim은 User-Agent 헤더를 요구한다.
|
||||||
@@ -121,4 +124,39 @@ class GeocodingService {
|
|||||||
return null;
|
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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,68 @@
|
|||||||
|
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
|
||||||
|
|
||||||
|
/// BLE 공유를 위한 디바이스 정보
|
||||||
class ShareDevice {
|
class ShareDevice {
|
||||||
|
/// 공유 코드 (6자리 숫자)
|
||||||
final String code;
|
final String code;
|
||||||
|
|
||||||
|
/// 디바이스 고유 ID
|
||||||
final String deviceId;
|
final String deviceId;
|
||||||
|
|
||||||
|
/// BLE Remote ID (MAC 주소 또는 UUID)
|
||||||
|
final String? remoteId;
|
||||||
|
|
||||||
|
/// 신호 강도 (RSSI)
|
||||||
|
final int? rssi;
|
||||||
|
|
||||||
|
/// 발견 시각
|
||||||
final DateTime discoveredAt;
|
final DateTime discoveredAt;
|
||||||
|
|
||||||
|
/// flutter_blue_plus BluetoothDevice 참조
|
||||||
|
/// 실제 BLE 연결 시 사용
|
||||||
|
final BluetoothDevice? bleDevice;
|
||||||
|
|
||||||
ShareDevice({
|
ShareDevice({
|
||||||
required this.code,
|
required this.code,
|
||||||
required this.deviceId,
|
required this.deviceId,
|
||||||
|
this.remoteId,
|
||||||
|
this.rssi,
|
||||||
required this.discoveredAt,
|
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,
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -586,9 +586,11 @@ class _CalendarScreenState extends ConsumerState<CalendarScreen>
|
|||||||
final recoTime = recommendationRecord?.recommendationDate;
|
final recoTime = recommendationRecord?.recommendationDate;
|
||||||
final isVisitConfirmed = visitRecord?.isConfirmed == true;
|
final isVisitConfirmed = visitRecord?.isConfirmed == true;
|
||||||
|
|
||||||
return Padding(
|
return SafeArea(
|
||||||
padding: const EdgeInsets.fromLTRB(16, 12, 16, 20),
|
top: false,
|
||||||
child: Column(
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(16, 12, 16, 20),
|
||||||
|
child: Column(
|
||||||
mainAxisSize: MainAxisSize.min,
|
mainAxisSize: MainAxisSize.min,
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
children: [
|
children: [
|
||||||
@@ -689,7 +691,8 @@ class _CalendarScreenState extends ConsumerState<CalendarScreen>
|
|||||||
label: const Text('추천 방문 기록으로 저장'),
|
label: const Text('추천 방문 기록으로 저장'),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -27,6 +27,33 @@ class RecommendationRecordCard extends ConsumerWidget {
|
|||||||
return '$hour:$minute';
|
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
|
@override
|
||||||
Widget build(BuildContext context, WidgetRef ref) {
|
Widget build(BuildContext context, WidgetRef ref) {
|
||||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||||
@@ -166,7 +193,7 @@ class RecommendationRecordCard extends ConsumerWidget {
|
|||||||
Align(
|
Align(
|
||||||
alignment: Alignment.centerRight,
|
alignment: Alignment.centerRight,
|
||||||
child: TextButton(
|
child: TextButton(
|
||||||
onPressed: onDelete,
|
onPressed: () => _showDeleteConfirmation(context),
|
||||||
style: TextButton.styleFrom(
|
style: TextButton.styleFrom(
|
||||||
foregroundColor: Colors.redAccent,
|
foregroundColor: Colors.redAccent,
|
||||||
padding: const EdgeInsets.only(top: 6),
|
padding: const EdgeInsets.only(top: 6),
|
||||||
|
|||||||
@@ -124,7 +124,7 @@ class _AddRestaurantDialogState extends ConsumerState<AddRestaurantDialog> {
|
|||||||
_jibunAddressController.text = formData.jibunAddress;
|
_jibunAddressController.text = formData.jibunAddress;
|
||||||
_latitudeController.text = formData.latitude;
|
_latitudeController.text = formData.latitude;
|
||||||
_longitudeController.text = formData.longitude;
|
_longitudeController.text = formData.longitude;
|
||||||
_naverUrlController.text = formData.naverUrl;
|
// naverUrlController는 사용자 입력을 그대로 유지
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _saveRestaurant() async {
|
Future<void> _saveRestaurant() async {
|
||||||
@@ -234,6 +234,7 @@ class _AddRestaurantDialogState extends ConsumerState<AddRestaurantDialog> {
|
|||||||
longitudeController: _longitudeController,
|
longitudeController: _longitudeController,
|
||||||
naverUrlController: _naverUrlController,
|
naverUrlController: _naverUrlController,
|
||||||
onFieldChanged: _onFormDataChanged,
|
onFieldChanged: _onFormDataChanged,
|
||||||
|
naverUrl: state.formData.naverUrl,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 24),
|
const SizedBox(height: 24),
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
import 'package:flutter/foundation.dart';
|
import 'package:flutter/foundation.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:url_launcher/url_launcher.dart';
|
||||||
|
|
||||||
import '../../../services/restaurant_form_validator.dart';
|
import '../../../services/restaurant_form_validator.dart';
|
||||||
|
|
||||||
/// 식당 추가 폼 위젯
|
/// 식당 추가 폼 위젯
|
||||||
@@ -18,6 +20,7 @@ class AddRestaurantForm extends StatefulWidget {
|
|||||||
final List<String> categories;
|
final List<String> categories;
|
||||||
final List<String> subCategories;
|
final List<String> subCategories;
|
||||||
final String geocodingStatus;
|
final String geocodingStatus;
|
||||||
|
final TextEditingController? naverUrlController; // 네이버 지도 URL 입력
|
||||||
|
|
||||||
const AddRestaurantForm({
|
const AddRestaurantForm({
|
||||||
super.key,
|
super.key,
|
||||||
@@ -35,6 +38,7 @@ class AddRestaurantForm extends StatefulWidget {
|
|||||||
this.categories = const <String>[],
|
this.categories = const <String>[],
|
||||||
this.subCategories = const <String>[],
|
this.subCategories = const <String>[],
|
||||||
this.geocodingStatus = '',
|
this.geocodingStatus = '',
|
||||||
|
this.naverUrlController,
|
||||||
});
|
});
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@@ -196,90 +200,22 @@ class _AddRestaurantFormState extends State<AddRestaurantForm> {
|
|||||||
),
|
),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
|
|
||||||
// 위도/경도 입력
|
// 네이버 지도 URL (컨트롤러가 있는 경우 항상 표시)
|
||||||
Row(
|
if (widget.naverUrlController != null)
|
||||||
children: [
|
_buildNaverUrlField(context),
|
||||||
Expanded(
|
|
||||||
child: TextFormField(
|
if (widget.geocodingStatus.isNotEmpty)
|
||||||
controller: widget.latitudeController,
|
Padding(
|
||||||
keyboardType: const TextInputType.numberWithOptions(
|
padding: const EdgeInsets.only(top: 8),
|
||||||
decimal: true,
|
child: Text(
|
||||||
),
|
widget.geocodingStatus,
|
||||||
decoration: InputDecoration(
|
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||||
labelText: '위도',
|
color: Colors.blueGrey,
|
||||||
hintText: '37.5665',
|
fontWeight: FontWeight.w600,
|
||||||
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,
|
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,
|
minLines: 1,
|
||||||
maxLines: 6,
|
maxLines: 6,
|
||||||
decoration: InputDecoration(
|
decoration: InputDecoration(
|
||||||
labelText: '네이버 지도 URL',
|
labelText: '네이버 지도 링크',
|
||||||
hintText: kIsWeb
|
hintText: kIsWeb
|
||||||
? 'https://map.naver.com/...'
|
? 'https://map.naver.com/...'
|
||||||
: 'https://naver.me/...',
|
: 'https://naver.me/...',
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ class _EditRestaurantDialogState extends ConsumerState<EditRestaurantDialog> {
|
|||||||
late final TextEditingController _jibunAddressController;
|
late final TextEditingController _jibunAddressController;
|
||||||
late final TextEditingController _latitudeController;
|
late final TextEditingController _latitudeController;
|
||||||
late final TextEditingController _longitudeController;
|
late final TextEditingController _longitudeController;
|
||||||
|
late final TextEditingController _naverUrlController;
|
||||||
|
|
||||||
bool _isSaving = false;
|
bool _isSaving = false;
|
||||||
late final String _originalRoadAddress;
|
late final String _originalRoadAddress;
|
||||||
@@ -64,6 +65,9 @@ class _EditRestaurantDialogState extends ConsumerState<EditRestaurantDialog> {
|
|||||||
_longitudeController = TextEditingController(
|
_longitudeController = TextEditingController(
|
||||||
text: restaurant.longitude.toString(),
|
text: restaurant.longitude.toString(),
|
||||||
);
|
);
|
||||||
|
_naverUrlController = TextEditingController(
|
||||||
|
text: restaurant.naverUrl ?? '',
|
||||||
|
);
|
||||||
_originalRoadAddress = restaurant.roadAddress;
|
_originalRoadAddress = restaurant.roadAddress;
|
||||||
_originalJibunAddress = restaurant.jibunAddress;
|
_originalJibunAddress = restaurant.jibunAddress;
|
||||||
}
|
}
|
||||||
@@ -79,6 +83,7 @@ class _EditRestaurantDialogState extends ConsumerState<EditRestaurantDialog> {
|
|||||||
_jibunAddressController.dispose();
|
_jibunAddressController.dispose();
|
||||||
_latitudeController.dispose();
|
_latitudeController.dispose();
|
||||||
_longitudeController.dispose();
|
_longitudeController.dispose();
|
||||||
|
_naverUrlController.dispose();
|
||||||
super.dispose();
|
super.dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -107,6 +112,9 @@ class _EditRestaurantDialogState extends ConsumerState<EditRestaurantDialog> {
|
|||||||
_latitudeController.text = coords.latitude.toString();
|
_latitudeController.text = coords.latitude.toString();
|
||||||
_longitudeController.text = coords.longitude.toString();
|
_longitudeController.text = coords.longitude.toString();
|
||||||
|
|
||||||
|
// URL 추출: 공유 텍스트에서 URL만 추출
|
||||||
|
final extractedUrl = _extractNaverUrl(_naverUrlController.text.trim());
|
||||||
|
|
||||||
final updatedRestaurant = widget.restaurant.copyWith(
|
final updatedRestaurant = widget.restaurant.copyWith(
|
||||||
name: _nameController.text.trim(),
|
name: _nameController.text.trim(),
|
||||||
category: _categoryController.text.trim(),
|
category: _categoryController.text.trim(),
|
||||||
@@ -125,6 +133,7 @@ class _EditRestaurantDialogState extends ConsumerState<EditRestaurantDialog> {
|
|||||||
: _jibunAddressController.text.trim(),
|
: _jibunAddressController.text.trim(),
|
||||||
latitude: coords.latitude,
|
latitude: coords.latitude,
|
||||||
longitude: coords.longitude,
|
longitude: coords.longitude,
|
||||||
|
naverUrl: extractedUrl.isEmpty ? null : extractedUrl,
|
||||||
updatedAt: DateTime.now(),
|
updatedAt: DateTime.now(),
|
||||||
needsAddressVerification: coords.usedCurrentLocation,
|
needsAddressVerification: coords.usedCurrentLocation,
|
||||||
);
|
);
|
||||||
@@ -201,6 +210,7 @@ class _EditRestaurantDialogState extends ConsumerState<EditRestaurantDialog> {
|
|||||||
onFieldChanged: _onFieldChanged,
|
onFieldChanged: _onFieldChanged,
|
||||||
categories: categories,
|
categories: categories,
|
||||||
subCategories: subCategories,
|
subCategories: subCategories,
|
||||||
|
naverUrlController: _naverUrlController,
|
||||||
),
|
),
|
||||||
const SizedBox(height: 24),
|
const SizedBox(height: 24),
|
||||||
Row(
|
Row(
|
||||||
@@ -288,4 +298,17 @@ class _EditRestaurantDialogState extends ConsumerState<EditRestaurantDialog> {
|
|||||||
usedCurrentLocation: true,
|
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:flutter/material.dart';
|
||||||
|
import 'package:url_launcher/url_launcher.dart';
|
||||||
|
|
||||||
import '../../../../core/constants/app_colors.dart';
|
import '../../../../core/constants/app_colors.dart';
|
||||||
import '../../../../core/constants/app_typography.dart';
|
import '../../../../core/constants/app_typography.dart';
|
||||||
@@ -17,6 +18,7 @@ class FetchedRestaurantJsonView extends StatefulWidget {
|
|||||||
final TextEditingController longitudeController;
|
final TextEditingController longitudeController;
|
||||||
final TextEditingController naverUrlController;
|
final TextEditingController naverUrlController;
|
||||||
final ValueChanged<String> onFieldChanged;
|
final ValueChanged<String> onFieldChanged;
|
||||||
|
final String? naverUrl; // 순수 URL (클릭 가능한 링크용)
|
||||||
|
|
||||||
const FetchedRestaurantJsonView({
|
const FetchedRestaurantJsonView({
|
||||||
super.key,
|
super.key,
|
||||||
@@ -32,6 +34,7 @@ class FetchedRestaurantJsonView extends StatefulWidget {
|
|||||||
required this.longitudeController,
|
required this.longitudeController,
|
||||||
required this.naverUrlController,
|
required this.naverUrlController,
|
||||||
required this.onFieldChanged,
|
required this.onFieldChanged,
|
||||||
|
this.naverUrl,
|
||||||
});
|
});
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@@ -126,7 +129,7 @@ class _FetchedRestaurantJsonViewState extends State<FetchedRestaurantJsonView> {
|
|||||||
controller: widget.jibunAddressController,
|
controller: widget.jibunAddressController,
|
||||||
icon: Icons.map,
|
icon: Icons.map,
|
||||||
),
|
),
|
||||||
_buildCoordinateFields(context),
|
_buildNaverUrlField(context),
|
||||||
_buildJsonField(
|
_buildJsonField(
|
||||||
context,
|
context,
|
||||||
label: '전화번호',
|
label: '전화번호',
|
||||||
@@ -154,78 +157,79 @@ class _FetchedRestaurantJsonViewState extends State<FetchedRestaurantJsonView> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget _buildCoordinateFields(BuildContext context) {
|
Widget _buildNaverUrlField(BuildContext context) {
|
||||||
final border = OutlineInputBorder(borderRadius: BorderRadius.circular(8));
|
final url = widget.naverUrl ?? '';
|
||||||
|
if (url.isEmpty) return const SizedBox.shrink();
|
||||||
|
|
||||||
return Column(
|
return Padding(
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
padding: const EdgeInsets.only(bottom: 12),
|
||||||
children: [
|
child: Column(
|
||||||
Row(
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
children: const [
|
children: [
|
||||||
Icon(Icons.my_location, size: 16),
|
Row(
|
||||||
SizedBox(width: 8),
|
children: const [
|
||||||
Text('좌표'),
|
Icon(Icons.link, size: 16),
|
||||||
],
|
SizedBox(width: 8),
|
||||||
),
|
Text('네이버 지도:'),
|
||||||
const SizedBox(height: 6),
|
],
|
||||||
Row(
|
),
|
||||||
children: [
|
const SizedBox(height: 6),
|
||||||
Expanded(
|
InkWell(
|
||||||
child: TextFormField(
|
onTap: () => _launchNaverUrl(url),
|
||||||
controller: widget.latitudeController,
|
borderRadius: BorderRadius.circular(8),
|
||||||
keyboardType: const TextInputType.numberWithOptions(
|
child: Container(
|
||||||
decimal: true,
|
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(
|
borderRadius: BorderRadius.circular(8),
|
||||||
labelText: '위도',
|
color: widget.isDark
|
||||||
border: border,
|
? AppColors.darkSurface
|
||||||
isDense: true,
|
: AppColors.lightSurface,
|
||||||
),
|
),
|
||||||
onChanged: widget.onFieldChanged,
|
child: Row(
|
||||||
validator: (value) {
|
children: [
|
||||||
if (value != null && value.isNotEmpty) {
|
Expanded(
|
||||||
final latitude = double.tryParse(value);
|
child: Text(
|
||||||
if (latitude == null || latitude < -90 || latitude > 90) {
|
url,
|
||||||
return '올바른 위도값을 입력해주세요';
|
style: TextStyle(
|
||||||
}
|
color: Colors.blue[700],
|
||||||
}
|
decoration: TextDecoration.underline,
|
||||||
return null;
|
),
|
||||||
},
|
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) {
|
Widget _buildCategoryField(BuildContext context) {
|
||||||
return RawAutocomplete<String>(
|
return RawAutocomplete<String>(
|
||||||
textEditingController: widget.categoryController,
|
textEditingController: widget.categoryController,
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:flutter_riverpod/flutter_riverpod.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_colors.dart';
|
||||||
import 'package:lunchpick/core/constants/app_typography.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/domain/entities/restaurant.dart';
|
||||||
import 'package:lunchpick/presentation/providers/restaurant_provider.dart';
|
import 'package:lunchpick/presentation/providers/restaurant_provider.dart';
|
||||||
import 'edit_restaurant_dialog.dart';
|
import 'edit_restaurant_dialog.dart';
|
||||||
@@ -25,10 +26,13 @@ class RestaurantCard extends ConsumerWidget {
|
|||||||
Widget build(BuildContext context, WidgetRef ref) {
|
Widget build(BuildContext context, WidgetRef ref) {
|
||||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||||
|
|
||||||
|
final hasNaverUrl = restaurant.naverUrl != null &&
|
||||||
|
restaurant.naverUrl!.isNotEmpty;
|
||||||
|
|
||||||
return Card(
|
return Card(
|
||||||
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||||
child: InkWell(
|
child: InkWell(
|
||||||
onTap: () => _showRestaurantDetail(context, isDark),
|
onTap: hasNaverUrl ? () => _openNaverUrl(restaurant.naverUrl!) : null,
|
||||||
borderRadius: BorderRadius.circular(12),
|
borderRadius: BorderRadius.circular(12),
|
||||||
child: Padding(
|
child: Padding(
|
||||||
padding: const EdgeInsets.all(16),
|
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) {
|
IconData _getCategoryIcon(String category) {
|
||||||
switch (category) {
|
switch (category) {
|
||||||
case '한식':
|
case '한식':
|
||||||
@@ -239,47 +255,6 @@ class RestaurantCard extends ConsumerWidget {
|
|||||||
return daysSinceVisit == 0 ? '오늘 방문' : '$daysSinceVisit일 전 방문';
|
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(
|
void _handleMenuAction(
|
||||||
_RestaurantMenuAction action,
|
_RestaurantMenuAction action,
|
||||||
BuildContext context,
|
BuildContext context,
|
||||||
|
|||||||
@@ -211,11 +211,11 @@ class _ShareScreenState extends ConsumerState<ShareScreen> {
|
|||||||
Text('이 코드를 상대방에게 알려주세요', style: AppTypography.caption(isDark)),
|
Text('이 코드를 상대방에게 알려주세요', style: AppTypography.caption(isDark)),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
TextButton.icon(
|
TextButton.icon(
|
||||||
onPressed: () {
|
onPressed: () async {
|
||||||
setState(() {
|
setState(() {
|
||||||
_shareCode = null;
|
_shareCode = null;
|
||||||
});
|
});
|
||||||
ref.read(bluetoothServiceProvider).stopListening();
|
await ref.read(bluetoothServiceProvider).stopListening();
|
||||||
},
|
},
|
||||||
icon: const Icon(Icons.close),
|
icon: const Icon(Icons.close),
|
||||||
label: const Text('취소'),
|
label: const Text('취소'),
|
||||||
@@ -551,7 +551,7 @@ class _ShareScreenState extends ConsumerState<ShareScreen> {
|
|||||||
setState(() {
|
setState(() {
|
||||||
_shareCode = null;
|
_shareCode = null;
|
||||||
});
|
});
|
||||||
ref.read(bluetoothServiceProvider).stopListening();
|
await ref.read(bluetoothServiceProvider).stopListening();
|
||||||
}
|
}
|
||||||
|
|
||||||
void _showLoadingDialog(String message) {
|
void _showLoadingDialog(String message) {
|
||||||
|
|||||||
@@ -166,8 +166,8 @@ class RecommendationNotifier extends StateNotifier<AsyncValue<Restaurant?>> {
|
|||||||
required List<String> selectedCategories,
|
required List<String> selectedCategories,
|
||||||
List<String> excludedRestaurantIds = const [],
|
List<String> excludedRestaurantIds = const [],
|
||||||
}) async {
|
}) async {
|
||||||
// 현재 위치 가져오기
|
// 현재 위치 가져오기 (StreamProvider에서 최신 위치 사용)
|
||||||
final location = await _ref.read(currentLocationProvider.future);
|
final location = _ref.read(currentLocationWithFallbackProvider).valueOrNull;
|
||||||
if (location == null) {
|
if (location == null) {
|
||||||
throw Exception('위치 정보를 가져올 수 없습니다');
|
throw Exception('위치 정보를 가져올 수 없습니다');
|
||||||
}
|
}
|
||||||
@@ -382,8 +382,8 @@ class EnhancedRecommendationNotifier
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 현재 위치 가져오기
|
// 현재 위치 가져오기 (StreamProvider에서 최신 위치 사용)
|
||||||
final location = await _ref.read(currentLocationProvider.future);
|
final location = _ref.read(currentLocationWithFallbackProvider).valueOrNull;
|
||||||
if (location == null) {
|
if (location == null) {
|
||||||
state = state.copyWith(error: '위치 정보를 가져올 수 없습니다', isLoading: false);
|
state = state.copyWith(error: '위치 정보를 가져올 수 없습니다', isLoading: false);
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -31,6 +31,9 @@ final monthlyVisitStatsProvider =
|
|||||||
ref,
|
ref,
|
||||||
params,
|
params,
|
||||||
) async {
|
) async {
|
||||||
|
// visitRecordsProvider를 watch하여 방문 기록 변경 시 자동 갱신
|
||||||
|
await ref.watch(visitRecordsProvider.future);
|
||||||
|
|
||||||
final repository = ref.watch(visitRepositoryProvider);
|
final repository = ref.watch(visitRepositoryProvider);
|
||||||
return repository.getMonthlyVisitStats(params.year, params.month);
|
return repository.getMonthlyVisitStats(params.year, params.month);
|
||||||
});
|
});
|
||||||
@@ -41,13 +44,19 @@ final monthlyCategoryVisitStatsProvider =
|
|||||||
ref,
|
ref,
|
||||||
params,
|
params,
|
||||||
) async {
|
) async {
|
||||||
final repository = ref.watch(visitRepositoryProvider);
|
// visitRecordsProvider를 watch하여 방문 기록 변경 시 자동 갱신
|
||||||
|
final allRecords = await ref.watch(visitRecordsProvider.future);
|
||||||
final restaurants = await ref.watch(restaurantListProvider.future);
|
final restaurants = await ref.watch(restaurantListProvider.future);
|
||||||
|
|
||||||
final records = await repository.getVisitRecordsByDateRange(
|
// 해당 월의 기록만 필터링
|
||||||
startDate: DateTime(params.year, params.month, 1),
|
final startDate = DateTime(params.year, params.month, 1);
|
||||||
endDate: DateTime(params.year, params.month + 1, 0),
|
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>{};
|
final categoryCount = <String, int>{};
|
||||||
for (final record in records) {
|
for (final record in records) {
|
||||||
|
|||||||
@@ -8,6 +8,15 @@ import '../providers/di_providers.dart';
|
|||||||
import '../providers/restaurant_provider.dart';
|
import '../providers/restaurant_provider.dart';
|
||||||
import '../providers/location_provider.dart';
|
import '../providers/location_provider.dart';
|
||||||
|
|
||||||
|
/// 지오코딩 실패 시 발생하는 예외
|
||||||
|
class GeocodingException implements Exception {
|
||||||
|
final String message;
|
||||||
|
const GeocodingException(this.message);
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() => message;
|
||||||
|
}
|
||||||
|
|
||||||
/// 식당 추가 화면의 상태 모델
|
/// 식당 추가 화면의 상태 모델
|
||||||
class AddRestaurantState {
|
class AddRestaurantState {
|
||||||
final bool isLoading;
|
final bool isLoading;
|
||||||
@@ -128,10 +137,23 @@ class RestaurantFormData {
|
|||||||
jibunAddress: jibunAddressController.text.trim(),
|
jibunAddress: jibunAddressController.text.trim(),
|
||||||
latitude: latitudeController.text.trim(),
|
latitude: latitudeController.text.trim(),
|
||||||
longitude: longitudeController.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 엔티티로부터 폼 데이터 생성
|
/// Restaurant 엔티티로부터 폼 데이터 생성
|
||||||
factory RestaurantFormData.fromRestaurant(Restaurant restaurant) {
|
factory RestaurantFormData.fromRestaurant(Restaurant restaurant) {
|
||||||
return RestaurantFormData(
|
return RestaurantFormData(
|
||||||
@@ -351,7 +373,11 @@ class AddRestaurantViewModel extends StateNotifier<AddRestaurantState> {
|
|||||||
state = state.copyWith(isLoading: false);
|
state = state.copyWith(isLoading: false);
|
||||||
return true;
|
return true;
|
||||||
} catch (e) {
|
} 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;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -474,12 +500,9 @@ class AddRestaurantViewModel extends StateNotifier<AddRestaurantState> {
|
|||||||
);
|
);
|
||||||
|
|
||||||
if (!allowFallbackWhenGeocodingFails) {
|
if (!allowFallbackWhenGeocodingFails) {
|
||||||
state = state.copyWith(
|
const userMessage = '위치 정보를 가져올 수 없습니다. 주소를 확인해주세요.';
|
||||||
errorMessage:
|
state = state.copyWith(errorMessage: userMessage);
|
||||||
'주소가 지도에서 인식되지 않습니다. '
|
throw GeocodingException(userMessage);
|
||||||
'도로명 주소 전체를 정확히 입력했는지 확인해 주세요.',
|
|
||||||
);
|
|
||||||
throw Exception('지오코딩 실패: $address');
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@
|
|||||||
import FlutterMacOS
|
import FlutterMacOS
|
||||||
import Foundation
|
import Foundation
|
||||||
|
|
||||||
|
import ble_peripheral
|
||||||
import flutter_blue_plus_darwin
|
import flutter_blue_plus_darwin
|
||||||
import flutter_local_notifications
|
import flutter_local_notifications
|
||||||
import geolocator_apple
|
import geolocator_apple
|
||||||
@@ -15,6 +16,7 @@ import url_launcher_macos
|
|||||||
import webview_flutter_wkwebview
|
import webview_flutter_wkwebview
|
||||||
|
|
||||||
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
|
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
|
||||||
|
BlePeripheralPlugin.register(with: registry.registrar(forPlugin: "BlePeripheralPlugin"))
|
||||||
FlutterBluePlusPlugin.register(with: registry.registrar(forPlugin: "FlutterBluePlusPlugin"))
|
FlutterBluePlusPlugin.register(with: registry.registrar(forPlugin: "FlutterBluePlusPlugin"))
|
||||||
FlutterLocalNotificationsPlugin.register(with: registry.registrar(forPlugin: "FlutterLocalNotificationsPlugin"))
|
FlutterLocalNotificationsPlugin.register(with: registry.registrar(forPlugin: "FlutterLocalNotificationsPlugin"))
|
||||||
GeolocatorPlugin.register(with: registry.registrar(forPlugin: "GeolocatorPlugin"))
|
GeolocatorPlugin.register(with: registry.registrar(forPlugin: "GeolocatorPlugin"))
|
||||||
|
|||||||
@@ -49,6 +49,14 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "2.13.0"
|
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:
|
bluez:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
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
|
# 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
|
# 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.
|
# 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:
|
environment:
|
||||||
sdk: ^3.8.1
|
sdk: ^3.8.1
|
||||||
@@ -63,6 +63,7 @@ dependencies:
|
|||||||
|
|
||||||
# Bluetooth
|
# Bluetooth
|
||||||
flutter_blue_plus: ^1.31.0
|
flutter_blue_plus: ^1.31.0
|
||||||
|
ble_peripheral: ^2.4.0 # Peripheral 역할 (Receiver)
|
||||||
|
|
||||||
# Utilities
|
# Utilities
|
||||||
uuid: ^4.2.1
|
uuid: ^4.2.1
|
||||||
|
|||||||
@@ -6,12 +6,15 @@
|
|||||||
|
|
||||||
#include "generated_plugin_registrant.h"
|
#include "generated_plugin_registrant.h"
|
||||||
|
|
||||||
|
#include <ble_peripheral/ble_peripheral_plugin_c_api.h>
|
||||||
#include <geolocator_windows/geolocator_windows.h>
|
#include <geolocator_windows/geolocator_windows.h>
|
||||||
#include <permission_handler_windows/permission_handler_windows_plugin.h>
|
#include <permission_handler_windows/permission_handler_windows_plugin.h>
|
||||||
#include <share_plus/share_plus_windows_plugin_c_api.h>
|
#include <share_plus/share_plus_windows_plugin_c_api.h>
|
||||||
#include <url_launcher_windows/url_launcher_windows.h>
|
#include <url_launcher_windows/url_launcher_windows.h>
|
||||||
|
|
||||||
void RegisterPlugins(flutter::PluginRegistry* registry) {
|
void RegisterPlugins(flutter::PluginRegistry* registry) {
|
||||||
|
BlePeripheralPluginCApiRegisterWithRegistrar(
|
||||||
|
registry->GetRegistrarForPlugin("BlePeripheralPluginCApi"));
|
||||||
GeolocatorWindowsRegisterWithRegistrar(
|
GeolocatorWindowsRegisterWithRegistrar(
|
||||||
registry->GetRegistrarForPlugin("GeolocatorWindows"));
|
registry->GetRegistrarForPlugin("GeolocatorWindows"));
|
||||||
PermissionHandlerWindowsPluginRegisterWithRegistrar(
|
PermissionHandlerWindowsPluginRegisterWithRegistrar(
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
#
|
#
|
||||||
|
|
||||||
list(APPEND FLUTTER_PLUGIN_LIST
|
list(APPEND FLUTTER_PLUGIN_LIST
|
||||||
|
ble_peripheral
|
||||||
geolocator_windows
|
geolocator_windows
|
||||||
permission_handler_windows
|
permission_handler_windows
|
||||||
share_plus
|
share_plus
|
||||||
|
|||||||
Reference in New Issue
Block a user