Compare commits

...

4 Commits

Author SHA1 Message Date
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
8 changed files with 264 additions and 202 deletions

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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