Compare commits
22 Commits
99ad8a3bd5
...
codex/feat
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1349f35cfe | ||
|
|
c608b6c7df | ||
|
|
24b074ff4c | ||
|
|
5d8e1157b9 | ||
|
|
29c247abc1 | ||
|
|
e888b51875 | ||
|
|
6426d14336 | ||
|
|
b989981464 | ||
|
|
48c22d76d0 | ||
|
|
c607a52962 | ||
|
|
f5a02f581e | ||
|
|
1cbf9ca82c | ||
|
|
a9fb5695fb | ||
|
|
6f45c7b456 | ||
|
|
21941443ee | ||
|
|
32e25aeb07 | ||
|
|
42c609c57a | ||
|
|
cf7e187985 | ||
|
|
0c6b10d4f6 | ||
|
|
753f578504 | ||
|
|
887f1ad6fe | ||
|
|
0e45616dfd |
387
CLAUDE.md
387
CLAUDE.md
@@ -1,331 +1,100 @@
|
||||
# Claude Code Global Development Rules
|
||||
# LunchPick - 점심 메뉴 추천 앱
|
||||
|
||||
## 🌐 Language Settings
|
||||
- **All answers and explanations must be provided in Korean**
|
||||
- **Variable and function names in code should use English**
|
||||
- **Error messages should be explained in Korean**
|
||||
> 글로벌 규칙(~/.claude/CLAUDE.md) 상속. 상세 가이드는 [AGENTS.md](AGENTS.md) 참조.
|
||||
|
||||
## 🤖 Agent Selection Rules
|
||||
- **Always select and use a specialized agent appropriate for the task**
|
||||
## 프로젝트 개요
|
||||
|
||||
## 🎯 Mandatory Response Format
|
||||
- **앱 이름**: 오늘 뭐 먹Z?
|
||||
- **패키지**: `com.naturebridgeai.lunchpick`
|
||||
- **SDK**: Flutter 3.8.1+ / Dart 3.8.1+
|
||||
|
||||
Before starting any task, you MUST respond in the following format:
|
||||
## 핵심 기술 스택
|
||||
|
||||
```
|
||||
[Model Name] - [Agent Name]. I have reviewed all the following rules: [rule file list or categories]. Proceeding with the task. Master!
|
||||
| 분류 | 패키지 |
|
||||
|------|--------|
|
||||
| 상태관리 | Riverpod + riverpod_generator |
|
||||
| 로컬저장 | Hive + hive_generator |
|
||||
| 네비게이션 | go_router |
|
||||
| 네트워크 | Dio + dio_cache_interceptor |
|
||||
| 위치/권한 | geolocator, permission_handler |
|
||||
| 광고 | google_mobile_ads |
|
||||
|
||||
## 프로젝트 구조
|
||||
|
||||
```text
|
||||
lib/
|
||||
├── core/
|
||||
│ ├── constants/ # app_constants, app_colors, api_keys
|
||||
│ ├── network/ # network_client, interceptors
|
||||
│ ├── services/ # permission, geocoding, ad, bluetooth, notification
|
||||
│ ├── errors/ # app_exceptions, network_exceptions
|
||||
│ └── widgets/ # 공통 위젯 (loading, error, empty_state)
|
||||
├── data/
|
||||
│ ├── api/ # naver_api_client, naver GraphQL/LocalSearch
|
||||
│ ├── datasources/ # local, remote (naver_html_parser 등)
|
||||
│ ├── repositories/ # *_repository_impl
|
||||
│ └── models/ # DTO, Hive adapters
|
||||
├── domain/
|
||||
│ ├── entities/ # Restaurant, VisitRecord, UserSettings, WeatherInfo
|
||||
│ ├── repositories/ # 인터페이스 정의
|
||||
│ └── usecases/ # 비즈니스 로직
|
||||
└── presentation/
|
||||
├── providers/ # Riverpod providers
|
||||
├── view_models/ # 화면 상태 관리
|
||||
└── pages/ # splash, main, random_selection, restaurant_list,
|
||||
# calendar, settings, share
|
||||
```
|
||||
|
||||
**Agent Names:**
|
||||
- **Direct Implementation**: Perform direct implementation tasks
|
||||
- **Master Manager**: Overall project management and coordination
|
||||
- **flutter-ui-designer**: Flutter UI/UX design
|
||||
- **flutter-architecture-designer**: Flutter architecture design
|
||||
- **flutter-offline-developer**: Flutter offline functionality development
|
||||
- **flutter-network-engineer**: Flutter network implementation
|
||||
- **flutter-qa-engineer**: Flutter QA/testing
|
||||
- **app-launch-validator**: App launch validation
|
||||
- **aso-optimization-expert**: ASO optimization
|
||||
- **mobile-growth-hacker**: Mobile growth strategy
|
||||
- **Idea Analysis**: Idea analysis
|
||||
- **mobile app mvp planner**: MVP planning
|
||||
## 주요 도메인 엔티티
|
||||
|
||||
**Examples:**
|
||||
- `Claude Opus 4 - Direct Implementation. I have reviewed all the following rules: development guidelines, class structure, testing rules. Proceeding with the task. Master!`
|
||||
- `Claude Opus 4 - flutter-network-engineer. I have reviewed all the following rules: API integration, error handling, network optimization. Proceeding with the task. Master!`
|
||||
- For extensive rules: `coding style, class design, exception handling, testing rules` (categorized summary)
|
||||
- `Restaurant`: 음식점 정보 (이름, 카테고리, 위치, 영업시간 등)
|
||||
- `VisitRecord`: 방문 기록
|
||||
- `RecommendationRecord`: 추천 기록
|
||||
- `UserSettings`: 사용자 설정 (반경, 카테고리 필터 등)
|
||||
- `WeatherInfo`: 날씨 정보 (추천 알고리즘 활용)
|
||||
|
||||
## 필수 명령어
|
||||
|
||||
```bash
|
||||
# 의존성 설치
|
||||
flutter pub get
|
||||
|
||||
## 🚀 Mandatory 3-Phase Task Process
|
||||
# 코드 생성 (Hive adapters, Riverpod, JSON)
|
||||
dart run build_runner build --delete-conflicting-outputs
|
||||
|
||||
### Phase 1: Codebase Exploration & Analysis
|
||||
**Required Actions:**
|
||||
- Systematically discover ALL relevant files, directories, modules
|
||||
- Search for related keywords, functions, classes, patterns
|
||||
- Thoroughly examine each identified file
|
||||
- Document coding conventions and style guidelines
|
||||
- Identify framework/library usage patterns
|
||||
- Map dependencies and architectural structure
|
||||
# 개발 중 자동 생성
|
||||
dart run build_runner watch --delete-conflicting-outputs
|
||||
|
||||
### Phase 2: Implementation Planning
|
||||
**Required Actions:**
|
||||
- Create detailed implementation roadmap based on Phase 1 findings
|
||||
- Define specific task lists and acceptance criteria per module
|
||||
- Specify performance/quality requirements
|
||||
- Plan test strategy and coverage
|
||||
- Identify potential risks and edge cases
|
||||
# 분석 & 테스트
|
||||
flutter analyze
|
||||
flutter test
|
||||
flutter test test_hive # Hive 변경 시
|
||||
|
||||
### Phase 3: Implementation Execution
|
||||
**Required Actions:**
|
||||
- Implement each module following Phase 2 plan
|
||||
- Verify ALL acceptance criteria before proceeding
|
||||
- Ensure adherence to conventions identified in Phase 1
|
||||
- Write tests alongside implementation
|
||||
- Document complex logic and design decisions
|
||||
|
||||
## ✅ Core Development Principles
|
||||
|
||||
### Language & Documentation Rules
|
||||
- **Code, variables, and identifiers**: Always in English
|
||||
- **Comments and documentation**: Use project's primary spoken language
|
||||
- **Commit messages**: Use project's primary spoken language
|
||||
- **Error messages**: Bilingual when appropriate (technical term + native explanation)
|
||||
|
||||
### Type Safety Rules
|
||||
- **Always declare types explicitly** for variables, parameters, and return values
|
||||
- Avoid `any`, `dynamic`, or loosely typed declarations (except when strictly necessary)
|
||||
- Define **custom types/interfaces** for complex data structures
|
||||
- Use **enums** for fixed sets of values
|
||||
- Extract magic numbers and literals into named constants
|
||||
|
||||
### Naming Conventions
|
||||
|
||||
|Element|Style|Example|
|
||||
|---|---|---|
|
||||
|Classes/Interfaces|`PascalCase`|`UserService`, `DataRepository`|
|
||||
|Variables/Methods|`camelCase`|`userName`, `calculateTotal`|
|
||||
|Constants|`UPPERCASE` or `PascalCase`|`MAX_RETRY_COUNT`, `DefaultTimeout`|
|
||||
|Files (varies by language)|Follow language convention|`user_service.py`, `UserService.java`|
|
||||
|Boolean variables|Verb-based|`isReady`, `hasError`, `canDelete`|
|
||||
|Functions/Methods|Start with verbs|`executeLogin`, `saveUser`, `validateInput`|
|
||||
|
||||
**Critical Rules:**
|
||||
- Use meaningful, descriptive names
|
||||
- Avoid abbreviations unless widely accepted: `i`, `j`, `err`, `ctx`, `API`, `URL`
|
||||
- Name length should reflect scope (longer names for wider scope)
|
||||
|
||||
## 🔧 Function & Method Design
|
||||
|
||||
### Function Structure Principles
|
||||
- **Keep functions short and focused** (≤20 lines recommended)
|
||||
- **Follow Single Responsibility Principle (SRP)**
|
||||
- **Minimize parameters** (≤3 ideal, use objects for more)
|
||||
- **Avoid deeply nested logic** (≤3 levels)
|
||||
- **Use early returns** to reduce complexity
|
||||
- **Extract complex conditions** into well-named functions
|
||||
|
||||
### Function Optimization Techniques
|
||||
- Prefer **pure functions** without side effects
|
||||
- Use **default parameters** to reduce overloading
|
||||
- Apply **RO-RO pattern** (Receive Object – Return Object) for complex APIs
|
||||
- **Cache expensive computations** when appropriate
|
||||
- **Avoid premature optimization** - profile first
|
||||
|
||||
## 📦 Data & Class Design
|
||||
|
||||
### Class Design Principles
|
||||
- **Single Responsibility Principle (SRP)**: One class, one purpose
|
||||
- **Favor composition over inheritance**
|
||||
- **Program to interfaces**, not implementations
|
||||
- **Keep classes cohesive** - high internal, low external coupling
|
||||
- **Prefer immutability** when possible
|
||||
|
||||
### File Size Management
|
||||
**Guidelines (not hard limits):**
|
||||
- Classes: ≤200 lines
|
||||
- Functions: ≤20 lines
|
||||
- Files: ≤300 lines
|
||||
|
||||
**Split when:**
|
||||
- Multiple responsibilities exist
|
||||
- Excessive scrolling required
|
||||
- Pattern duplication occurs
|
||||
- Testing becomes complex
|
||||
|
||||
### Data Model Design
|
||||
- **Encapsulate validation** within data models
|
||||
- **Use Value Objects** for complex primitives
|
||||
- **Apply Builder pattern** for complex object construction
|
||||
- **Implement proper equals/hashCode** for data classes
|
||||
|
||||
## ❗ Exception Handling
|
||||
|
||||
### Exception Usage Principles
|
||||
- Use exceptions for **exceptional circumstances only**
|
||||
- **Fail fast** at system boundaries
|
||||
- **Catch exceptions only when you can handle them**
|
||||
- **Add context** when re-throwing
|
||||
- **Use custom exceptions** for domain-specific errors
|
||||
- **Document thrown exceptions**
|
||||
|
||||
### Error Handling Strategies
|
||||
- Return **Result/Option types** for expected failures
|
||||
- Use **error codes** for performance-critical paths
|
||||
- Implement **circuit breakers** for external dependencies
|
||||
- **Log errors appropriately** (error level, context, stack trace)
|
||||
|
||||
## 🧪 Testing Strategy
|
||||
|
||||
### Test Structure
|
||||
- Follow **Arrange-Act-Assert (AAA)** pattern
|
||||
- Use **descriptive test names** that explain what and why
|
||||
- **One assertion per test** (when practical)
|
||||
- **Test behavior, not implementation**
|
||||
|
||||
### Test Coverage Guidelines
|
||||
- **Unit tests**: All public methods and edge cases
|
||||
- **Integration tests**: Critical paths and external integrations
|
||||
- **End-to-end tests**: Key user journeys
|
||||
- Aim for **80%+ code coverage** (quality over quantity)
|
||||
|
||||
### Test Best Practices
|
||||
- **Use test doubles** (mocks, stubs, fakes) appropriately
|
||||
- **Keep tests independent** and idempotent
|
||||
- **Test data builders** for complex test setups
|
||||
- **Parameterized tests** for multiple scenarios
|
||||
- **Performance tests** for critical paths
|
||||
|
||||
## 📝 Version Control Guidelines
|
||||
|
||||
### Commit Best Practices
|
||||
- **Atomic commits**: One logical change per commit
|
||||
- **Frequent commits**: Small, incremental changes
|
||||
- **Clean history**: Use interactive rebase when needed
|
||||
- **Branch strategy**: Follow project's branching model
|
||||
|
||||
### Commit Message Format
|
||||
```
|
||||
type(scope): brief description
|
||||
|
||||
Detailed explanation if needed
|
||||
- Bullet points for multiple changes
|
||||
- Reference issue numbers: #123
|
||||
|
||||
BREAKING CHANGE: description (if applicable)
|
||||
# 릴리즈 빌드
|
||||
flutter build appbundle --release
|
||||
```
|
||||
|
||||
### Commit Types
|
||||
- `feat`: New feature
|
||||
- `fix`: Bug fix
|
||||
- `refactor`: Code refactoring
|
||||
- `perf`: Performance improvement
|
||||
- `test`: Test changes
|
||||
- `docs`: Documentation
|
||||
- `style`: Code formatting
|
||||
- `chore`: Build/tooling changes
|
||||
## Agent 응답 형식
|
||||
|
||||
## 🏗️ Architecture Guidelines
|
||||
|
||||
### Clean Architecture Principles
|
||||
- **Dependency Rule**: Dependencies point inward
|
||||
- **Layer Independence**: Each layer has single responsibility
|
||||
- **Testability**: Business logic independent of frameworks
|
||||
- **Framework Agnostic**: Core logic doesn't depend on external tools
|
||||
|
||||
### Common Architectural Patterns
|
||||
- **Repository Pattern**: Abstract data access
|
||||
- **Service Layer**: Business logic coordination
|
||||
- **Dependency Injection**: Loose coupling
|
||||
- **Event-Driven**: For asynchronous workflows
|
||||
- **CQRS**: When read/write separation needed
|
||||
|
||||
### Module Organization
|
||||
```
|
||||
src/
|
||||
├── domain/ # Business entities and rules
|
||||
├── application/ # Use cases and workflows
|
||||
├── infrastructure/ # External dependencies
|
||||
├── presentation/ # UI/API layer
|
||||
└── shared/ # Cross-cutting concerns
|
||||
```text
|
||||
[Model Name] - [Agent Name]. I have reviewed all the following rules: [categories]. Proceeding with the task. Master!
|
||||
```
|
||||
|
||||
## 🔄 Safe Refactoring Practices
|
||||
### Available Agents
|
||||
|
||||
### Preventing Side Effects During Refactoring
|
||||
- **Run all tests before and after** every refactoring step
|
||||
- **Make incremental changes**: One small refactoring at a time
|
||||
- **Use automated refactoring tools** when available (IDE support)
|
||||
- **Preserve existing behavior**: Refactoring should not change functionality
|
||||
- **Create characterization tests** for legacy code before refactoring
|
||||
- **Use feature flags** for large-scale refactorings
|
||||
- **Monitor production metrics** after deployment
|
||||
| Agent | 용도 |
|
||||
|-------|------|
|
||||
| Direct Implementation | 직접 구현 |
|
||||
| flutter-ui-designer | UI/UX 디자인 |
|
||||
| flutter-architecture-designer | 아키텍처 설계 |
|
||||
| flutter-network-engineer | 네트워크/API |
|
||||
| flutter-qa-engineer | QA/테스트 |
|
||||
| app-launch-validator | 출시 검증 |
|
||||
| aso-optimization-expert | ASO 최적화 |
|
||||
|
||||
### Refactoring Checklist
|
||||
1. **Before Starting**:
|
||||
- [ ] All tests passing
|
||||
- [ ] Understand current behavior completely
|
||||
- [ ] Create backup branch
|
||||
- [ ] Document intended changes
|
||||
## 주의사항
|
||||
|
||||
2. **During Refactoring**:
|
||||
- [ ] Keep commits atomic and reversible
|
||||
- [ ] Run tests after each change
|
||||
- [ ] Verify no behavior changes
|
||||
- [ ] Check for performance impacts
|
||||
|
||||
3. **After Completion**:
|
||||
- [ ] All tests still passing
|
||||
- [ ] Code coverage maintained or improved
|
||||
- [ ] Performance benchmarks verified
|
||||
- [ ] Peer review completed
|
||||
|
||||
### Common Refactoring Patterns
|
||||
- **Extract Method**: Break large functions into smaller ones
|
||||
- **Rename**: Improve clarity with better names
|
||||
- **Move**: Relocate code to appropriate modules
|
||||
- **Extract Variable**: Make complex expressions readable
|
||||
- **Inline**: Remove unnecessary indirection
|
||||
- **Extract Interface**: Decouple implementations
|
||||
|
||||
## 🧠 Continuous Improvement
|
||||
|
||||
### Code Review Focus Areas
|
||||
- **Correctness**: Does it work as intended?
|
||||
- **Clarity**: Is it easy to understand?
|
||||
- **Consistency**: Does it follow conventions?
|
||||
- **Completeness**: Are edge cases handled?
|
||||
- **Performance**: Are there obvious bottlenecks?
|
||||
- **Security**: Are there vulnerabilities?
|
||||
- **Side Effects**: Are there unintended consequences?
|
||||
|
||||
### Knowledge Sharing
|
||||
- **Document decisions** in ADRs (Architecture Decision Records)
|
||||
- **Create runbooks** for operational procedures
|
||||
- **Maintain README** files for each module
|
||||
- **Share learnings** through team discussions
|
||||
- **Update rules** based on team consensus
|
||||
|
||||
## ✅ Quality Validation Checklist
|
||||
|
||||
Before completing any task, confirm:
|
||||
|
||||
### Phase Completion
|
||||
- [ ] Phase 1: Comprehensive analysis completed
|
||||
- [ ] Phase 2: Detailed plan with acceptance criteria
|
||||
- [ ] Phase 3: Implementation meets all criteria
|
||||
|
||||
### Code Quality
|
||||
- [ ] Follows naming conventions
|
||||
- [ ] Type safety enforced
|
||||
- [ ] Single Responsibility maintained
|
||||
- [ ] Proper error handling
|
||||
- [ ] Adequate test coverage
|
||||
- [ ] Documentation complete
|
||||
|
||||
### Best Practices
|
||||
- [ ] No code smells or anti-patterns
|
||||
- [ ] Performance considerations addressed
|
||||
- [ ] Security vulnerabilities checked
|
||||
- [ ] Accessibility requirements met
|
||||
- [ ] Internationalization ready (if applicable)
|
||||
|
||||
## 🎯 Success Metrics
|
||||
|
||||
### Code Quality Indicators
|
||||
- **Low cyclomatic complexity** (≤10 per function)
|
||||
- **High cohesion**, low coupling
|
||||
- **Minimal code duplication** (<5%)
|
||||
- **Clear separation of concerns**
|
||||
- **Consistent style throughout**
|
||||
|
||||
### Professional Standards
|
||||
- **Readable**: New developers understand quickly
|
||||
- **Maintainable**: Changes are easy to make
|
||||
- **Testable**: Components tested in isolation
|
||||
- **Scalable**: Handles growth gracefully
|
||||
- **Reliable**: Fails gracefully with clear errors
|
||||
|
||||
---
|
||||
|
||||
**Remember**: These are guidelines, not rigid rules. Use professional judgment and adapt to project needs while maintaining high quality standards.
|
||||
- `api_keys.dart`는 커밋 금지 (로컬 생성)
|
||||
- Android/iOS 빌드 설정 변경 시 승인 필요
|
||||
- Hive 스키마 변경 시 마이그레이션 고려
|
||||
- 네이버 API 호출 시 캐시 정책 준수
|
||||
|
||||
@@ -20,11 +20,17 @@ android {
|
||||
jvmTarget = JavaVersion.VERSION_11.toString()
|
||||
}
|
||||
|
||||
signingConfigs {
|
||||
create("release") {
|
||||
storeFile = file("../../doc/key/lunchpick-release.keystore")
|
||||
storePassword = "lunchpick"
|
||||
keyAlias = "lunchpick"
|
||||
keyPassword = "lunchpick"
|
||||
}
|
||||
}
|
||||
|
||||
defaultConfig {
|
||||
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
|
||||
applicationId = "com.naturebridgeai.lunchpick"
|
||||
// You can update the following values to match your application needs.
|
||||
// For more information, see: https://flutter.dev/to/review-gradle-config.
|
||||
minSdk = flutter.minSdkVersion
|
||||
targetSdk = flutter.targetSdkVersion
|
||||
versionCode = flutter.versionCode
|
||||
@@ -37,9 +43,7 @@ android {
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
// TODO: Add your own signing config for the release build.
|
||||
// Signing with the debug keys for now, so `flutter run --release` works.
|
||||
signingConfig = signingConfigs.getByName("debug")
|
||||
signingConfig = signingConfigs.getByName("release")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<!-- BLE 기능 선언 (필수 아님으로 설정) -->
|
||||
<uses-feature android:name="android.hardware.bluetooth_le" android:required="false" />
|
||||
|
||||
<!-- 알림 권한 (Android 13+) -->
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<!-- 정확한 알람 권한 (Android 12+) -->
|
||||
|
||||
@@ -520,7 +520,7 @@ class _SplashScreenState extends State<SplashScreen> with TickerProviderStateMix
|
||||
left: 0,
|
||||
right: 0,
|
||||
child: Text(
|
||||
'© 2025. NatureBridgeAI. All rights reserved.',
|
||||
'© 2025. NatureBridgeAI & cclabs. All rights reserved.',
|
||||
style: AppTypography.caption(isDark).copyWith(
|
||||
color: (isDark ? AppColors.darkTextSecondary : AppColors.lightTextSecondary)
|
||||
.withOpacity(0.5),
|
||||
|
||||
190
doc/store_desc/privacy_policy.md
Normal file
190
doc/store_desc/privacy_policy.md
Normal file
@@ -0,0 +1,190 @@
|
||||
# 오늘 뭐 먹Z? 개인정보 처리방침
|
||||
|
||||
오늘 뭐 먹Z? (이하 “앱”)는 사용자의 개인정보 보호를 최우선 가치로 삼습니다.
|
||||
|
||||
앱은 점심 메뉴 추천 및 맛집 관리 기능 제공을 위해 최소한의 정보만을 사용하며, **개발자가 직접 운영하는 별도 서버를 두지 않습니다.**
|
||||
다만, 위치 기반 추천, 날씨 정보 제공, 네이버 검색 연동, 광고 노출 및 좌표 확인을 위해 제3자 서비스와 통신할 수 있습니다.
|
||||
|
||||
본 개인정보 처리방침은 앱이 어떤 정보를 어떤 목적과 방식으로 처리하는지 설명합니다.
|
||||
|
||||
---
|
||||
|
||||
## 1. 수집하는 개인정보
|
||||
|
||||
### 1-1. 직접 식별 가능한 정보
|
||||
|
||||
앱은 다음과 같은 의미에서 사용자를 직접 식별할 수 있는 개인정보(이름, 이메일, 전화번호 등)를 **직접 수집하지 않습니다.**
|
||||
|
||||
- 회원가입, 로그인 기능이 없습니다.
|
||||
- 주민등록번호, 이름, 이메일, 전화번호, 주소 등 사용자를 직접 식별할 수 있는 정보를 요구하지 않습니다.
|
||||
- 개발자가 운영하는 자체 서버로 사용자의 개인정보를 수집·저장하지 않습니다.
|
||||
|
||||
### 1-2. 서비스 제공을 위해 처리되는 정보
|
||||
|
||||
앱 기능 제공을 위해 다음과 같은 정보가 기기 내에서 처리되거나 제3자 서비스로 전송될 수 있습니다.
|
||||
|
||||
1) **위치 정보**
|
||||
|
||||
- 내용: 현재 위치 좌표(위도, 경도)
|
||||
- 사용 목적
|
||||
- 주변 맛집 추천 및 거리 계산
|
||||
- 날씨(기상청 Open API) 조회
|
||||
- 현재 위치 반경 내 추천 후보를 제한하는 데 활용
|
||||
- 처리 방식
|
||||
- 위치 정보는 주로 **실시간 계산 및 API 호출**에 사용되며, 사용자의 “위치 이력”을 장기적으로 별도 저장하지 않습니다.
|
||||
- 앱에서 저장하는 위치 정보는 주로 “식당 좌표(맛집 위치)”이며, 이는 사용자의 거주지나 신원과 직접 연결되지 않습니다.
|
||||
- 위치 정보는 기상청 Open API 등 날씨 서비스에 한해, 격자 좌표(nx, ny) 형태로 전송될 수 있습니다(자세한 내용은 아래 3절 참조).
|
||||
|
||||
2) **맛집 및 방문 기록 정보**
|
||||
|
||||
- 내용
|
||||
- 사용자가 직접 입력하거나 네이버 URL에서 가져온 식당 정보
|
||||
- 식당 이름, 카테고리, 설명, 전화번호, 도로명/지번 주소
|
||||
- 위도·경도, 주소, 영업시간 등
|
||||
- 방문 기록 및 통계 정보
|
||||
- 방문 일자, 방문 여부, 방문 횟수 등
|
||||
- 사용 목적
|
||||
- 점심 메뉴 추천, 중복 방문 방지, 방문 기록 조회, 통계 제공 등
|
||||
- 처리 방식
|
||||
- 위 정보는 모두 **사용자의 기기 내 로컬 데이터베이스**에만 저장됩니다.
|
||||
- 개발자는 이 데이터를 서버를 통해 열람하거나 수집하지 않습니다.
|
||||
|
||||
3) **앱 사용 설정 정보**
|
||||
|
||||
- 내용: 알림 시간, 추천 거리/날씨 관련 설정, 다크모드 여부 등 앱 내 환경 설정
|
||||
- 사용 목적: 사용자 맞춤 추천 및 알림 제공
|
||||
- 처리 방식: 기기 내 로컬 저장소에만 저장되며, 서버로 전송되지 않습니다.
|
||||
|
||||
---
|
||||
|
||||
## 2. 데이터 저장 및 처리 방식
|
||||
|
||||
1) **로컬 저장소(기기 내 저장소)**
|
||||
|
||||
- 맛집 정보, 방문 기록, 앱 설정, 일부 캐시 데이터(날씨 등)는
|
||||
**기기 내 로컬 데이터베이스에만 저장**됩니다.
|
||||
- 앱을 삭제하면 일반적으로 해당 앱과 연계된 로컬 데이터도 함께 삭제됩니다.
|
||||
다만, 운영체제나 백업 설정에 따라 일부 데이터가 OS 또는 클라우드 백업에 남을 수 있으며, 이는 각 플랫폼(예: Apple, Google)의 정책을 따릅니다.
|
||||
|
||||
2) **네트워크 통신 및 제3자 전송**
|
||||
|
||||
앱은 자체 서버를 운영하지 않지만, 다음과 같은 제3자 서비스와 통신합니다.
|
||||
|
||||
- **지도·식당 정보 제공을 위한 네이버 지도 웹 서비스**
|
||||
- 전송되는 정보(예시): 사용자가 앱에 붙여넣은 네이버 지도 URL, 해당 URL에 포함된 식당 ID 등
|
||||
- 사용 목적: 네이버 지도 페이지 및 관련 API(예: GraphQL)를 통해 식당 이름·주소·좌표·전화번호 등을 조회하고, 앱 내 식당 정보로 변환
|
||||
|
||||
- **지오코딩(Geocoding) 서비스: OpenStreetMap Nominatim**
|
||||
- 전송되는 정보(예시): 사용자가 입력한 식당 주소(도로명·지번 등)
|
||||
- 사용 목적: 주소를 위도·경도 좌표로 변환하여 지도/거리 계산 및 추천 알고리즘에 활용
|
||||
|
||||
- **기상청 Open API(공공데이터포털)**
|
||||
- 전송되는 정보(예시): 위치를 기반으로 변환된 격자 좌표(nx, ny)
|
||||
- 사용 목적: 현재 및 단기(1시간 후) 날씨 정보 조회
|
||||
|
||||
- **광고 네트워크(Google AdMob 등)**
|
||||
- 자세한 내용은 아래 3절 “광고 및 제3자 서비스” 참조
|
||||
|
||||
앱 개발자는 이들 제3자 서비스의 서버에 저장되는 데이터에 직접 접근하지 않으며,
|
||||
제3자 서비스에서 수집·처리하는 정보는 각 서비스의 개인정보 처리방침을 따릅니다.
|
||||
|
||||
---
|
||||
|
||||
## 3. 광고 및 제3자 서비스
|
||||
|
||||
앱은 무료 제공을 위해 광고를 노출할 수 있으며, 이 과정에서 **Google AdMob** 등 제3자 광고 네트워크가 참여합니다.
|
||||
|
||||
### 3-1. 광고 네트워크가 수집할 수 있는 정보
|
||||
|
||||
앱은 직접 사용자의 개인정보를 수집하지 않지만, 광고 네트워크는 다음과 같은 정보를 수집·처리할 수 있습니다(예시).
|
||||
|
||||
- 광고 식별자 (예: Android 광고 ID, IDFA 등)
|
||||
- 기기 정보 (단말기 모델명, OS 버전, 언어/국가 설정 등)
|
||||
- 대략적인 위치 정보 (국가/지역 수준, IP 기반 위치 등)
|
||||
- 앱 사용 정보 (광고 조회/클릭 여부, 광고 노출 횟수 등)
|
||||
|
||||
이러한 정보는 **개발자가 아닌 광고 네트워크 사업자**가 수집·처리하며,
|
||||
수집 범위와 이용 목적은 해당 사업자의 개인정보 처리방침을 따릅니다.
|
||||
|
||||
보다 자세한 내용은 각 서비스의 정책을 참고하세요.
|
||||
|
||||
- Google AdMob / Google Mobile Ads: https://policies.google.com/privacy
|
||||
- 네이버(Naver): https://policy.naver.com/
|
||||
- 공공데이터포털·기상청 Open API: 각 제공 기관의 개인정보 처리방침
|
||||
|
||||
### 3-2. 제3자 서비스 관련 안내
|
||||
|
||||
- 앱은 제3자 서비스에 사용자의 이름, 이메일, 전화번호 등 **직접 식별 정보**를 의도적으로 전송하지 않습니다.
|
||||
- 위치 정보, 검색어, 기기 정보 등은 제3자 서비스의 기술적 처리 과정에서 사용될 수 있습니다.
|
||||
- 제3자 서비스에서 제공하는 맞춤형 광고 또는 추천 기능 등은 해당 서비스의 정책에 따라 동작합니다.
|
||||
|
||||
---
|
||||
|
||||
## 4. 권한 사용
|
||||
|
||||
앱은 기능 제공을 위해 다음과 같은 권한을 사용할 수 있습니다.
|
||||
각 권한은 **명시된 목적 외의 용도로 사용되지 않습니다.**
|
||||
|
||||
1) **위치 권한**
|
||||
|
||||
- 사용 목적
|
||||
- 현재 위치를 기준으로 주변 맛집을 추천하기 위해 사용
|
||||
- 현재/1시간 후 날씨 정보를 조회하기 위해 사용
|
||||
- 추천 대상이 되는 식당 범위를 “현재 위치 반경”으로 제한하기 위해 사용
|
||||
- 특징
|
||||
- 위치 권한을 거부할 경우, 앱은 서울 시청(기본 좌표)을 기준으로 동작합니다.
|
||||
- 사용자의 위치 이력을 장기적으로 추적하거나, 별도 계정과 연결하여 프로파일링하지 않습니다.
|
||||
|
||||
2) **알림 권한**
|
||||
|
||||
- 사용 목적
|
||||
- 점심 식사 후 방문 기록을 남기도록 안내하는 **방문 확인 알림** 발송
|
||||
- 알림 진동·소리, 정확한 시각의 알림 예약, 기기 재부팅 후 예약 알림 복원
|
||||
- 특징
|
||||
- 알림 내용에는 주로 추천된 식당 이름, 방문 여부 확인 요청 등의 간단한 메시지가 포함됩니다.
|
||||
- 알림 권한을 거부해도 앱의 기본 사용은 가능하나, 방문 리마인더 기능은 제한될 수 있습니다.
|
||||
|
||||
3) **블루투스 권한**
|
||||
|
||||
- 사용 목적
|
||||
- 주변 기기와 **맛집 리스트를 공유**하기 위해 사용
|
||||
- 팀/동료와 함께 맛집 목록을 교환하는 기능에 활용
|
||||
- 특징
|
||||
- 공유 대상 데이터는 식당 이름, 주소, 카테고리 등으로, 사용자의 이름·이메일 등 직접 식별 정보는 포함하지 않습니다.
|
||||
- 공유는 기기간 통신을 전제로 하며, 개발자가 운영하는 중앙 서버를 경유하지 않습니다(향후 실제 Bluetooth 스택 도입 시에도 동일 원칙을 적용합니다).
|
||||
|
||||
4) **네트워크 권한**
|
||||
|
||||
- 사용 목적
|
||||
- 네이버 지도 페이지 및 관련 API 호출(붙여넣은 지도 링크 기반 식당 정보 조회)
|
||||
- 지오코딩 서비스(OpenStreetMap Nominatim) 및 기상청 Open API 호출(좌표·날씨 정보)
|
||||
- 광고(Google AdMob) 로딩 및 통계 전송
|
||||
- 특징
|
||||
- 앱은 별도의 자체 백엔드 서버를 운영하지 않으며, 네트워크 요청은 위와 같은 제3자 API·광고 서비스에 한정됩니다.
|
||||
|
||||
---
|
||||
|
||||
## 5. 아동의 개인정보
|
||||
|
||||
- 앱은 성인(직장인 등 일반 사용자)을 주요 대상으로 설계되었습니다.
|
||||
- 만 14세 미만(또는 각 국가에서 정한 연령 기준 미만)의 아동을 대상으로 개인정보를 수집하려는 의도가 없습니다.
|
||||
- 만약 아동의 개인정보가 부주의로 수집된 사실을 인지하게 될 경우, 가능한 한 신속히 해당 정보를 삭제하기 위한 조치를 취하겠습니다.
|
||||
|
||||
---
|
||||
|
||||
## 6. 개인정보 처리방침의 변경
|
||||
|
||||
- 본 개인정보 처리방침은 서비스 개선, 관련 법령 및 가이드라인 개정, 기능 추가/변경 등에 따라 수시로 수정될 수 있습니다.
|
||||
- 중요한 내용(수집 항목, 이용 목적, 제3자 제공 등)이 변경되는 경우, 앱 내 공지 또는 스토어 설명 등을 통해 변경 내용을 안내하겠습니다.
|
||||
- 변경된 개인정보 처리방침은 명시된 시행일로부터 효력이 발생합니다.
|
||||
|
||||
**시행일자: 2025.12.05**
|
||||
|
||||
---
|
||||
|
||||
## 7. 문의처
|
||||
|
||||
앱의 개인정보 처리방침과 관련하여 문의, 의견 제출, 권리 행사(열람, 정정, 삭제 요청 등)가 필요하신 경우 아래 연락처로 문의해 주세요.
|
||||
|
||||
- 담당자: 네이처브릿지AI 앱개발팀
|
||||
- 이메일: naturebridgeai@gmail.com
|
||||
@@ -21,7 +21,7 @@
|
||||
- 한식·중식·일식·카페 등 카테고리를 선택해, 그날 기분에 맞는 맛집만 골라서 추천
|
||||
|
||||
2. 네이버 지도 연동 맛집 수집
|
||||
- 네이버 지도앱에서 공유한 링크(naver.me 등)를 그대로 붙여넣으면, 가게 이름·주소·카테고리·좌표를 자동으로 불러와 등록
|
||||
- 네이버 지도앱의 ‘공유’ 기능으로 복사한 링크(naver.me 등)를 **수정하지 말고 그대로** 붙여넣으면, 가게 이름·주소·카테고리·좌표를 자동으로 불러와 등록
|
||||
- 회사 구내식당이나 단골 분식집은 직접 입력으로 손쉽게 등록
|
||||
- 메모, 전화번호까지 함께 저장해 두고, 동료에게 설명할 때도 한 번에 보여줄 수 있습니다.
|
||||
|
||||
@@ -49,4 +49,4 @@
|
||||
- 캘린더와 통계 화면 덕분에, 점심 시간이 단순 소비가 아니라 나만의 작은 라이프로그가 됩니다.
|
||||
- 팀 점심·회식까지 한 앱으로 해결해, 메뉴 선택 스트레스를 팀 전체에서 줄일 수 있습니다.
|
||||
- 지금 ‘오늘 뭐 먹Z?’를 설치하고, 한국 직장인의 가장 큰 고민 중 하나인 점심 메뉴 선택을 1분 안에 끝내 보세요.
|
||||
※ 본 서비스는 현재 한국(대한민국) 지역에서만 사용 가능합니다.
|
||||
※ 본 서비스는 현재 한국(대한민국) 지역에서만 사용 가능합니다.
|
||||
|
||||
@@ -54,6 +54,10 @@
|
||||
<string>맛집과의 거리 계산을 위해 위치 정보가 필요합니다.</string>
|
||||
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
|
||||
<string>맛집과의 거리 계산을 위해 위치 정보가 필요합니다.</string>
|
||||
<key>NSBluetoothAlwaysUsageDescription</key>
|
||||
<string>맛집 리스트를 다른 사용자와 공유하기 위해 블루투스 권한이 필요합니다.</string>
|
||||
<key>NSBluetoothPeripheralUsageDescription</key>
|
||||
<string>맛집 리스트를 다른 사용자로부터 받기 위해 블루투스 권한이 필요합니다.</string>
|
||||
<key>GADApplicationIdentifier</key>
|
||||
<string>$(GAD_APPLICATION_ID)</string>
|
||||
</dict>
|
||||
|
||||
@@ -4,7 +4,7 @@ class AppConstants {
|
||||
static const String appDescription = '점심 메뉴 추천 앱';
|
||||
static const String appVersion = '1.0.0';
|
||||
static const String appCopyright =
|
||||
'© 2025. NatureBridgeAI. All rights reserved.';
|
||||
'© 2025. NatureBridgeAI & cclabs. All rights reserved.';
|
||||
|
||||
// Animation Durations
|
||||
static const Duration splashAnimationDuration = Duration(seconds: 3);
|
||||
|
||||
55
lib/core/constants/app_dimensions.dart
Normal file
55
lib/core/constants/app_dimensions.dart
Normal file
@@ -0,0 +1,55 @@
|
||||
/// UI 관련 상수 정의
|
||||
/// 하드코딩된 패딩, 마진, 크기 값들을 중앙 집중화
|
||||
class AppDimensions {
|
||||
AppDimensions._();
|
||||
|
||||
// Padding & Margin
|
||||
static const double paddingXs = 4.0;
|
||||
static const double paddingSm = 8.0;
|
||||
static const double paddingMd = 12.0;
|
||||
static const double paddingDefault = 16.0;
|
||||
static const double paddingLg = 20.0;
|
||||
static const double paddingXl = 24.0;
|
||||
|
||||
// Border Radius
|
||||
static const double radiusSm = 8.0;
|
||||
static const double radiusMd = 12.0;
|
||||
static const double radiusLg = 16.0;
|
||||
static const double radiusXl = 20.0;
|
||||
static const double radiusRound = 999.0;
|
||||
|
||||
// Icon Sizes
|
||||
static const double iconSm = 16.0;
|
||||
static const double iconMd = 24.0;
|
||||
static const double iconLg = 32.0;
|
||||
static const double iconXl = 48.0;
|
||||
static const double iconXxl = 64.0;
|
||||
static const double iconHuge = 80.0;
|
||||
|
||||
// Card Sizes
|
||||
static const double cardIconSize = 48.0;
|
||||
static const double cardMinHeight = 80.0;
|
||||
|
||||
// Ad Settings
|
||||
static const int adInterval = 6; // 5리스트 후 1광고
|
||||
static const int adOffset = 5; // 광고 시작 위치
|
||||
static const double adHeightSmall = 100.0;
|
||||
static const double adHeightMedium = 320.0;
|
||||
|
||||
// Distance Settings
|
||||
static const double maxSearchDistance = 2000.0; // meters
|
||||
static const int distanceSliderDivisions = 19;
|
||||
|
||||
// List Settings
|
||||
static const double listItemSpacing = 8.0;
|
||||
static const double sectionSpacing = 16.0;
|
||||
|
||||
// Bottom Sheet
|
||||
static const double bottomSheetHandleWidth = 40.0;
|
||||
static const double bottomSheetHandleHeight = 4.0;
|
||||
|
||||
// Avatar/Profile
|
||||
static const double avatarSm = 32.0;
|
||||
static const double avatarMd = 48.0;
|
||||
static const double avatarLg = 64.0;
|
||||
}
|
||||
32
lib/core/constants/ble_constants.dart
Normal file
32
lib/core/constants/ble_constants.dart
Normal file
@@ -0,0 +1,32 @@
|
||||
/// BLE 공유 기능에서 사용하는 상수 정의
|
||||
class BleConstants {
|
||||
BleConstants._();
|
||||
|
||||
/// LunchPick 전용 서비스 UUID
|
||||
static const String serviceUuid = 'a1b2c3d4-e5f6-7890-abcd-ef1234567890';
|
||||
|
||||
/// 맛집 데이터 전송용 Characteristic UUID
|
||||
static const String dataCharacteristicUuid =
|
||||
'a1b2c3d4-e5f6-7890-abcd-ef1234567891';
|
||||
|
||||
/// 공유 코드 확인용 Characteristic UUID (매칭용)
|
||||
static const String codeCharacteristicUuid =
|
||||
'a1b2c3d4-e5f6-7890-abcd-ef1234567892';
|
||||
|
||||
/// 청크 사이즈 (MTU - 3, 보수적으로 설정)
|
||||
/// BLE 표준 MTU는 23바이트지만, 협상을 통해 더 커질 수 있음
|
||||
/// 안전하게 500바이트로 설정
|
||||
static const int chunkSize = 500;
|
||||
|
||||
/// 광고 이름 prefix
|
||||
static const String advertiseNamePrefix = 'LP-';
|
||||
|
||||
/// 스캔 타임아웃 (초)
|
||||
static const int scanTimeoutSeconds = 10;
|
||||
|
||||
/// 연결 타임아웃 (초)
|
||||
static const int connectionTimeoutSeconds = 15;
|
||||
|
||||
/// 청크 전송 간 딜레이 (밀리초)
|
||||
static const int chunkDelayMs = 50;
|
||||
}
|
||||
@@ -1,142 +0,0 @@
|
||||
/// 애플리케이션 전체 예외 클래스들
|
||||
///
|
||||
/// 각 레이어별로 명확한 예외 계층 구조를 제공합니다.
|
||||
|
||||
/// 앱 예외 기본 클래스
|
||||
abstract class AppException implements Exception {
|
||||
final String message;
|
||||
final String? code;
|
||||
final dynamic originalError;
|
||||
|
||||
const AppException({required this.message, this.code, this.originalError});
|
||||
|
||||
@override
|
||||
String toString() =>
|
||||
'$runtimeType: $message${code != null ? ' (코드: $code)' : ''}';
|
||||
}
|
||||
|
||||
/// 비즈니스 로직 예외
|
||||
class BusinessException extends AppException {
|
||||
const BusinessException({
|
||||
required String message,
|
||||
String? code,
|
||||
dynamic originalError,
|
||||
}) : super(message: message, code: code, originalError: originalError);
|
||||
}
|
||||
|
||||
/// 검증 예외
|
||||
class ValidationException extends AppException {
|
||||
final Map<String, String>? fieldErrors;
|
||||
|
||||
const ValidationException({
|
||||
required String message,
|
||||
this.fieldErrors,
|
||||
String? code,
|
||||
}) : super(message: message, code: code);
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
final base = super.toString();
|
||||
if (fieldErrors != null && fieldErrors!.isNotEmpty) {
|
||||
final errors = fieldErrors!.entries
|
||||
.map((e) => '${e.key}: ${e.value}')
|
||||
.join(', ');
|
||||
return '$base [필드 오류: $errors]';
|
||||
}
|
||||
return base;
|
||||
}
|
||||
}
|
||||
|
||||
/// 데이터 예외
|
||||
class DataException extends AppException {
|
||||
const DataException({
|
||||
required String message,
|
||||
String? code,
|
||||
dynamic originalError,
|
||||
}) : super(message: message, code: code, originalError: originalError);
|
||||
}
|
||||
|
||||
/// 저장소 예외
|
||||
class StorageException extends DataException {
|
||||
const StorageException({
|
||||
required String message,
|
||||
String? code,
|
||||
dynamic originalError,
|
||||
}) : super(message: message, code: code, originalError: originalError);
|
||||
}
|
||||
|
||||
/// 권한 예외
|
||||
class PermissionException extends AppException {
|
||||
final String permission;
|
||||
|
||||
const PermissionException({
|
||||
required String message,
|
||||
required this.permission,
|
||||
String? code,
|
||||
}) : super(message: message, code: code);
|
||||
|
||||
@override
|
||||
String toString() => '$runtimeType: $message (권한: $permission)';
|
||||
}
|
||||
|
||||
/// 위치 서비스 예외
|
||||
class LocationException extends AppException {
|
||||
const LocationException({
|
||||
required String message,
|
||||
String? code,
|
||||
dynamic originalError,
|
||||
}) : super(message: message, code: code, originalError: originalError);
|
||||
}
|
||||
|
||||
/// 설정 예외
|
||||
class ConfigurationException extends AppException {
|
||||
const ConfigurationException({required String message, String? code})
|
||||
: super(message: message, code: code);
|
||||
}
|
||||
|
||||
/// UI 예외
|
||||
class UIException extends AppException {
|
||||
const UIException({
|
||||
required String message,
|
||||
String? code,
|
||||
dynamic originalError,
|
||||
}) : super(message: message, code: code, originalError: originalError);
|
||||
}
|
||||
|
||||
/// 리소스를 찾을 수 없음 예외
|
||||
class NotFoundException extends AppException {
|
||||
final String resourceType;
|
||||
final dynamic resourceId;
|
||||
|
||||
const NotFoundException({
|
||||
required this.resourceType,
|
||||
required this.resourceId,
|
||||
String? message,
|
||||
}) : super(
|
||||
message: message ?? '$resourceType을(를) 찾을 수 없습니다 (ID: $resourceId)',
|
||||
code: 'NOT_FOUND',
|
||||
);
|
||||
}
|
||||
|
||||
/// 중복 리소스 예외
|
||||
class DuplicateException extends AppException {
|
||||
final String resourceType;
|
||||
|
||||
const DuplicateException({required this.resourceType, String? message})
|
||||
: super(message: message ?? '이미 존재하는 $resourceType입니다', code: 'DUPLICATE');
|
||||
}
|
||||
|
||||
/// 추천 엔진 예외
|
||||
class RecommendationException extends BusinessException {
|
||||
const RecommendationException({required String message, String? code})
|
||||
: super(message: message, code: code);
|
||||
}
|
||||
|
||||
/// 알림 예외
|
||||
class NotificationException extends AppException {
|
||||
const NotificationException({
|
||||
required String message,
|
||||
String? code,
|
||||
dynamic originalError,
|
||||
}) : super(message: message, code: code, originalError: originalError);
|
||||
}
|
||||
@@ -1,142 +0,0 @@
|
||||
/// 데이터 레이어 예외 클래스들
|
||||
///
|
||||
/// API, 데이터베이스, 파싱 관련 예외를 정의합니다.
|
||||
|
||||
import 'app_exceptions.dart';
|
||||
|
||||
/// API 예외 기본 클래스
|
||||
abstract class ApiException extends DataException {
|
||||
final int? statusCode;
|
||||
|
||||
const ApiException({
|
||||
required String message,
|
||||
this.statusCode,
|
||||
String? code,
|
||||
dynamic originalError,
|
||||
}) : super(message: message, code: code, originalError: originalError);
|
||||
|
||||
@override
|
||||
String toString() =>
|
||||
'$runtimeType: $message${statusCode != null ? ' (HTTP $statusCode)' : ''}';
|
||||
}
|
||||
|
||||
/// 네이버 API 예외
|
||||
class NaverApiException extends ApiException {
|
||||
const NaverApiException({
|
||||
required String message,
|
||||
int? statusCode,
|
||||
String? code,
|
||||
dynamic originalError,
|
||||
}) : super(
|
||||
message: message,
|
||||
statusCode: statusCode,
|
||||
code: code,
|
||||
originalError: originalError,
|
||||
);
|
||||
}
|
||||
|
||||
/// HTML 파싱 예외
|
||||
class HtmlParsingException extends DataException {
|
||||
final String? url;
|
||||
|
||||
const HtmlParsingException({
|
||||
required String message,
|
||||
this.url,
|
||||
dynamic originalError,
|
||||
}) : super(
|
||||
message: message,
|
||||
code: 'HTML_PARSE_ERROR',
|
||||
originalError: originalError,
|
||||
);
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
final base = super.toString();
|
||||
return url != null ? '$base (URL: $url)' : base;
|
||||
}
|
||||
}
|
||||
|
||||
/// 데이터 변환 예외
|
||||
class DataConversionException extends DataException {
|
||||
final String fromType;
|
||||
final String toType;
|
||||
|
||||
const DataConversionException({
|
||||
required String message,
|
||||
required this.fromType,
|
||||
required this.toType,
|
||||
dynamic originalError,
|
||||
}) : super(
|
||||
message: message,
|
||||
code: 'DATA_CONVERSION_ERROR',
|
||||
originalError: originalError,
|
||||
);
|
||||
|
||||
@override
|
||||
String toString() => '$runtimeType: $message ($fromType → $toType)';
|
||||
}
|
||||
|
||||
/// 캐시 예외
|
||||
class CacheException extends StorageException {
|
||||
const CacheException({
|
||||
required String message,
|
||||
String? code,
|
||||
dynamic originalError,
|
||||
}) : super(
|
||||
message: message,
|
||||
code: code ?? 'CACHE_ERROR',
|
||||
originalError: originalError,
|
||||
);
|
||||
}
|
||||
|
||||
/// Hive 예외
|
||||
class HiveException extends StorageException {
|
||||
const HiveException({
|
||||
required String message,
|
||||
String? code,
|
||||
dynamic originalError,
|
||||
}) : super(
|
||||
message: message,
|
||||
code: code ?? 'HIVE_ERROR',
|
||||
originalError: originalError,
|
||||
);
|
||||
}
|
||||
|
||||
/// URL 처리 예외
|
||||
class UrlProcessingException extends DataException {
|
||||
final String url;
|
||||
|
||||
const UrlProcessingException({
|
||||
required String message,
|
||||
required this.url,
|
||||
String? code,
|
||||
dynamic originalError,
|
||||
}) : super(
|
||||
message: message,
|
||||
code: code ?? 'URL_PROCESSING_ERROR',
|
||||
originalError: originalError,
|
||||
);
|
||||
|
||||
@override
|
||||
String toString() => '$runtimeType: $message (URL: $url)';
|
||||
}
|
||||
|
||||
/// 잘못된 URL 형식 예외
|
||||
class InvalidUrlException extends UrlProcessingException {
|
||||
const InvalidUrlException({required String url, String? message})
|
||||
: super(
|
||||
message: message ?? '올바르지 않은 URL 형식입니다',
|
||||
url: url,
|
||||
code: 'INVALID_URL',
|
||||
);
|
||||
}
|
||||
|
||||
/// 지원하지 않는 URL 예외
|
||||
class UnsupportedUrlException extends UrlProcessingException {
|
||||
const UnsupportedUrlException({required String url, String? message})
|
||||
: super(
|
||||
message: message ?? '지원하지 않는 URL입니다',
|
||||
url: url,
|
||||
code: 'UNSUPPORTED_URL',
|
||||
);
|
||||
}
|
||||
@@ -1,89 +1,452 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:math';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:ble_peripheral/ble_peripheral.dart' as ble_peripheral;
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
|
||||
import 'package:lunchpick/core/constants/ble_constants.dart';
|
||||
import 'package:lunchpick/domain/entities/restaurant.dart';
|
||||
import 'package:lunchpick/domain/entities/share_device.dart';
|
||||
|
||||
/// 실제 Bluetooth 통신을 대체하는 간단한 모의(Mock) 서비스.
|
||||
/// BLE 기반 맛집 리스트 공유 서비스
|
||||
///
|
||||
/// - Receiver (공유받기): ble_peripheral 패키지로 GATT Server 역할
|
||||
/// - Sender (공유하기): flutter_blue_plus 패키지로 Central 역할
|
||||
class BluetoothService {
|
||||
// === Peripheral (Receiver) 관련 ===
|
||||
bool _isPeripheralInitialized = false;
|
||||
String? _currentShareCode;
|
||||
final _incomingDataController = StreamController<String>.broadcast();
|
||||
final Map<String, ShareDevice> _listeningDevices = {};
|
||||
final Random _random = Random();
|
||||
final _receivedChunks = <int, String>{};
|
||||
// ignore: unused_field - 디버깅 및 진행률 표시용
|
||||
int _expectedTotalChunks = 0;
|
||||
|
||||
// === Central (Sender) 관련 ===
|
||||
final List<ShareDevice> _discoveredDevices = [];
|
||||
StreamSubscription<List<ScanResult>>? _scanSubscription;
|
||||
BluetoothDevice? _connectedDevice;
|
||||
|
||||
// === 진행 상태 콜백 ===
|
||||
Function(int current, int total)? onSendProgress;
|
||||
Function(int current, int total)? onReceiveProgress;
|
||||
|
||||
/// 수신된 데이터 스트림
|
||||
Stream<String> get onDataReceived => _incomingDataController.stream;
|
||||
|
||||
/// 특정 코드로 수신 대기를 시작한다.
|
||||
Future<void> startListening(String code) async {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 300));
|
||||
stopListening();
|
||||
final shareDevice = ShareDevice(
|
||||
code: code,
|
||||
deviceId: 'LP-${_random.nextInt(900000) + 100000}',
|
||||
discoveredAt: DateTime.now(),
|
||||
);
|
||||
_listeningDevices[code] = shareDevice;
|
||||
}
|
||||
/// 현재 광고 중인 공유 코드
|
||||
String? get currentShareCode => _currentShareCode;
|
||||
|
||||
/// 더 이상 수신 대기하지 않는다.
|
||||
void stopListening() {
|
||||
if (_listeningDevices.isEmpty) return;
|
||||
final codes = List<String>.from(_listeningDevices.keys);
|
||||
for (final code in codes) {
|
||||
_listeningDevices.remove(code);
|
||||
/// BLE 지원 여부 확인
|
||||
Future<bool> get isSupported async {
|
||||
if (!Platform.isAndroid && !Platform.isIOS) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
return await FlutterBluePlus.isSupported;
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// 현재 주변에서 수신 대기 중인 기기 목록을 반환한다.
|
||||
Future<List<ShareDevice>> scanNearbyDevices() async {
|
||||
await Future<void>.delayed(const Duration(seconds: 1));
|
||||
return _listeningDevices.values.toList();
|
||||
/// Bluetooth 어댑터 상태 확인
|
||||
Future<bool> get isBluetoothOn async {
|
||||
try {
|
||||
final state = await FlutterBluePlus.adapterState.first;
|
||||
return state == BluetoothAdapterState.on;
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// 대상 코드로 맛집 리스트를 전송한다. 실제 BT 대신 JSON 문자열을 브로드캐스트한다.
|
||||
// =========================================================================
|
||||
// Receiver (Peripheral) 메서드 - ble_peripheral 사용
|
||||
// =========================================================================
|
||||
|
||||
/// Peripheral 초기화
|
||||
Future<void> initializePeripheral() async {
|
||||
if (_isPeripheralInitialized) return;
|
||||
if (!Platform.isAndroid && !Platform.isIOS) {
|
||||
throw UnsupportedError('BLE Peripheral은 Android/iOS에서만 지원됩니다.');
|
||||
}
|
||||
|
||||
try {
|
||||
await ble_peripheral.BlePeripheral.initialize();
|
||||
_setupWriteCallback();
|
||||
_isPeripheralInitialized = true;
|
||||
debugPrint('[BLE] Peripheral 초기화 완료');
|
||||
} catch (e) {
|
||||
debugPrint('[BLE] Peripheral 초기화 실패: $e');
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
/// 공유 코드로 수신 대기 시작
|
||||
Future<void> startListening(String code) async {
|
||||
await initializePeripheral();
|
||||
|
||||
// 기존 서비스 정리
|
||||
await _cleanupPeripheral();
|
||||
|
||||
_currentShareCode = code;
|
||||
_receivedChunks.clear();
|
||||
_expectedTotalChunks = 0;
|
||||
|
||||
try {
|
||||
// GATT 서비스 추가
|
||||
await ble_peripheral.BlePeripheral.addService(
|
||||
ble_peripheral.BleService(
|
||||
uuid: BleConstants.serviceUuid,
|
||||
primary: true,
|
||||
characteristics: [
|
||||
// 데이터 수신용 Characteristic (writable)
|
||||
ble_peripheral.BleCharacteristic(
|
||||
uuid: BleConstants.dataCharacteristicUuid,
|
||||
properties: [
|
||||
ble_peripheral.CharacteristicProperties.write.index,
|
||||
ble_peripheral.CharacteristicProperties.writeWithoutResponse.index,
|
||||
],
|
||||
permissions: [ble_peripheral.AttributePermissions.writeable.index],
|
||||
value: null,
|
||||
),
|
||||
// 공유 코드 확인용 Characteristic (readable)
|
||||
ble_peripheral.BleCharacteristic(
|
||||
uuid: BleConstants.codeCharacteristicUuid,
|
||||
properties: [ble_peripheral.CharacteristicProperties.read.index],
|
||||
permissions: [ble_peripheral.AttributePermissions.readable.index],
|
||||
value: Uint8List.fromList(utf8.encode(code)),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
// 광고 시작
|
||||
await ble_peripheral.BlePeripheral.startAdvertising(
|
||||
services: [BleConstants.serviceUuid],
|
||||
localName: '${BleConstants.advertiseNamePrefix}$code',
|
||||
);
|
||||
|
||||
debugPrint('[BLE] 광고 시작: ${BleConstants.advertiseNamePrefix}$code');
|
||||
} catch (e) {
|
||||
debugPrint('[BLE] 광고 시작 실패: $e');
|
||||
_currentShareCode = null;
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
/// Write 콜백 설정
|
||||
void _setupWriteCallback() {
|
||||
ble_peripheral.BlePeripheral.setWriteRequestCallback((
|
||||
deviceId,
|
||||
characteristicId,
|
||||
offset,
|
||||
value,
|
||||
) {
|
||||
if (characteristicId.toLowerCase() ==
|
||||
BleConstants.dataCharacteristicUuid.toLowerCase()) {
|
||||
_handleReceivedChunk(value ?? Uint8List(0));
|
||||
}
|
||||
// null 반환 = 성공 (ble_peripheral 패키지 규약)
|
||||
return null;
|
||||
});
|
||||
|
||||
debugPrint('[BLE] Write 콜백 설정 완료');
|
||||
}
|
||||
|
||||
/// 수신된 청크 처리
|
||||
void _handleReceivedChunk(Uint8List data) {
|
||||
try {
|
||||
final decoded = utf8.decode(data);
|
||||
debugPrint('[BLE] 청크 수신: ${decoded.substring(0, decoded.length.clamp(0, 50))}...');
|
||||
|
||||
// 프로토콜: "CHUNK:index:total:data"
|
||||
if (decoded.startsWith('CHUNK:')) {
|
||||
final colonIndex1 = decoded.indexOf(':', 6);
|
||||
final colonIndex2 = decoded.indexOf(':', colonIndex1 + 1);
|
||||
|
||||
if (colonIndex1 == -1 || colonIndex2 == -1) {
|
||||
debugPrint('[BLE] 잘못된 청크 형식');
|
||||
return;
|
||||
}
|
||||
|
||||
final index = int.tryParse(decoded.substring(6, colonIndex1));
|
||||
final total = int.tryParse(decoded.substring(colonIndex1 + 1, colonIndex2));
|
||||
final chunkData = decoded.substring(colonIndex2 + 1);
|
||||
|
||||
if (index == null || total == null) {
|
||||
debugPrint('[BLE] 청크 인덱스/전체 파싱 실패');
|
||||
return;
|
||||
}
|
||||
|
||||
_expectedTotalChunks = total;
|
||||
_receivedChunks[index] = chunkData;
|
||||
|
||||
// 진행 상태 콜백
|
||||
onReceiveProgress?.call(_receivedChunks.length, total);
|
||||
|
||||
debugPrint('[BLE] 청크 $index/$total 수신 완료');
|
||||
|
||||
// 모든 청크 수신 완료
|
||||
if (_receivedChunks.length == total) {
|
||||
_assembleAndEmit();
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint('[BLE] 청크 처리 오류: $e');
|
||||
}
|
||||
}
|
||||
|
||||
/// 청크 조립 후 스트림으로 전송
|
||||
void _assembleAndEmit() {
|
||||
final sorted = _receivedChunks.entries.toList()
|
||||
..sort((a, b) => a.key.compareTo(b.key));
|
||||
final fullData = sorted.map((e) => e.value).join();
|
||||
|
||||
debugPrint('[BLE] 데이터 조립 완료: ${fullData.length} bytes');
|
||||
|
||||
_incomingDataController.add(fullData);
|
||||
_receivedChunks.clear();
|
||||
_expectedTotalChunks = 0;
|
||||
}
|
||||
|
||||
/// Peripheral 정리
|
||||
Future<void> _cleanupPeripheral() async {
|
||||
try {
|
||||
await ble_peripheral.BlePeripheral.stopAdvertising();
|
||||
await ble_peripheral.BlePeripheral.clearServices();
|
||||
} catch (e) {
|
||||
debugPrint('[BLE] Peripheral 정리 중 오류 (무시됨): $e');
|
||||
}
|
||||
}
|
||||
|
||||
/// 수신 대기 중지
|
||||
Future<void> stopListening() async {
|
||||
await _cleanupPeripheral();
|
||||
_currentShareCode = null;
|
||||
_receivedChunks.clear();
|
||||
_expectedTotalChunks = 0;
|
||||
debugPrint('[BLE] 광고 중지');
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Sender (Central) 메서드 - flutter_blue_plus 사용
|
||||
// =========================================================================
|
||||
|
||||
/// 주변 LunchPick 기기 스캔
|
||||
Future<List<ShareDevice>> scanNearbyDevices() async {
|
||||
_discoveredDevices.clear();
|
||||
|
||||
// Bluetooth 상태 확인
|
||||
if (!await isBluetoothOn) {
|
||||
throw Exception('블루투스가 꺼져 있습니다. 블루투스를 켜주세요.');
|
||||
}
|
||||
|
||||
debugPrint('[BLE] 스캔 시작...');
|
||||
|
||||
// 스캔 결과 리스닝
|
||||
_scanSubscription = FlutterBluePlus.scanResults.listen(
|
||||
(results) {
|
||||
for (final result in results) {
|
||||
_processScannedDevice(result);
|
||||
}
|
||||
},
|
||||
onError: (e) {
|
||||
debugPrint('[BLE] 스캔 오류: $e');
|
||||
},
|
||||
);
|
||||
|
||||
try {
|
||||
// 서비스 UUID로 필터링하여 스캔
|
||||
await FlutterBluePlus.startScan(
|
||||
withServices: [Guid(BleConstants.serviceUuid)],
|
||||
timeout: Duration(seconds: BleConstants.scanTimeoutSeconds),
|
||||
);
|
||||
|
||||
// 스캔 완료 대기
|
||||
await Future.delayed(
|
||||
Duration(seconds: BleConstants.scanTimeoutSeconds + 1),
|
||||
);
|
||||
} catch (e) {
|
||||
debugPrint('[BLE] 스캔 시작 오류: $e');
|
||||
} finally {
|
||||
await _scanSubscription?.cancel();
|
||||
_scanSubscription = null;
|
||||
}
|
||||
|
||||
debugPrint('[BLE] 스캔 완료: ${_discoveredDevices.length}개 기기 발견');
|
||||
return List.from(_discoveredDevices);
|
||||
}
|
||||
|
||||
/// 스캔된 디바이스 처리
|
||||
void _processScannedDevice(ScanResult result) {
|
||||
// 서비스 UUID 확인
|
||||
final hasService = result.advertisementData.serviceUuids.any(
|
||||
(uuid) =>
|
||||
uuid.toString().toLowerCase() ==
|
||||
BleConstants.serviceUuid.toLowerCase(),
|
||||
);
|
||||
|
||||
if (!hasService) return;
|
||||
|
||||
// 광고 이름에서 공유 코드 추출
|
||||
final name = result.advertisementData.advName;
|
||||
if (name.isEmpty) return;
|
||||
|
||||
final code = name.startsWith(BleConstants.advertiseNamePrefix)
|
||||
? name.substring(BleConstants.advertiseNamePrefix.length)
|
||||
: name;
|
||||
|
||||
// 중복 방지
|
||||
if (_discoveredDevices.any((d) => d.deviceId == result.device.remoteId.str)) {
|
||||
return;
|
||||
}
|
||||
|
||||
final device = ShareDevice(
|
||||
code: code,
|
||||
deviceId: result.device.remoteId.str,
|
||||
remoteId: result.device.remoteId.str,
|
||||
rssi: result.rssi,
|
||||
discoveredAt: DateTime.now(),
|
||||
bleDevice: result.device,
|
||||
);
|
||||
|
||||
_discoveredDevices.add(device);
|
||||
debugPrint('[BLE] 기기 발견: $code (RSSI: ${result.rssi})');
|
||||
}
|
||||
|
||||
/// 맛집 리스트 전송
|
||||
Future<void> sendRestaurantList(
|
||||
String targetCode,
|
||||
List<Restaurant> restaurants,
|
||||
) async {
|
||||
await Future<void>.delayed(const Duration(seconds: 1));
|
||||
if (!_listeningDevices.containsKey(targetCode)) {
|
||||
throw Exception('해당 코드를 찾을 수 없습니다.');
|
||||
// 대상 디바이스 찾기
|
||||
final targetDevice = _discoveredDevices.firstWhere(
|
||||
(d) => d.code == targetCode,
|
||||
orElse: () => throw Exception('대상 기기를 찾을 수 없습니다: $targetCode'),
|
||||
);
|
||||
|
||||
final bleDevice = targetDevice.bleDevice;
|
||||
if (bleDevice == null) {
|
||||
throw Exception('BLE 디바이스 정보가 없습니다.');
|
||||
}
|
||||
|
||||
final payload = jsonEncode(
|
||||
restaurants
|
||||
.map((restaurant) => _serializeRestaurant(restaurant))
|
||||
.toList(),
|
||||
debugPrint('[BLE] 연결 시작: $targetCode');
|
||||
|
||||
// 연결
|
||||
await bleDevice.connect(
|
||||
timeout: Duration(seconds: BleConstants.connectionTimeoutSeconds),
|
||||
);
|
||||
_incomingDataController.add(payload);
|
||||
_connectedDevice = bleDevice;
|
||||
|
||||
try {
|
||||
// 서비스 탐색
|
||||
debugPrint('[BLE] 서비스 탐색 중...');
|
||||
final services = await bleDevice.discoverServices();
|
||||
|
||||
final targetService = services.firstWhere(
|
||||
(s) =>
|
||||
s.uuid.toString().toLowerCase() ==
|
||||
BleConstants.serviceUuid.toLowerCase(),
|
||||
orElse: () => throw Exception('LunchPick 서비스를 찾을 수 없습니다.'),
|
||||
);
|
||||
|
||||
final dataCharacteristic = targetService.characteristics.firstWhere(
|
||||
(c) =>
|
||||
c.uuid.toString().toLowerCase() ==
|
||||
BleConstants.dataCharacteristicUuid.toLowerCase(),
|
||||
orElse: () => throw Exception('데이터 Characteristic을 찾을 수 없습니다.'),
|
||||
);
|
||||
|
||||
// JSON 직렬화
|
||||
final payload = jsonEncode(
|
||||
restaurants.map(_serializeRestaurant).toList(),
|
||||
);
|
||||
|
||||
debugPrint('[BLE] 전송 데이터 크기: ${payload.length} bytes');
|
||||
|
||||
// 청킹 및 전송
|
||||
final chunks = _splitIntoChunks(payload, BleConstants.chunkSize);
|
||||
debugPrint('[BLE] 청크 수: ${chunks.length}');
|
||||
|
||||
for (var i = 0; i < chunks.length; i++) {
|
||||
final chunkMessage = 'CHUNK:$i:${chunks.length}:${chunks[i]}';
|
||||
final data = utf8.encode(chunkMessage);
|
||||
|
||||
await dataCharacteristic.write(
|
||||
data,
|
||||
withoutResponse: false,
|
||||
);
|
||||
|
||||
// 진행 상태 콜백
|
||||
onSendProgress?.call(i + 1, chunks.length);
|
||||
|
||||
debugPrint('[BLE] 청크 ${i + 1}/${chunks.length} 전송 완료');
|
||||
|
||||
// 청크 간 딜레이
|
||||
if (i < chunks.length - 1) {
|
||||
await Future.delayed(
|
||||
Duration(milliseconds: BleConstants.chunkDelayMs),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
debugPrint('[BLE] 전송 완료!');
|
||||
} finally {
|
||||
// 연결 해제
|
||||
await bleDevice.disconnect();
|
||||
_connectedDevice = null;
|
||||
debugPrint('[BLE] 연결 해제');
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, dynamic> _serializeRestaurant(Restaurant restaurant) {
|
||||
return {
|
||||
'id': restaurant.id,
|
||||
'name': restaurant.name,
|
||||
'category': restaurant.category,
|
||||
'subCategory': restaurant.subCategory,
|
||||
'description': restaurant.description,
|
||||
'phoneNumber': restaurant.phoneNumber,
|
||||
'roadAddress': restaurant.roadAddress,
|
||||
'jibunAddress': restaurant.jibunAddress,
|
||||
'latitude': restaurant.latitude,
|
||||
'longitude': restaurant.longitude,
|
||||
'lastVisitDate': restaurant.lastVisitDate?.toIso8601String(),
|
||||
'source': restaurant.source.name,
|
||||
'createdAt': restaurant.createdAt.toIso8601String(),
|
||||
'updatedAt': restaurant.updatedAt.toIso8601String(),
|
||||
'naverPlaceId': restaurant.naverPlaceId,
|
||||
'naverUrl': restaurant.naverUrl,
|
||||
'businessHours': restaurant.businessHours,
|
||||
'lastVisited': restaurant.lastVisited?.toIso8601String(),
|
||||
'visitCount': restaurant.visitCount,
|
||||
};
|
||||
/// 문자열을 청크로 분할
|
||||
List<String> _splitIntoChunks(String data, int chunkSize) {
|
||||
final chunks = <String>[];
|
||||
for (var i = 0; i < data.length; i += chunkSize) {
|
||||
final end = (i + chunkSize > data.length) ? data.length : i + chunkSize;
|
||||
chunks.add(data.substring(i, end));
|
||||
}
|
||||
return chunks;
|
||||
}
|
||||
|
||||
/// Restaurant를 JSON Map으로 변환
|
||||
Map<String, dynamic> _serializeRestaurant(Restaurant r) => {
|
||||
'id': r.id,
|
||||
'name': r.name,
|
||||
'category': r.category,
|
||||
'subCategory': r.subCategory,
|
||||
'description': r.description,
|
||||
'phoneNumber': r.phoneNumber,
|
||||
'roadAddress': r.roadAddress,
|
||||
'jibunAddress': r.jibunAddress,
|
||||
'latitude': r.latitude,
|
||||
'longitude': r.longitude,
|
||||
'lastVisitDate': r.lastVisitDate?.toIso8601String(),
|
||||
'source': r.source.name,
|
||||
'createdAt': r.createdAt.toIso8601String(),
|
||||
'updatedAt': r.updatedAt.toIso8601String(),
|
||||
'naverPlaceId': r.naverPlaceId,
|
||||
'naverUrl': r.naverUrl,
|
||||
'businessHours': r.businessHours,
|
||||
'lastVisited': r.lastVisited?.toIso8601String(),
|
||||
'visitCount': r.visitCount,
|
||||
};
|
||||
|
||||
/// 스캔 중지
|
||||
Future<void> stopScan() async {
|
||||
await FlutterBluePlus.stopScan();
|
||||
await _scanSubscription?.cancel();
|
||||
_scanSubscription = null;
|
||||
_discoveredDevices.clear();
|
||||
debugPrint('[BLE] 스캔 중지');
|
||||
}
|
||||
|
||||
/// 리소스 정리
|
||||
void dispose() {
|
||||
_incomingDataController.close();
|
||||
_listeningDevices.clear();
|
||||
_scanSubscription?.cancel();
|
||||
_connectedDevice?.disconnect();
|
||||
_cleanupPeripheral();
|
||||
debugPrint('[BLE] BluetoothService disposed');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,8 +17,11 @@ class GeocodingService {
|
||||
Future<({double latitude, double longitude})?> geocode(String address) async {
|
||||
if (address.trim().isEmpty) return null;
|
||||
|
||||
// 주소 전처리: 상세 주소(층수, 상호명 등) 제거
|
||||
final cleanedAddress = _cleanAddress(address);
|
||||
|
||||
// 1차: VWorld 지오코딩 시도 (키가 존재할 때만)
|
||||
final vworldResult = await _geocodeWithVworld(address);
|
||||
final vworldResult = await _geocodeWithVworld(cleanedAddress);
|
||||
if (vworldResult != null) {
|
||||
return vworldResult;
|
||||
}
|
||||
@@ -26,7 +29,7 @@ class GeocodingService {
|
||||
// 2차: Nominatim (fallback)
|
||||
try {
|
||||
final uri = Uri.parse(
|
||||
'$_endpoint?format=json&limit=1&q=${Uri.encodeQueryComponent(address)}',
|
||||
'$_endpoint?format=json&limit=1&q=${Uri.encodeQueryComponent(cleanedAddress)}',
|
||||
);
|
||||
|
||||
// Nominatim은 User-Agent 헤더를 요구한다.
|
||||
@@ -121,4 +124,39 @@ class GeocodingService {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// 주소에서 상세 주소(층수, 상호명 등)를 제거하여 순수 도로명 주소만 추출한다.
|
||||
///
|
||||
/// 예시:
|
||||
/// - "서울 관악구 관악로14길 6-4 1층 이자카야 혼네" → "서울 관악구 관악로14길 6-4"
|
||||
/// - "서울특별시 강남구 테헤란로 123 B1 스타벅스" → "서울특별시 강남구 테헤란로 123"
|
||||
String _cleanAddress(String address) {
|
||||
final trimmed = address.trim();
|
||||
|
||||
// 패턴 1: 건물번호 뒤에 층수 정보가 있는 경우 (1층, B1, 지하1층 등)
|
||||
// 도로명 주소의 건물번호는 숫자 또는 숫자-숫자 형태
|
||||
final floorPattern = RegExp(
|
||||
r'(\d+(?:-\d+)?)\s+(?:\d+층|[Bb]\d+|지하\d*층?).*$',
|
||||
);
|
||||
final floorMatch = floorPattern.firstMatch(trimmed);
|
||||
if (floorMatch != null) {
|
||||
final buildingNumber = floorMatch.group(1);
|
||||
final beforeMatch = trimmed.substring(0, floorMatch.start);
|
||||
return '$beforeMatch$buildingNumber'.trim();
|
||||
}
|
||||
|
||||
// 패턴 2: 건물번호 뒤에 상호명이 바로 오는 경우 (공백 + 한글/영문)
|
||||
// 단, 구/동/로/길 같은 주소 구성요소는 제외
|
||||
final namePattern = RegExp(
|
||||
r'(\d+(?:-\d+)?)\s+(?![가-힣]+[구동로길읍면리]\s)([가-힣a-zA-Z&]+.*)$',
|
||||
);
|
||||
final nameMatch = namePattern.firstMatch(trimmed);
|
||||
if (nameMatch != null) {
|
||||
final buildingNumber = nameMatch.group(1);
|
||||
final beforeMatch = trimmed.substring(0, nameMatch.start);
|
||||
return '$beforeMatch$buildingNumber'.trim();
|
||||
}
|
||||
|
||||
return trimmed;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,149 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../constants/app_colors.dart';
|
||||
import '../constants/app_typography.dart';
|
||||
|
||||
/// 빈 상태 위젯
|
||||
///
|
||||
/// 데이터가 없을 때 표시하는 공통 위젯
|
||||
class EmptyStateWidget extends StatelessWidget {
|
||||
/// 제목
|
||||
final String title;
|
||||
|
||||
/// 설명 메시지 (선택사항)
|
||||
final String? message;
|
||||
|
||||
/// 아이콘 (선택사항)
|
||||
final IconData? icon;
|
||||
|
||||
/// 아이콘 크기
|
||||
final double iconSize;
|
||||
|
||||
/// 액션 버튼 텍스트 (선택사항)
|
||||
final String? actionText;
|
||||
|
||||
/// 액션 버튼 콜백 (선택사항)
|
||||
final VoidCallback? onAction;
|
||||
|
||||
/// 커스텀 위젯 (아이콘 대신 사용할 수 있음)
|
||||
final Widget? customWidget;
|
||||
|
||||
const EmptyStateWidget({
|
||||
super.key,
|
||||
required this.title,
|
||||
this.message,
|
||||
this.icon,
|
||||
this.iconSize = 80.0,
|
||||
this.actionText,
|
||||
this.onAction,
|
||||
this.customWidget,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
|
||||
return Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(32.0),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
// 아이콘 또는 커스텀 위젯
|
||||
if (customWidget != null)
|
||||
customWidget!
|
||||
else if (icon != null)
|
||||
Container(
|
||||
padding: const EdgeInsets.all(24),
|
||||
decoration: BoxDecoration(
|
||||
color:
|
||||
(isDark ? AppColors.darkPrimary : AppColors.lightPrimary)
|
||||
.withValues(alpha: 0.1),
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
child: Icon(
|
||||
icon,
|
||||
size: iconSize,
|
||||
color: isDark
|
||||
? AppColors.darkTextSecondary
|
||||
: AppColors.lightTextSecondary,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// 제목
|
||||
Text(
|
||||
title,
|
||||
style: AppTypography.heading2(isDark),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
|
||||
// 설명 메시지 (있을 경우)
|
||||
if (message != null) ...[
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
message!,
|
||||
style: AppTypography.body2(isDark),
|
||||
textAlign: TextAlign.center,
|
||||
maxLines: 3,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
],
|
||||
|
||||
// 액션 버튼 (있을 경우)
|
||||
if (actionText != null && onAction != null) ...[
|
||||
const SizedBox(height: 32),
|
||||
ElevatedButton(
|
||||
onPressed: onAction,
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: isDark
|
||||
? AppColors.darkPrimary
|
||||
: AppColors.lightPrimary,
|
||||
foregroundColor: Colors.white,
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 32,
|
||||
vertical: 12,
|
||||
),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
),
|
||||
child: Text(
|
||||
actionText!,
|
||||
style: const TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 리스트 빈 상태 위젯
|
||||
///
|
||||
/// 리스트나 그리드가 비어있을 때 사용하는 특화된 위젯
|
||||
class ListEmptyStateWidget extends StatelessWidget {
|
||||
/// 아이템 유형 (예: "식당", "기록" 등)
|
||||
final String itemType;
|
||||
|
||||
/// 추가 액션 콜백 (선택사항)
|
||||
final VoidCallback? onAdd;
|
||||
|
||||
const ListEmptyStateWidget({super.key, required this.itemType, this.onAdd});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return EmptyStateWidget(
|
||||
icon: Icons.inbox_outlined,
|
||||
title: '$itemType이(가) 없습니다',
|
||||
message: '새로운 $itemType을(를) 추가해보세요',
|
||||
actionText: onAdd != null ? '$itemType 추가' : null,
|
||||
onAction: onAdd,
|
||||
);
|
||||
}
|
||||
}
|
||||
58
lib/core/widgets/info_row.dart
Normal file
58
lib/core/widgets/info_row.dart
Normal file
@@ -0,0 +1,58 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../constants/app_dimensions.dart';
|
||||
import '../constants/app_typography.dart';
|
||||
|
||||
/// 상세 정보를 표시하는 공통 행 위젯
|
||||
/// [label]과 [value]를 수직 또는 수평으로 배치
|
||||
class InfoRow extends StatelessWidget {
|
||||
final String label;
|
||||
final String value;
|
||||
final bool isDark;
|
||||
|
||||
/// true: 수평 배치 (레이블 | 값), false: 수직 배치 (레이블 위, 값 아래)
|
||||
final bool horizontal;
|
||||
|
||||
/// 수평 배치 시 레이블 영역 너비
|
||||
final double? labelWidth;
|
||||
|
||||
const InfoRow({
|
||||
super.key,
|
||||
required this.label,
|
||||
required this.value,
|
||||
required this.isDark,
|
||||
this.horizontal = false,
|
||||
this.labelWidth = 80,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (horizontal) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: AppDimensions.paddingXs),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
SizedBox(
|
||||
width: labelWidth,
|
||||
child: Text(label, style: AppTypography.caption(isDark)),
|
||||
),
|
||||
const SizedBox(width: AppDimensions.paddingSm),
|
||||
Expanded(child: Text(value, style: AppTypography.body2(isDark))),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: AppDimensions.paddingXs),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(label, style: AppTypography.caption(isDark)),
|
||||
const SizedBox(height: 2),
|
||||
Text(value, style: AppTypography.body2(isDark)),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../constants/app_colors.dart';
|
||||
|
||||
/// 로딩 인디케이터 위젯
|
||||
///
|
||||
/// 앱 전체에서 일관된 로딩 표시를 위한 공통 위젯
|
||||
class LoadingIndicator extends StatelessWidget {
|
||||
/// 로딩 메시지 (선택사항)
|
||||
final String? message;
|
||||
|
||||
/// 인디케이터 크기
|
||||
final double size;
|
||||
|
||||
/// 스트로크 너비
|
||||
final double strokeWidth;
|
||||
|
||||
const LoadingIndicator({
|
||||
super.key,
|
||||
this.message,
|
||||
this.size = 40.0,
|
||||
this.strokeWidth = 4.0,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
|
||||
return Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
SizedBox(
|
||||
width: size,
|
||||
height: size,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: strokeWidth,
|
||||
valueColor: AlwaysStoppedAnimation<Color>(
|
||||
isDark ? AppColors.darkPrimary : AppColors.lightPrimary,
|
||||
),
|
||||
),
|
||||
),
|
||||
if (message != null) ...[
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
message!,
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
color: isDark
|
||||
? AppColors.darkTextSecondary
|
||||
: AppColors.lightTextSecondary,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 전체 화면 로딩 인디케이터
|
||||
///
|
||||
/// 화면 전체를 덮는 로딩 표시를 위한 위젯
|
||||
class FullScreenLoadingIndicator extends StatelessWidget {
|
||||
/// 로딩 메시지 (선택사항)
|
||||
final String? message;
|
||||
|
||||
/// 배경 투명도
|
||||
final double backgroundOpacity;
|
||||
|
||||
const FullScreenLoadingIndicator({
|
||||
super.key,
|
||||
this.message,
|
||||
this.backgroundOpacity = 0.5,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
|
||||
return Container(
|
||||
color: (isDark ? Colors.black : Colors.white).withValues(
|
||||
alpha: backgroundOpacity,
|
||||
),
|
||||
child: LoadingIndicator(message: message),
|
||||
);
|
||||
}
|
||||
}
|
||||
147
lib/core/widgets/skeleton_loader.dart
Normal file
147
lib/core/widgets/skeleton_loader.dart
Normal file
@@ -0,0 +1,147 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../constants/app_colors.dart';
|
||||
import '../constants/app_dimensions.dart';
|
||||
|
||||
/// Shimmer 효과를 가진 스켈톤 로더
|
||||
class SkeletonLoader extends StatefulWidget {
|
||||
final double width;
|
||||
final double height;
|
||||
final double borderRadius;
|
||||
|
||||
const SkeletonLoader({
|
||||
super.key,
|
||||
this.width = double.infinity,
|
||||
required this.height,
|
||||
this.borderRadius = AppDimensions.radiusSm,
|
||||
});
|
||||
|
||||
@override
|
||||
State<SkeletonLoader> createState() => _SkeletonLoaderState();
|
||||
}
|
||||
|
||||
class _SkeletonLoaderState extends State<SkeletonLoader>
|
||||
with SingleTickerProviderStateMixin {
|
||||
late AnimationController _controller;
|
||||
late Animation<double> _animation;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_controller = AnimationController(
|
||||
duration: const Duration(milliseconds: 1500),
|
||||
vsync: this,
|
||||
)..repeat();
|
||||
|
||||
_animation = Tween<double>(begin: -1.0, end: 2.0).animate(
|
||||
CurvedAnimation(parent: _controller, curve: Curves.easeInOutSine),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
final baseColor = isDark
|
||||
? AppColors.darkSurface.withValues(alpha: 0.6)
|
||||
: Colors.grey.shade300;
|
||||
final highlightColor = isDark
|
||||
? AppColors.darkSurface.withValues(alpha: 0.9)
|
||||
: Colors.grey.shade100;
|
||||
|
||||
return AnimatedBuilder(
|
||||
animation: _animation,
|
||||
builder: (context, child) {
|
||||
return Container(
|
||||
width: widget.width,
|
||||
height: widget.height,
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(widget.borderRadius),
|
||||
gradient: LinearGradient(
|
||||
begin: Alignment.centerLeft,
|
||||
end: Alignment.centerRight,
|
||||
colors: [baseColor, highlightColor, baseColor],
|
||||
stops: [
|
||||
(_animation.value - 1).clamp(0.0, 1.0),
|
||||
_animation.value.clamp(0.0, 1.0),
|
||||
(_animation.value + 1).clamp(0.0, 1.0),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 맛집 카드 스켈톤
|
||||
class RestaurantCardSkeleton extends StatelessWidget {
|
||||
const RestaurantCardSkeleton({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
|
||||
return Card(
|
||||
margin: const EdgeInsets.symmetric(
|
||||
horizontal: AppDimensions.paddingDefault,
|
||||
vertical: AppDimensions.paddingSm,
|
||||
),
|
||||
color: isDark ? AppColors.darkSurface : AppColors.lightSurface,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(AppDimensions.paddingDefault),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
// 카테고리 아이콘 영역
|
||||
const SkeletonLoader(
|
||||
width: AppDimensions.cardIconSize,
|
||||
height: AppDimensions.cardIconSize,
|
||||
),
|
||||
const SizedBox(width: AppDimensions.paddingMd),
|
||||
// 가게 정보 영역
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const SkeletonLoader(height: 20, width: 150),
|
||||
const SizedBox(height: AppDimensions.paddingXs),
|
||||
const SkeletonLoader(height: 14, width: 100),
|
||||
],
|
||||
),
|
||||
),
|
||||
// 거리 배지
|
||||
const SkeletonLoader(width: 60, height: 28, borderRadius: 14),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: AppDimensions.paddingMd),
|
||||
// 주소
|
||||
const SkeletonLoader(height: 14),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 맛집 리스트 스켈톤
|
||||
class RestaurantListSkeleton extends StatelessWidget {
|
||||
final int itemCount;
|
||||
|
||||
const RestaurantListSkeleton({super.key, this.itemCount = 5});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ListView.builder(
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
itemCount: itemCount,
|
||||
itemBuilder: (context, index) => const RestaurantCardSkeleton(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -34,9 +34,12 @@ class NaverApiClient {
|
||||
_proxyClient = NaverProxyClient(networkClient: _networkClient);
|
||||
}
|
||||
|
||||
/// 네이버 로컬 검색 API 호출
|
||||
/// 네이버 로컬 검색 API 호출 (현재 비활성화됨)
|
||||
///
|
||||
/// 검색어와 좌표를 기반으로 주변 식당을 검색합니다.
|
||||
/// 개인정보 처리방침 및 운영 정책에 따라
|
||||
/// 네이버 로컬 검색 Open API(키 기반 검색)는 사용하지 않는다.
|
||||
/// 이 메서드는 네트워크 요청을 보내지 않고 항상 빈 리스트를 반환한다.
|
||||
/// (향후 정책 변경 시, 기존 구현을 복원하여 사용할 수 있다.)
|
||||
Future<List<NaverLocalSearchResult>> searchLocal({
|
||||
required String query,
|
||||
double? latitude,
|
||||
@@ -45,14 +48,10 @@ class NaverApiClient {
|
||||
int start = 1,
|
||||
String sort = 'random',
|
||||
}) async {
|
||||
return _localSearchApi.searchLocal(
|
||||
query: query,
|
||||
latitude: latitude,
|
||||
longitude: longitude,
|
||||
display: display,
|
||||
start: start,
|
||||
sort: sort,
|
||||
AppLogger.debug(
|
||||
'[NaverApiClient] searchLocal 호출됨 - 로컬 검색 Open API는 현재 비활성화 상태입니다.',
|
||||
);
|
||||
return <NaverLocalSearchResult>[];
|
||||
}
|
||||
|
||||
/// 단축 URL을 실제 URL로 변환
|
||||
|
||||
@@ -1,553 +0,0 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../../core/constants/api_keys.dart';
|
||||
import '../../core/network/network_client.dart';
|
||||
import '../../core/network/network_config.dart';
|
||||
import '../../core/errors/network_exceptions.dart';
|
||||
import '../../domain/entities/restaurant.dart';
|
||||
import '../datasources/remote/naver_html_extractor.dart';
|
||||
|
||||
/// 네이버 API 클라이언트
|
||||
///
|
||||
/// 네이버 오픈 API와 지도 서비스를 위한 통합 클라이언트입니다.
|
||||
class NaverApiClient {
|
||||
final NetworkClient _networkClient;
|
||||
|
||||
NaverApiClient({NetworkClient? networkClient})
|
||||
: _networkClient = networkClient ?? NetworkClient();
|
||||
|
||||
/// 네이버 로컬 검색 API 호출
|
||||
///
|
||||
/// 검색어와 좌표를 기반으로 주변 식당을 검색합니다.
|
||||
Future<List<NaverLocalSearchResult>> searchLocal({
|
||||
required String query,
|
||||
double? latitude,
|
||||
double? longitude,
|
||||
int display = 20,
|
||||
int start = 1,
|
||||
String sort = 'random', // random, comment
|
||||
}) async {
|
||||
// API 키 확인
|
||||
if (!ApiKeys.areKeysConfigured()) {
|
||||
throw ApiKeyException();
|
||||
}
|
||||
|
||||
try {
|
||||
final response = await _networkClient.get<Map<String, dynamic>>(
|
||||
ApiKeys.naverLocalSearchEndpoint,
|
||||
queryParameters: {
|
||||
'query': query,
|
||||
'display': display,
|
||||
'start': start,
|
||||
'sort': sort,
|
||||
if (latitude != null && longitude != null) ...{
|
||||
'coordinate': '$longitude,$latitude', // 경도,위도 순서
|
||||
},
|
||||
},
|
||||
options: Options(
|
||||
headers: {
|
||||
'X-Naver-Client-Id': ApiKeys.naverClientId,
|
||||
'X-Naver-Client-Secret': ApiKeys.naverClientSecret,
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
if (response.statusCode == 200 && response.data != null) {
|
||||
final items = response.data!['items'] as List<dynamic>?;
|
||||
if (items == null || items.isEmpty) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return items
|
||||
.map(
|
||||
(item) =>
|
||||
NaverLocalSearchResult.fromJson(item as Map<String, dynamic>),
|
||||
)
|
||||
.toList();
|
||||
}
|
||||
|
||||
throw ParseException(message: '검색 결과를 파싱할 수 없습니다');
|
||||
} on DioException catch (e) {
|
||||
// 에러는 NetworkClient에서 이미 변환됨
|
||||
throw e.error ??
|
||||
ServerException(message: '네이버 API 호출 실패', statusCode: 500);
|
||||
}
|
||||
}
|
||||
|
||||
/// 네이버 단축 URL 리다이렉션 처리
|
||||
///
|
||||
/// naver.me 단축 URL을 실제 지도 URL로 변환합니다.
|
||||
Future<String> resolveShortUrl(String shortUrl) async {
|
||||
if (!shortUrl.contains('naver.me')) {
|
||||
debugPrint('NaverApiClient: 단축 URL이 아님, 원본 반환 - $shortUrl');
|
||||
return shortUrl;
|
||||
}
|
||||
|
||||
try {
|
||||
debugPrint('NaverApiClient: 단축 URL 리디렉션 처리 시작 - $shortUrl');
|
||||
|
||||
// 웹 환경에서는 CORS 프록시 사용
|
||||
if (kIsWeb) {
|
||||
return await _resolveShortUrlViaProxy(shortUrl);
|
||||
}
|
||||
|
||||
// 모바일 환경에서는 여러 단계의 리다이렉션 처리
|
||||
String currentUrl = shortUrl;
|
||||
int redirectCount = 0;
|
||||
const maxRedirects = 10;
|
||||
|
||||
while (redirectCount < maxRedirects) {
|
||||
debugPrint(
|
||||
'NaverApiClient: 리다이렉션 시도 #${redirectCount + 1} - $currentUrl',
|
||||
);
|
||||
|
||||
final response = await _networkClient.get(
|
||||
currentUrl,
|
||||
options: Options(
|
||||
followRedirects: false,
|
||||
validateStatus: (status) => true, // 모든 상태 코드 허용
|
||||
headers: {'User-Agent': NetworkConfig.userAgent},
|
||||
),
|
||||
useCache: false,
|
||||
);
|
||||
|
||||
debugPrint('NaverApiClient: 응답 상태 코드 - ${response.statusCode}');
|
||||
|
||||
// 리다이렉션 체크 (301, 302, 307, 308)
|
||||
if ([301, 302, 307, 308].contains(response.statusCode)) {
|
||||
final location = response.headers['location']?.firstOrNull;
|
||||
if (location != null) {
|
||||
debugPrint('NaverApiClient: Location 헤더 발견 - $location');
|
||||
|
||||
// 상대 경로인 경우 절대 경로로 변환
|
||||
if (!location.startsWith('http')) {
|
||||
final Uri baseUri = Uri.parse(currentUrl);
|
||||
currentUrl = baseUri.resolve(location).toString();
|
||||
} else {
|
||||
currentUrl = location;
|
||||
}
|
||||
|
||||
// 목표 URL에 도달했는지 확인
|
||||
if (currentUrl.contains('pcmap.place.naver.com') ||
|
||||
currentUrl.contains('map.naver.com/p/')) {
|
||||
debugPrint('NaverApiClient: 최종 URL 도착 - $currentUrl');
|
||||
return currentUrl;
|
||||
}
|
||||
|
||||
redirectCount++;
|
||||
} else {
|
||||
debugPrint('NaverApiClient: Location 헤더 없음');
|
||||
break;
|
||||
}
|
||||
} else if (response.statusCode == 200) {
|
||||
// 200 OK인 경우 meta refresh 태그 확인
|
||||
debugPrint('NaverApiClient: 200 OK - meta refresh 태그 확인');
|
||||
|
||||
final String? html = response.data as String?;
|
||||
if (html != null &&
|
||||
html.contains('meta') &&
|
||||
html.contains('refresh')) {
|
||||
final metaRefreshRegex = RegExp(
|
||||
'<meta[^>]+http-equiv=["\']refresh["\'][^>]+content=["\']\\d+;\\s*url=([^"\'>]+)',
|
||||
caseSensitive: false,
|
||||
);
|
||||
|
||||
final match = metaRefreshRegex.firstMatch(html);
|
||||
if (match != null) {
|
||||
final redirectUrl = match.group(1)!;
|
||||
debugPrint('NaverApiClient: Meta refresh URL 발견 - $redirectUrl');
|
||||
|
||||
// 상대 경로 처리
|
||||
if (!redirectUrl.startsWith('http')) {
|
||||
final Uri baseUri = Uri.parse(currentUrl);
|
||||
currentUrl = baseUri.resolve(redirectUrl).toString();
|
||||
} else {
|
||||
currentUrl = redirectUrl;
|
||||
}
|
||||
|
||||
redirectCount++;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// meta refresh가 없으면 현재 URL이 최종 URL
|
||||
debugPrint('NaverApiClient: 200 OK - 최종 URL - $currentUrl');
|
||||
return currentUrl;
|
||||
} else {
|
||||
debugPrint('NaverApiClient: 리다이렉션 아님 - 상태 코드 ${response.statusCode}');
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// 모든 시도 후 현재 URL 반환
|
||||
debugPrint('NaverApiClient: 최종 URL - $currentUrl');
|
||||
return currentUrl;
|
||||
} catch (e) {
|
||||
debugPrint('NaverApiClient: 단축 URL 리다이렉션 실패 - $e');
|
||||
return shortUrl;
|
||||
}
|
||||
}
|
||||
|
||||
/// 프록시를 통한 단축 URL 리다이렉션 (웹 환경)
|
||||
Future<String> _resolveShortUrlViaProxy(String shortUrl) async {
|
||||
try {
|
||||
final proxyUrl =
|
||||
'${NetworkConfig.corsProxyUrl}?url=${Uri.encodeComponent(shortUrl)}';
|
||||
|
||||
final response = await _networkClient.get<Map<String, dynamic>>(
|
||||
proxyUrl,
|
||||
options: Options(headers: {'Accept': 'application/json'}),
|
||||
useCache: false,
|
||||
);
|
||||
|
||||
if (response.statusCode == 200 && response.data != null) {
|
||||
final data = response.data!;
|
||||
|
||||
// status.url 확인
|
||||
if (data['status'] != null &&
|
||||
data['status'] is Map &&
|
||||
data['status']['url'] != null) {
|
||||
final finalUrl = data['status']['url'] as String;
|
||||
debugPrint('NaverApiClient: 프록시 최종 URL - $finalUrl');
|
||||
return finalUrl;
|
||||
}
|
||||
|
||||
// contents에서 meta refresh 태그 찾기
|
||||
final contents = data['contents'] as String?;
|
||||
if (contents != null && contents.isNotEmpty) {
|
||||
final metaRefreshRegex = RegExp(
|
||||
'<meta\\s+http-equiv=["\']refresh["\']'
|
||||
'\\s+content=["\']0;\\s*url=([^"\']+)["\']',
|
||||
caseSensitive: false,
|
||||
);
|
||||
|
||||
final match = metaRefreshRegex.firstMatch(contents);
|
||||
if (match != null) {
|
||||
final redirectUrl = match.group(1)!;
|
||||
debugPrint('NaverApiClient: Meta refresh URL - $redirectUrl');
|
||||
return redirectUrl;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return shortUrl;
|
||||
} catch (e) {
|
||||
debugPrint('NaverApiClient: 프록시 리다이렉션 실패 - $e');
|
||||
return shortUrl;
|
||||
}
|
||||
}
|
||||
|
||||
/// 네이버 지도 HTML 가져오기
|
||||
///
|
||||
/// 웹 환경에서는 CORS 프록시를 사용합니다.
|
||||
Future<String> fetchMapPageHtml(String url) async {
|
||||
try {
|
||||
if (kIsWeb) {
|
||||
return await _fetchViaProxy(url);
|
||||
}
|
||||
|
||||
// 모바일 환경에서는 직접 요청
|
||||
final response = await _networkClient.get<String>(
|
||||
url,
|
||||
options: Options(
|
||||
responseType: ResponseType.plain,
|
||||
headers: {
|
||||
'User-Agent': NetworkConfig.userAgent,
|
||||
'Referer': 'https://map.naver.com',
|
||||
},
|
||||
),
|
||||
useCache: false, // 네이버 지도는 동적 콘텐츠이므로 캐시 사용 안함
|
||||
);
|
||||
|
||||
if (response.statusCode == 200 && response.data != null) {
|
||||
return response.data!;
|
||||
}
|
||||
|
||||
throw ServerException(
|
||||
message: 'HTML을 가져올 수 없습니다',
|
||||
statusCode: response.statusCode ?? 500,
|
||||
);
|
||||
} on DioException catch (e) {
|
||||
throw e.error ??
|
||||
ServerException(message: 'HTML 가져오기 실패', statusCode: 500);
|
||||
}
|
||||
}
|
||||
|
||||
/// 프록시를 통한 HTML 가져오기 (웹 환경)
|
||||
Future<String> _fetchViaProxy(String url) async {
|
||||
final proxyUrl =
|
||||
'${NetworkConfig.corsProxyUrl}?url=${Uri.encodeComponent(url)}';
|
||||
|
||||
final response = await _networkClient.get<Map<String, dynamic>>(
|
||||
proxyUrl,
|
||||
options: Options(headers: {'Accept': 'application/json'}),
|
||||
);
|
||||
|
||||
if (response.statusCode == 200 && response.data != null) {
|
||||
final data = response.data!;
|
||||
|
||||
// 상태 코드 확인
|
||||
if (data['status'] != null && data['status'] is Map) {
|
||||
final statusMap = data['status'] as Map<String, dynamic>;
|
||||
final httpCode = statusMap['http_code'];
|
||||
if (httpCode != null && httpCode != 200) {
|
||||
throw ServerException(
|
||||
message: '네이버 서버 응답 오류',
|
||||
statusCode: httpCode as int,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// contents 반환
|
||||
final contents = data['contents'];
|
||||
if (contents == null || contents.toString().isEmpty) {
|
||||
throw ParseException(message: '빈 응답을 받았습니다');
|
||||
}
|
||||
|
||||
return contents.toString();
|
||||
}
|
||||
|
||||
throw ServerException(
|
||||
message: '프록시 요청 실패',
|
||||
statusCode: response.statusCode ?? 500,
|
||||
);
|
||||
}
|
||||
|
||||
/// GraphQL 쿼리 실행
|
||||
///
|
||||
/// 네이버 지도 API의 GraphQL 엔드포인트에 요청을 보냅니다.
|
||||
Future<Map<String, dynamic>> fetchGraphQL({
|
||||
required String operationName,
|
||||
required Map<String, dynamic> variables,
|
||||
required String query,
|
||||
}) async {
|
||||
const String graphqlUrl = 'https://pcmap-api.place.naver.com/graphql';
|
||||
|
||||
try {
|
||||
final response = await _networkClient.post<Map<String, dynamic>>(
|
||||
graphqlUrl,
|
||||
data: {
|
||||
'operationName': operationName,
|
||||
'variables': variables,
|
||||
'query': query,
|
||||
},
|
||||
options: Options(
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Referer': 'https://map.naver.com/',
|
||||
'User-Agent': NetworkConfig.userAgent,
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
if (response.statusCode == 200 && response.data != null) {
|
||||
return response.data!;
|
||||
}
|
||||
|
||||
throw ParseException(message: 'GraphQL 응답을 파싱할 수 없습니다');
|
||||
} on DioException catch (e) {
|
||||
throw e.error ??
|
||||
ServerException(message: 'GraphQL 요청 실패', statusCode: 500);
|
||||
}
|
||||
}
|
||||
|
||||
/// pcmap URL에서 한글 텍스트 리스트 가져오기
|
||||
///
|
||||
/// restaurant/{ID}/home 형식의 URL에서 모든 한글 텍스트를 추출합니다.
|
||||
Future<Map<String, dynamic>> fetchKoreanTextsFromPcmap(String placeId) async {
|
||||
// restaurant 타입 URL 사용
|
||||
final pcmapUrl = 'https://pcmap.place.naver.com/restaurant/$placeId/home';
|
||||
|
||||
try {
|
||||
debugPrint('========== 네이버 pcmap 한글 추출 시작 ==========');
|
||||
debugPrint('요청 URL: $pcmapUrl');
|
||||
debugPrint('Place ID: $placeId');
|
||||
|
||||
String html;
|
||||
if (kIsWeb) {
|
||||
// 웹 환경에서는 프록시 사용
|
||||
html = await _fetchViaProxy(pcmapUrl);
|
||||
} else {
|
||||
// 모바일 환경에서는 직접 요청
|
||||
final response = await _networkClient.get<String>(
|
||||
pcmapUrl,
|
||||
options: Options(
|
||||
responseType: ResponseType.plain,
|
||||
headers: {
|
||||
'User-Agent': NetworkConfig.userAgent,
|
||||
'Accept': 'text/html,application/xhtml+xml',
|
||||
'Accept-Language': 'ko-KR,ko;q=0.9,en;q=0.8',
|
||||
'Referer': 'https://map.naver.com/',
|
||||
},
|
||||
),
|
||||
useCache: false,
|
||||
);
|
||||
|
||||
if (response.statusCode != 200 || response.data == null) {
|
||||
debugPrint(
|
||||
'NaverApiClient: pcmap 페이지 로드 실패 - status: ${response.statusCode}',
|
||||
);
|
||||
return {
|
||||
'success': false,
|
||||
'error': 'HTTP ${response.statusCode}',
|
||||
'koreanTexts': <String>[],
|
||||
};
|
||||
}
|
||||
|
||||
html = response.data!;
|
||||
}
|
||||
|
||||
// 모든 한글 텍스트 추출
|
||||
final koreanTexts = NaverHtmlExtractor.extractAllValidKoreanTexts(html);
|
||||
|
||||
// JSON-LD 데이터 추출 시도
|
||||
final jsonLdName = NaverHtmlExtractor.extractPlaceNameFromJsonLd(html);
|
||||
|
||||
// Apollo State 데이터 추출 시도
|
||||
final apolloName = NaverHtmlExtractor.extractPlaceNameFromApolloState(html);
|
||||
|
||||
debugPrint('========== 추출 결과 ==========');
|
||||
debugPrint('총 한글 텍스트 수: ${koreanTexts.length}');
|
||||
debugPrint('JSON-LD 상호명: $jsonLdName');
|
||||
debugPrint('Apollo State 상호명: $apolloName');
|
||||
debugPrint('=====================================');
|
||||
|
||||
return {
|
||||
'success': true,
|
||||
'placeId': placeId,
|
||||
'url': pcmapUrl,
|
||||
'koreanTexts': koreanTexts,
|
||||
'jsonLdName': jsonLdName,
|
||||
'apolloStateName': apolloName,
|
||||
'extractedAt': DateTime.now().toIso8601String(),
|
||||
};
|
||||
} catch (e) {
|
||||
debugPrint('NaverApiClient: pcmap 페이지 파싱 실패 - $e');
|
||||
return {
|
||||
'success': false,
|
||||
'error': e.toString(),
|
||||
'koreanTexts': <String>[],
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// 최종 리디렉션 URL 획득
|
||||
///
|
||||
/// 주어진 URL이 리디렉션되는 최종 URL을 반환합니다.
|
||||
Future<String> getFinalRedirectUrl(String url) async {
|
||||
try {
|
||||
debugPrint('NaverApiClient: 최종 리디렉션 URL 획득 중 - $url');
|
||||
|
||||
// 429 에러 방지를 위한 지연
|
||||
await Future.delayed(const Duration(milliseconds: 500));
|
||||
|
||||
final response = await _networkClient.get(
|
||||
url,
|
||||
options: Options(
|
||||
followRedirects: true,
|
||||
maxRedirects: 5,
|
||||
responseType: ResponseType.plain,
|
||||
),
|
||||
useCache: false,
|
||||
);
|
||||
|
||||
final finalUrl = response.realUri.toString();
|
||||
debugPrint('NaverApiClient: 최종 리디렉션 URL - $finalUrl');
|
||||
|
||||
return finalUrl;
|
||||
} catch (e) {
|
||||
debugPrint('NaverApiClient: 최종 리디렉션 URL 획득 실패 - $e');
|
||||
return url;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/// 리소스 정리
|
||||
void dispose() {
|
||||
_networkClient.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// 네이버 로컬 검색 결과
|
||||
class NaverLocalSearchResult {
|
||||
final String title;
|
||||
final String link;
|
||||
final String category;
|
||||
final String description;
|
||||
final String telephone;
|
||||
final String address;
|
||||
final String roadAddress;
|
||||
final int mapx; // 경도 (x좌표)
|
||||
final int mapy; // 위도 (y좌표)
|
||||
|
||||
NaverLocalSearchResult({
|
||||
required this.title,
|
||||
required this.link,
|
||||
required this.category,
|
||||
required this.description,
|
||||
required this.telephone,
|
||||
required this.address,
|
||||
required this.roadAddress,
|
||||
required this.mapx,
|
||||
required this.mapy,
|
||||
});
|
||||
|
||||
factory NaverLocalSearchResult.fromJson(Map<String, dynamic> json) {
|
||||
return NaverLocalSearchResult(
|
||||
title: _removeHtmlTags(json['title'] ?? ''),
|
||||
link: json['link'] ?? '',
|
||||
category: json['category'] ?? '',
|
||||
description: _removeHtmlTags(json['description'] ?? ''),
|
||||
telephone: json['telephone'] ?? '',
|
||||
address: json['address'] ?? '',
|
||||
roadAddress: json['roadAddress'] ?? '',
|
||||
mapx: int.tryParse(json['mapx']?.toString() ?? '0') ?? 0,
|
||||
mapy: int.tryParse(json['mapy']?.toString() ?? '0') ?? 0,
|
||||
);
|
||||
}
|
||||
|
||||
/// HTML 태그 제거
|
||||
static String _removeHtmlTags(String text) {
|
||||
return text.replaceAll(RegExp(r'<[^>]+>'), '');
|
||||
}
|
||||
|
||||
/// 위도 (십진도)
|
||||
double get latitude => mapy / 10000000.0;
|
||||
|
||||
/// 경도 (십진도)
|
||||
double get longitude => mapx / 10000000.0;
|
||||
|
||||
/// Restaurant 엔티티로 변환
|
||||
Restaurant toRestaurant({required String id}) {
|
||||
// 카테고리 파싱
|
||||
final categories = category.split('>').map((c) => c.trim()).toList();
|
||||
final mainCategory = categories.isNotEmpty ? categories.first : '기타';
|
||||
final subCategory = categories.length > 1 ? categories.last : mainCategory;
|
||||
|
||||
return Restaurant(
|
||||
id: id,
|
||||
name: title,
|
||||
category: mainCategory,
|
||||
subCategory: subCategory,
|
||||
description: description.isNotEmpty ? description : null,
|
||||
phoneNumber: telephone.isNotEmpty ? telephone : null,
|
||||
roadAddress: roadAddress.isNotEmpty ? roadAddress : address,
|
||||
jibunAddress: address,
|
||||
latitude: latitude,
|
||||
longitude: longitude,
|
||||
lastVisitDate: null,
|
||||
source: DataSource.NAVER,
|
||||
createdAt: DateTime.now(),
|
||||
updatedAt: DateTime.now(),
|
||||
naverPlaceId: null,
|
||||
naverUrl: link.isNotEmpty ? link : null,
|
||||
businessHours: null,
|
||||
lastVisited: null,
|
||||
visitCount: 0,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,68 @@
|
||||
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
|
||||
|
||||
/// BLE 공유를 위한 디바이스 정보
|
||||
class ShareDevice {
|
||||
/// 공유 코드 (6자리 숫자)
|
||||
final String code;
|
||||
|
||||
/// 디바이스 고유 ID
|
||||
final String deviceId;
|
||||
|
||||
/// BLE Remote ID (MAC 주소 또는 UUID)
|
||||
final String? remoteId;
|
||||
|
||||
/// 신호 강도 (RSSI)
|
||||
final int? rssi;
|
||||
|
||||
/// 발견 시각
|
||||
final DateTime discoveredAt;
|
||||
|
||||
/// flutter_blue_plus BluetoothDevice 참조
|
||||
/// 실제 BLE 연결 시 사용
|
||||
final BluetoothDevice? bleDevice;
|
||||
|
||||
ShareDevice({
|
||||
required this.code,
|
||||
required this.deviceId,
|
||||
this.remoteId,
|
||||
this.rssi,
|
||||
required this.discoveredAt,
|
||||
this.bleDevice,
|
||||
});
|
||||
|
||||
/// 신호 강도 레벨 (0-4)
|
||||
/// RSSI 값을 기반으로 계산
|
||||
int get signalLevel {
|
||||
if (rssi == null) return 0;
|
||||
if (rssi! >= -50) return 4; // 매우 강함
|
||||
if (rssi! >= -60) return 3; // 강함
|
||||
if (rssi! >= -70) return 2; // 보통
|
||||
if (rssi! >= -80) return 1; // 약함
|
||||
return 0; // 매우 약함
|
||||
}
|
||||
|
||||
/// 디버그용 문자열
|
||||
@override
|
||||
String toString() {
|
||||
return 'ShareDevice(code: $code, deviceId: $deviceId, rssi: $rssi)';
|
||||
}
|
||||
|
||||
/// 복사본 생성
|
||||
ShareDevice copyWith({
|
||||
String? code,
|
||||
String? deviceId,
|
||||
String? remoteId,
|
||||
int? rssi,
|
||||
DateTime? discoveredAt,
|
||||
BluetoothDevice? bleDevice,
|
||||
}) {
|
||||
return ShareDevice(
|
||||
code: code ?? this.code,
|
||||
deviceId: deviceId ?? this.deviceId,
|
||||
remoteId: remoteId ?? this.remoteId,
|
||||
rssi: rssi ?? this.rssi,
|
||||
discoveredAt: discoveredAt ?? this.discoveredAt,
|
||||
bleDevice: bleDevice ?? this.bleDevice,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,14 +22,28 @@ import 'data/sample/sample_data_initializer.dart';
|
||||
void main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
if (AdHelper.isMobilePlatform) {
|
||||
await MobileAds.instance.initialize();
|
||||
}
|
||||
|
||||
// Initialize timezone
|
||||
// Initialize timezone (동기, 빠름)
|
||||
tz.initializeTimeZones();
|
||||
|
||||
// Initialize Hive
|
||||
// 광고 SDK와 Hive 초기화를 병렬 처리
|
||||
await Future.wait([
|
||||
if (AdHelper.isMobilePlatform) MobileAds.instance.initialize(),
|
||||
_initializeHive(),
|
||||
]);
|
||||
|
||||
// Hive 초기화 후 병렬 처리 가능한 작업들
|
||||
await Future.wait([
|
||||
SampleDataInitializer.seedInitialData(),
|
||||
_initializeNotifications(),
|
||||
AdaptiveTheme.getThemeMode(),
|
||||
]).then((results) {
|
||||
final savedThemeMode = results[2] as AdaptiveThemeMode?;
|
||||
runApp(ProviderScope(child: LunchPickApp(savedThemeMode: savedThemeMode)));
|
||||
});
|
||||
}
|
||||
|
||||
/// Hive 초기화 및 Box 오픈
|
||||
Future<void> _initializeHive() async {
|
||||
await Hive.initFlutter();
|
||||
|
||||
// Register Hive Adapters
|
||||
@@ -39,24 +53,21 @@ void main() async {
|
||||
Hive.registerAdapter(RecommendationRecordAdapter());
|
||||
Hive.registerAdapter(UserSettingsAdapter());
|
||||
|
||||
// Open Hive Boxes
|
||||
await Hive.openBox<Restaurant>(AppConstants.restaurantBox);
|
||||
await Hive.openBox<VisitRecord>(AppConstants.visitRecordBox);
|
||||
await Hive.openBox<RecommendationRecord>(AppConstants.recommendationBox);
|
||||
await Hive.openBox(AppConstants.settingsBox);
|
||||
await Hive.openBox<UserSettings>('user_settings');
|
||||
await SampleDataInitializer.seedInitialData();
|
||||
// Open Hive Boxes (병렬 오픈)
|
||||
await Future.wait([
|
||||
Hive.openBox<Restaurant>(AppConstants.restaurantBox),
|
||||
Hive.openBox<VisitRecord>(AppConstants.visitRecordBox),
|
||||
Hive.openBox<RecommendationRecord>(AppConstants.recommendationBox),
|
||||
Hive.openBox(AppConstants.settingsBox),
|
||||
Hive.openBox<UserSettings>('user_settings'),
|
||||
]);
|
||||
}
|
||||
|
||||
// Initialize Notification Service (only for non-web platforms)
|
||||
if (!kIsWeb) {
|
||||
final notificationService = NotificationService();
|
||||
await notificationService.ensureInitialized(requestPermission: true);
|
||||
}
|
||||
|
||||
// Get saved theme mode
|
||||
final savedThemeMode = await AdaptiveTheme.getThemeMode();
|
||||
|
||||
runApp(ProviderScope(child: LunchPickApp(savedThemeMode: savedThemeMode)));
|
||||
/// 알림 서비스 초기화 (비-웹 플랫폼)
|
||||
Future<void> _initializeNotifications() async {
|
||||
if (kIsWeb) return;
|
||||
final notificationService = NotificationService();
|
||||
await notificationService.ensureInitialized(requestPermission: true);
|
||||
}
|
||||
|
||||
class LunchPickApp extends StatelessWidget {
|
||||
|
||||
@@ -3,6 +3,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:table_calendar/table_calendar.dart';
|
||||
import '../../../core/constants/app_colors.dart';
|
||||
import '../../../core/constants/app_typography.dart';
|
||||
import '../../../core/widgets/info_row.dart';
|
||||
import '../../../domain/entities/restaurant.dart';
|
||||
import '../../../domain/entities/recommendation_record.dart';
|
||||
import '../../../domain/entities/visit_record.dart';
|
||||
@@ -585,9 +586,11 @@ class _CalendarScreenState extends ConsumerState<CalendarScreen>
|
||||
final recoTime = recommendationRecord?.recommendationDate;
|
||||
final isVisitConfirmed = visitRecord?.isConfirmed == true;
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 12, 16, 20),
|
||||
child: Column(
|
||||
return SafeArea(
|
||||
top: false,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 12, 16, 20),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
@@ -607,18 +610,25 @@ class _CalendarScreenState extends ConsumerState<CalendarScreen>
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
_buildInfoRow('주소', restaurant.roadAddress, isDark),
|
||||
InfoRow(
|
||||
label: '주소',
|
||||
value: restaurant.roadAddress,
|
||||
isDark: isDark,
|
||||
horizontal: true,
|
||||
),
|
||||
if (visitTime != null)
|
||||
_buildInfoRow(
|
||||
isVisitConfirmed ? '방문 완료' : '방문 예정',
|
||||
_formatFullDateTime(visitTime),
|
||||
isDark,
|
||||
InfoRow(
|
||||
label: isVisitConfirmed ? '방문 완료' : '방문 예정',
|
||||
value: _formatFullDateTime(visitTime),
|
||||
isDark: isDark,
|
||||
horizontal: true,
|
||||
),
|
||||
if (recoTime != null)
|
||||
_buildInfoRow(
|
||||
'추천 시각',
|
||||
_formatFullDateTime(recoTime),
|
||||
isDark,
|
||||
InfoRow(
|
||||
label: '추천 시각',
|
||||
value: _formatFullDateTime(recoTime),
|
||||
isDark: isDark,
|
||||
horizontal: true,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Wrap(
|
||||
@@ -681,7 +691,8 @@ class _CalendarScreenState extends ConsumerState<CalendarScreen>
|
||||
label: const Text('추천 방문 기록으로 저장'),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
@@ -703,23 +714,6 @@ class _CalendarScreenState extends ConsumerState<CalendarScreen>
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildInfoRow(String label, String value, bool isDark) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 4),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
SizedBox(
|
||||
width: 80,
|
||||
child: Text(label, style: AppTypography.caption(isDark)),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(child: Text(value, style: AppTypography.body2(isDark))),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _showRestaurantDetailDialog(
|
||||
BuildContext context,
|
||||
bool isDark,
|
||||
@@ -737,18 +731,39 @@ class _CalendarScreenState extends ConsumerState<CalendarScreen>
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
_buildInfoRow(
|
||||
'카테고리',
|
||||
'${restaurant.category} > ${restaurant.subCategory}',
|
||||
isDark,
|
||||
InfoRow(
|
||||
label: '카테고리',
|
||||
value: '${restaurant.category} > ${restaurant.subCategory}',
|
||||
isDark: isDark,
|
||||
horizontal: true,
|
||||
),
|
||||
if (restaurant.phoneNumber != null)
|
||||
_buildInfoRow('전화번호', restaurant.phoneNumber!, isDark),
|
||||
_buildInfoRow('도로명', restaurant.roadAddress, isDark),
|
||||
_buildInfoRow('지번', restaurant.jibunAddress, isDark),
|
||||
InfoRow(
|
||||
label: '전화번호',
|
||||
value: restaurant.phoneNumber!,
|
||||
isDark: isDark,
|
||||
horizontal: true,
|
||||
),
|
||||
InfoRow(
|
||||
label: '도로명',
|
||||
value: restaurant.roadAddress,
|
||||
isDark: isDark,
|
||||
horizontal: true,
|
||||
),
|
||||
InfoRow(
|
||||
label: '지번',
|
||||
value: restaurant.jibunAddress,
|
||||
isDark: isDark,
|
||||
horizontal: true,
|
||||
),
|
||||
if (restaurant.description != null &&
|
||||
restaurant.description!.isNotEmpty)
|
||||
_buildInfoRow('메모', restaurant.description!, isDark),
|
||||
InfoRow(
|
||||
label: '메모',
|
||||
value: restaurant.description!,
|
||||
isDark: isDark,
|
||||
horizontal: true,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
@@ -1,92 +0,0 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:lunchpick/core/constants/app_colors.dart';
|
||||
import 'package:lunchpick/core/constants/app_typography.dart';
|
||||
import 'package:lunchpick/presentation/providers/debug_test_data_provider.dart';
|
||||
|
||||
class DebugTestDataBanner extends ConsumerWidget {
|
||||
final EdgeInsetsGeometry? margin;
|
||||
|
||||
const DebugTestDataBanner({super.key, this.margin});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
if (!kDebugMode) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
final state = ref.watch(debugTestDataNotifierProvider);
|
||||
final notifier = ref.read(debugTestDataNotifierProvider.notifier);
|
||||
|
||||
return Card(
|
||||
margin: margin ?? const EdgeInsets.all(16),
|
||||
color: isDark ? AppColors.darkSurface : AppColors.lightSurface,
|
||||
elevation: 1,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
const Icon(
|
||||
Icons.science_outlined,
|
||||
color: AppColors.lightPrimary,
|
||||
size: 20,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
'테스트 데이터 미리보기',
|
||||
style: AppTypography.body1(
|
||||
isDark,
|
||||
).copyWith(fontWeight: FontWeight.w600),
|
||||
),
|
||||
const Spacer(),
|
||||
if (state.isProcessing)
|
||||
const SizedBox(
|
||||
width: 20,
|
||||
height: 20,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Switch.adaptive(
|
||||
value: state.isEnabled,
|
||||
onChanged: state.isProcessing
|
||||
? null
|
||||
: (value) async {
|
||||
if (value) {
|
||||
await notifier.enableTestData();
|
||||
} else {
|
||||
await notifier.disableTestData();
|
||||
}
|
||||
},
|
||||
activeColor: AppColors.lightPrimary,
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
state.isEnabled
|
||||
? '디버그 빌드에서만 적용됩니다. 기록/통계 UI를 테스트용 데이터로 확인하세요.'
|
||||
: '디버그 빌드에서만 사용 가능합니다. 스위치를 켜면 추천·방문 기록이 자동으로 채워집니다.',
|
||||
style: AppTypography.caption(isDark),
|
||||
),
|
||||
if (state.errorMessage != null) ...[
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
state.errorMessage!,
|
||||
style: AppTypography.caption(isDark).copyWith(
|
||||
color: AppColors.lightError,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,33 @@ class RecommendationRecordCard extends ConsumerWidget {
|
||||
return '$hour:$minute';
|
||||
}
|
||||
|
||||
Future<void> _showDeleteConfirmation(BuildContext context) async {
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: const Text('추천 기록 삭제'),
|
||||
content: const Text('이 추천 기록을 삭제하시겠습니까?'),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(false),
|
||||
child: const Text('취소'),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(true),
|
||||
style: TextButton.styleFrom(
|
||||
foregroundColor: AppColors.lightError,
|
||||
),
|
||||
child: const Text('삭제'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
if (confirmed == true) {
|
||||
onDelete();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
@@ -166,7 +193,7 @@ class RecommendationRecordCard extends ConsumerWidget {
|
||||
Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: TextButton(
|
||||
onPressed: onDelete,
|
||||
onPressed: () => _showDeleteConfirmation(context),
|
||||
style: TextButton.styleFrom(
|
||||
foregroundColor: Colors.redAccent,
|
||||
padding: const EdgeInsets.only(top: 6),
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:geolocator/geolocator.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
import '../../../core/constants/app_colors.dart';
|
||||
import '../../../core/constants/app_dimensions.dart';
|
||||
import '../../../core/constants/app_typography.dart';
|
||||
import '../../../core/utils/category_mapper.dart';
|
||||
import '../../../domain/entities/restaurant.dart';
|
||||
@@ -306,8 +308,8 @@ class _RandomSelectionScreenState extends ConsumerState<RandomSelectionScreen> {
|
||||
child: Slider(
|
||||
value: _distanceValue,
|
||||
min: 100,
|
||||
max: 2000,
|
||||
divisions: 19,
|
||||
max: AppDimensions.maxSearchDistance,
|
||||
divisions: AppDimensions.distanceSliderDivisions,
|
||||
onChanged: (value) {
|
||||
setState(() => _distanceValue = value);
|
||||
},
|
||||
@@ -739,6 +741,9 @@ class _RandomSelectionScreenState extends ConsumerState<RandomSelectionScreen> {
|
||||
}) async {
|
||||
if (_isProcessingRecommendation) return;
|
||||
|
||||
// 버튼 터치 햅틱 피드백
|
||||
HapticFeedback.mediumImpact();
|
||||
|
||||
if (!isReroll) {
|
||||
_excludedRestaurantIds.clear();
|
||||
}
|
||||
@@ -769,6 +774,10 @@ class _RandomSelectionScreenState extends ConsumerState<RandomSelectionScreen> {
|
||||
}
|
||||
|
||||
if (!mounted) return;
|
||||
|
||||
// 추천 결과 햅틱 피드백
|
||||
HapticFeedback.heavyImpact();
|
||||
|
||||
await _showRecommendationDialog(candidate, recommendedAt: recommendedAt);
|
||||
} catch (_) {
|
||||
_showSnack('추천을 준비하는 중 문제가 발생했습니다.', type: _SnackType.error);
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import '../../../core/constants/app_colors.dart';
|
||||
import '../../../core/constants/app_dimensions.dart';
|
||||
import '../../../core/constants/app_typography.dart';
|
||||
import '../../../core/widgets/skeleton_loader.dart';
|
||||
import '../../../core/utils/category_mapper.dart';
|
||||
import '../../../core/utils/app_logger.dart';
|
||||
import '../../providers/restaurant_provider.dart';
|
||||
import '../../providers/settings_provider.dart';
|
||||
import '../../providers/visit_provider.dart';
|
||||
import '../../widgets/category_selector.dart';
|
||||
import '../../widgets/native_ad_placeholder.dart';
|
||||
import 'manual_restaurant_input_screen.dart';
|
||||
@@ -40,6 +43,8 @@ class _RestaurantListScreenState extends ConsumerState<RestaurantListScreen> {
|
||||
.maybeWhen(data: (value) => value, orElse: () => false);
|
||||
final isFiltered = searchQuery.isNotEmpty || selectedCategory != null;
|
||||
final restaurantsAsync = ref.watch(sortedRestaurantsByDistanceProvider);
|
||||
final lastVisitDates =
|
||||
ref.watch(allLastVisitDatesProvider).valueOrNull ?? {};
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: isDark
|
||||
@@ -70,6 +75,7 @@ class _RestaurantListScreenState extends ConsumerState<RestaurantListScreen> {
|
||||
if (_isSearching) ...[
|
||||
IconButton(
|
||||
icon: const Icon(Icons.close),
|
||||
tooltip: '검색 닫기',
|
||||
onPressed: () {
|
||||
setState(() {
|
||||
_isSearching = false;
|
||||
@@ -81,6 +87,7 @@ class _RestaurantListScreenState extends ConsumerState<RestaurantListScreen> {
|
||||
] else ...[
|
||||
IconButton(
|
||||
icon: const Icon(Icons.search),
|
||||
tooltip: '맛집 검색',
|
||||
onPressed: () {
|
||||
setState(() {
|
||||
_isSearching = true;
|
||||
@@ -149,8 +156,8 @@ class _RestaurantListScreenState extends ConsumerState<RestaurantListScreen> {
|
||||
return _buildEmptyState(isDark);
|
||||
}
|
||||
|
||||
const adInterval = 6; // 5리스트 후 1광고
|
||||
const adOffset = 5; // 1~5 리스트 이후 6 광고 시작
|
||||
const adInterval = AppDimensions.adInterval;
|
||||
const adOffset = AppDimensions.adOffset;
|
||||
final adCount = (items.length ~/ adOffset);
|
||||
final totalCount = items.length + adCount;
|
||||
|
||||
@@ -167,7 +174,7 @@ class _RestaurantListScreenState extends ConsumerState<RestaurantListScreen> {
|
||||
horizontal: 16,
|
||||
vertical: 8,
|
||||
),
|
||||
height: 200, // 카드 높이와 비슷한 중간 사이즈
|
||||
height: 100, // 작은 템플릿으로 노출
|
||||
);
|
||||
}
|
||||
|
||||
@@ -180,48 +187,70 @@ class _RestaurantListScreenState extends ConsumerState<RestaurantListScreen> {
|
||||
return RestaurantCard(
|
||||
restaurant: item.restaurant,
|
||||
distanceKm: item.distanceKm,
|
||||
lastVisitDate: lastVisitDates[item.restaurant.id],
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
loading: () {
|
||||
AppLogger.debug('[restaurant_list_ui] loading...');
|
||||
return const Center(
|
||||
child: CircularProgressIndicator(
|
||||
color: AppColors.lightPrimary,
|
||||
),
|
||||
);
|
||||
return const RestaurantListSkeleton();
|
||||
},
|
||||
error: (error, stack) => Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.error_outline,
|
||||
size: 64,
|
||||
color: isDark
|
||||
? AppColors.darkError
|
||||
: AppColors.lightError,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text('오류가 발생했습니다', style: AppTypography.heading2(isDark)),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
error.toString(),
|
||||
style: AppTypography.body2(isDark),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(AppDimensions.paddingDefault),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.error_outline,
|
||||
size: AppDimensions.iconXxl,
|
||||
color: isDark
|
||||
? AppColors.darkError
|
||||
: AppColors.lightError,
|
||||
),
|
||||
const SizedBox(height: AppDimensions.paddingDefault),
|
||||
Text('오류가 발생했습니다', style: AppTypography.heading2(isDark)),
|
||||
const SizedBox(height: AppDimensions.paddingSm),
|
||||
Text(
|
||||
error.toString(),
|
||||
style: AppTypography.body2(isDark),
|
||||
textAlign: TextAlign.center,
|
||||
maxLines: 3,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
const SizedBox(height: AppDimensions.paddingLg),
|
||||
ElevatedButton.icon(
|
||||
onPressed: () =>
|
||||
ref.invalidate(sortedRestaurantsByDistanceProvider),
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: AppColors.lightPrimary,
|
||||
foregroundColor: Colors.white,
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: AppDimensions.paddingXl,
|
||||
vertical: AppDimensions.paddingMd,
|
||||
),
|
||||
),
|
||||
icon: const Icon(Icons.refresh),
|
||||
label: const Text('다시 시도'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
floatingActionButton: FloatingActionButton(
|
||||
onPressed: _showAddOptions,
|
||||
backgroundColor: AppColors.lightPrimary,
|
||||
child: const Icon(Icons.add, color: Colors.white),
|
||||
floatingActionButton: Semantics(
|
||||
label: '맛집 추가하기',
|
||||
button: true,
|
||||
child: FloatingActionButton(
|
||||
onPressed: _showAddOptions,
|
||||
tooltip: '맛집 추가',
|
||||
backgroundColor: AppColors.lightPrimary,
|
||||
child: const Icon(Icons.add, color: Colors.white),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -124,7 +124,7 @@ class _AddRestaurantDialogState extends ConsumerState<AddRestaurantDialog> {
|
||||
_jibunAddressController.text = formData.jibunAddress;
|
||||
_latitudeController.text = formData.latitude;
|
||||
_longitudeController.text = formData.longitude;
|
||||
_naverUrlController.text = formData.naverUrl;
|
||||
// naverUrlController는 사용자 입력을 그대로 유지
|
||||
}
|
||||
|
||||
Future<void> _saveRestaurant() async {
|
||||
@@ -234,6 +234,7 @@ class _AddRestaurantDialogState extends ConsumerState<AddRestaurantDialog> {
|
||||
longitudeController: _longitudeController,
|
||||
naverUrlController: _naverUrlController,
|
||||
onFieldChanged: _onFormDataChanged,
|
||||
naverUrl: state.formData.naverUrl,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
@@ -1,925 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:lunchpick/core/constants/app_colors.dart';
|
||||
import 'package:lunchpick/core/constants/app_typography.dart';
|
||||
import 'package:lunchpick/core/utils/validators.dart';
|
||||
import 'package:lunchpick/domain/entities/restaurant.dart';
|
||||
import 'package:lunchpick/presentation/providers/restaurant_provider.dart';
|
||||
|
||||
class AddRestaurantDialog extends ConsumerStatefulWidget {
|
||||
final int initialTabIndex;
|
||||
|
||||
const AddRestaurantDialog({
|
||||
super.key,
|
||||
this.initialTabIndex = 0,
|
||||
});
|
||||
|
||||
@override
|
||||
ConsumerState<AddRestaurantDialog> createState() => _AddRestaurantDialogState();
|
||||
}
|
||||
|
||||
class _AddRestaurantDialogState extends ConsumerState<AddRestaurantDialog> with SingleTickerProviderStateMixin {
|
||||
final _formKey = GlobalKey<FormState>();
|
||||
final _nameController = TextEditingController();
|
||||
final _categoryController = TextEditingController();
|
||||
final _subCategoryController = TextEditingController();
|
||||
final _descriptionController = TextEditingController();
|
||||
final _phoneController = TextEditingController();
|
||||
final _roadAddressController = TextEditingController();
|
||||
final _jibunAddressController = TextEditingController();
|
||||
final _latitudeController = TextEditingController();
|
||||
final _longitudeController = TextEditingController();
|
||||
final _naverUrlController = TextEditingController();
|
||||
|
||||
// 기본 좌표 (서울시청)
|
||||
final double _defaultLatitude = 37.5665;
|
||||
final double _defaultLongitude = 126.9780;
|
||||
|
||||
// UI 상태 관리
|
||||
late TabController _tabController;
|
||||
bool _isLoading = false;
|
||||
String? _errorMessage;
|
||||
Restaurant? _fetchedRestaurantData;
|
||||
final _linkController = TextEditingController();
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_tabController = TabController(
|
||||
length: 2,
|
||||
vsync: this,
|
||||
initialIndex: widget.initialTabIndex,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_nameController.dispose();
|
||||
_categoryController.dispose();
|
||||
_subCategoryController.dispose();
|
||||
_descriptionController.dispose();
|
||||
_phoneController.dispose();
|
||||
_roadAddressController.dispose();
|
||||
_jibunAddressController.dispose();
|
||||
_latitudeController.dispose();
|
||||
_longitudeController.dispose();
|
||||
_naverUrlController.dispose();
|
||||
_linkController.dispose();
|
||||
_tabController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
|
||||
return Dialog(
|
||||
backgroundColor: isDark ? AppColors.darkSurface : AppColors.lightSurface,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
),
|
||||
child: Container(
|
||||
constraints: const BoxConstraints(maxWidth: 400),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
// 제목과 탭바
|
||||
Container(
|
||||
padding: const EdgeInsets.fromLTRB(24, 24, 24, 0),
|
||||
child: Column(
|
||||
children: [
|
||||
Text(
|
||||
'맛집 추가',
|
||||
style: AppTypography.heading1(isDark),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Container(
|
||||
decoration: BoxDecoration(
|
||||
color: isDark ? AppColors.darkBackground : AppColors.lightBackground,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: TabBar(
|
||||
controller: _tabController,
|
||||
indicator: BoxDecoration(
|
||||
color: AppColors.lightPrimary,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
indicatorSize: TabBarIndicatorSize.tab,
|
||||
labelColor: Colors.white,
|
||||
unselectedLabelColor: isDark ? AppColors.darkTextSecondary : AppColors.lightTextSecondary,
|
||||
labelStyle: AppTypography.body1(false).copyWith(fontWeight: FontWeight.w600),
|
||||
tabs: const [
|
||||
Tab(text: '직접 입력'),
|
||||
Tab(text: '네이버 지도에서 가져오기'),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
// 탭뷰 컨텐츠
|
||||
Flexible(
|
||||
child: TabBarView(
|
||||
controller: _tabController,
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
children: [
|
||||
// 직접 입력 탭
|
||||
SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Form(
|
||||
key: _formKey,
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
|
||||
// 가게 이름
|
||||
TextFormField(
|
||||
controller: _nameController,
|
||||
decoration: InputDecoration(
|
||||
labelText: '가게 이름 *',
|
||||
hintText: '예: 서울갈비',
|
||||
prefixIcon: const Icon(Icons.store),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
),
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return '가게 이름을 입력해주세요';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// 카테고리
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: TextFormField(
|
||||
controller: _categoryController,
|
||||
decoration: InputDecoration(
|
||||
labelText: '카테고리 *',
|
||||
hintText: '예: 한식',
|
||||
prefixIcon: const Icon(Icons.category),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
),
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return '카테고리를 입력해주세요';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: TextFormField(
|
||||
controller: _subCategoryController,
|
||||
decoration: InputDecoration(
|
||||
labelText: '세부 카테고리',
|
||||
hintText: '예: 갈비',
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// 설명
|
||||
TextFormField(
|
||||
controller: _descriptionController,
|
||||
maxLines: 2,
|
||||
decoration: InputDecoration(
|
||||
labelText: '설명',
|
||||
hintText: '맛집에 대한 간단한 설명',
|
||||
prefixIcon: const Icon(Icons.description),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// 전화번호
|
||||
TextFormField(
|
||||
controller: _phoneController,
|
||||
keyboardType: TextInputType.phone,
|
||||
decoration: InputDecoration(
|
||||
labelText: '전화번호',
|
||||
hintText: '예: 02-1234-5678',
|
||||
prefixIcon: const Icon(Icons.phone),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// 도로명 주소
|
||||
TextFormField(
|
||||
controller: _roadAddressController,
|
||||
decoration: InputDecoration(
|
||||
labelText: '도로명 주소 *',
|
||||
hintText: '예: 서울시 중구 세종대로 110',
|
||||
prefixIcon: const Icon(Icons.location_on),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
),
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return '도로명 주소를 입력해주세요';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// 지번 주소
|
||||
TextFormField(
|
||||
controller: _jibunAddressController,
|
||||
decoration: InputDecoration(
|
||||
labelText: '지번 주소',
|
||||
hintText: '예: 서울시 중구 태평로1가 31',
|
||||
prefixIcon: const Icon(Icons.map),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// 위도/경도 입력
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: TextFormField(
|
||||
controller: _latitudeController,
|
||||
keyboardType: const TextInputType.numberWithOptions(decimal: true),
|
||||
decoration: InputDecoration(
|
||||
labelText: '위도',
|
||||
hintText: '37.5665',
|
||||
prefixIcon: const Icon(Icons.explore),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
),
|
||||
validator: Validators.validateLatitude,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: TextFormField(
|
||||
controller: _longitudeController,
|
||||
keyboardType: const TextInputType.numberWithOptions(decimal: true),
|
||||
decoration: InputDecoration(
|
||||
labelText: '경도',
|
||||
hintText: '126.9780',
|
||||
prefixIcon: const Icon(Icons.explore),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
),
|
||||
validator: Validators.validateLongitude,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'* 위도/경도를 입력하지 않으면 서울시청 기준으로 저장됩니다',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: isDark ? AppColors.darkTextSecondary : AppColors.lightTextSecondary,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// 버튼
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.end,
|
||||
children: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context),
|
||||
child: Text(
|
||||
'취소',
|
||||
style: TextStyle(
|
||||
color: isDark ? AppColors.darkTextSecondary : AppColors.lightTextSecondary,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
ElevatedButton(
|
||||
onPressed: _saveRestaurant,
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: AppColors.lightPrimary,
|
||||
foregroundColor: Colors.white,
|
||||
),
|
||||
child: const Text('저장'),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
// 네이버 지도 탭
|
||||
_buildNaverMapTab(isDark),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// 네이버 지도 탭 빌드
|
||||
Widget _buildNaverMapTab(bool isDark) {
|
||||
return SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
// 안내 메시지
|
||||
Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.lightPrimary.withOpacity(0.1),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(
|
||||
color: AppColors.lightPrimary.withOpacity(0.3),
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.info_outline,
|
||||
color: AppColors.lightPrimary,
|
||||
size: 20,
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
kIsWeb
|
||||
? '네이버 지도에서 맛집 페이지 URL을 복사하여\n붙여넣어 주세요.\n\n웹 환경에서는 프록시 서버를 통해 정보를 가져옵니다.\n네트워크 상황에 따라 시간이 걸릴 수 있습니다.'
|
||||
: '네이버 지도에서 맛집 페이지 URL을 복사하여\n붙여넣어 주세요.',
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
color: isDark ? AppColors.darkText : AppColors.lightText,
|
||||
height: 1.5,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// URL 입력 필드
|
||||
TextFormField(
|
||||
controller: _naverUrlController,
|
||||
decoration: InputDecoration(
|
||||
labelText: '네이버 지도 URL',
|
||||
hintText: 'https://map.naver.com/... 또는 https://naver.me/...',
|
||||
prefixIcon: Icon(
|
||||
Icons.link,
|
||||
color: AppColors.lightPrimary,
|
||||
),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: BorderSide(
|
||||
color: isDark ? AppColors.darkDivider : AppColors.lightDivider,
|
||||
),
|
||||
),
|
||||
focusedBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: BorderSide(
|
||||
color: AppColors.lightPrimary,
|
||||
width: 2,
|
||||
),
|
||||
),
|
||||
errorText: _errorMessage,
|
||||
errorMaxLines: 2,
|
||||
),
|
||||
enabled: !_isLoading,
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// 가져온 정보 표시 (JSON 스타일)
|
||||
if (_fetchedRestaurantData != null) ...[
|
||||
Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: isDark
|
||||
? AppColors.darkBackground
|
||||
: AppColors.lightBackground.withOpacity(0.5),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(
|
||||
color: isDark
|
||||
? AppColors.darkDivider
|
||||
: AppColors.lightDivider,
|
||||
),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// 타이틀
|
||||
Row(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.code,
|
||||
size: 20,
|
||||
color: isDark
|
||||
? AppColors.darkTextSecondary
|
||||
: AppColors.lightTextSecondary,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
'가져온 정보',
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: isDark
|
||||
? AppColors.darkTextSecondary
|
||||
: AppColors.lightTextSecondary,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
// JSON 스타일 정보 표시
|
||||
_buildJsonField(
|
||||
'이름',
|
||||
_nameController,
|
||||
isDark,
|
||||
icon: Icons.store,
|
||||
),
|
||||
_buildJsonField(
|
||||
'카테고리',
|
||||
_categoryController,
|
||||
isDark,
|
||||
icon: Icons.category,
|
||||
),
|
||||
_buildJsonField(
|
||||
'세부 카테고리',
|
||||
_subCategoryController,
|
||||
isDark,
|
||||
icon: Icons.label_outline,
|
||||
),
|
||||
_buildJsonField(
|
||||
'주소',
|
||||
_roadAddressController,
|
||||
isDark,
|
||||
icon: Icons.location_on,
|
||||
),
|
||||
_buildJsonField(
|
||||
'전화',
|
||||
_phoneController,
|
||||
isDark,
|
||||
icon: Icons.phone,
|
||||
),
|
||||
_buildJsonField(
|
||||
'설명',
|
||||
_descriptionController,
|
||||
isDark,
|
||||
icon: Icons.description,
|
||||
maxLines: 2,
|
||||
),
|
||||
_buildJsonField(
|
||||
'좌표',
|
||||
TextEditingController(
|
||||
text: '${_latitudeController.text}, ${_longitudeController.text}'
|
||||
),
|
||||
isDark,
|
||||
icon: Icons.my_location,
|
||||
isCoordinate: true,
|
||||
),
|
||||
if (_linkController.text.isNotEmpty)
|
||||
_buildJsonField(
|
||||
'링크',
|
||||
_linkController,
|
||||
isDark,
|
||||
icon: Icons.link,
|
||||
isLink: true,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
],
|
||||
|
||||
// 버튼
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.end,
|
||||
children: [
|
||||
TextButton(
|
||||
onPressed: _isLoading ? null : () => Navigator.pop(context),
|
||||
child: Text(
|
||||
'취소',
|
||||
style: TextStyle(
|
||||
color: isDark ? AppColors.darkTextSecondary : AppColors.lightTextSecondary,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
if (_fetchedRestaurantData == null)
|
||||
ElevatedButton(
|
||||
onPressed: _isLoading ? null : _fetchFromNaverUrl,
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: AppColors.lightPrimary,
|
||||
foregroundColor: Colors.white,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
|
||||
),
|
||||
child: _isLoading
|
||||
? SizedBox(
|
||||
width: 20,
|
||||
height: 20,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
|
||||
),
|
||||
)
|
||||
: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: const [
|
||||
Icon(Icons.download, size: 18),
|
||||
SizedBox(width: 8),
|
||||
Text('가져오기'),
|
||||
],
|
||||
),
|
||||
)
|
||||
else ...[
|
||||
OutlinedButton(
|
||||
onPressed: () {
|
||||
setState(() {
|
||||
_fetchedRestaurantData = null;
|
||||
_clearControllers();
|
||||
});
|
||||
},
|
||||
style: OutlinedButton.styleFrom(
|
||||
foregroundColor: isDark
|
||||
? AppColors.darkTextSecondary
|
||||
: AppColors.lightTextSecondary,
|
||||
side: BorderSide(
|
||||
color: isDark
|
||||
? AppColors.darkDivider
|
||||
: AppColors.lightDivider,
|
||||
),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
|
||||
),
|
||||
child: const Text('초기화'),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
ElevatedButton(
|
||||
onPressed: _saveRestaurant,
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: AppColors.lightPrimary,
|
||||
foregroundColor: Colors.white,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: const [
|
||||
Icon(Icons.save, size: 18),
|
||||
SizedBox(width: 8),
|
||||
Text('저장'),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// JSON 스타일 필드 빌드
|
||||
Widget _buildJsonField(
|
||||
String label,
|
||||
TextEditingController controller,
|
||||
bool isDark, {
|
||||
IconData? icon,
|
||||
int maxLines = 1,
|
||||
bool isCoordinate = false,
|
||||
bool isLink = false,
|
||||
}) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
if (icon != null) ...[
|
||||
Icon(
|
||||
icon,
|
||||
size: 16,
|
||||
color: isDark
|
||||
? AppColors.darkTextSecondary
|
||||
: AppColors.lightTextSecondary,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
],
|
||||
Text(
|
||||
'$label:',
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
fontWeight: FontWeight.w500,
|
||||
color: isDark
|
||||
? AppColors.darkTextSecondary
|
||||
: AppColors.lightTextSecondary,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
if (isCoordinate)
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: TextFormField(
|
||||
controller: _latitudeController,
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
fontFamily: 'monospace',
|
||||
color: isDark ? AppColors.darkText : AppColors.lightText,
|
||||
),
|
||||
decoration: InputDecoration(
|
||||
hintText: '위도',
|
||||
isDense: true,
|
||||
contentPadding: const EdgeInsets.symmetric(
|
||||
horizontal: 12,
|
||||
vertical: 8,
|
||||
),
|
||||
filled: true,
|
||||
fillColor: isDark
|
||||
? AppColors.darkSurface
|
||||
: Colors.white,
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
borderSide: BorderSide(
|
||||
color: isDark
|
||||
? AppColors.darkDivider
|
||||
: AppColors.lightDivider,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
',',
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
fontFamily: 'monospace',
|
||||
color: isDark ? AppColors.darkText : AppColors.lightText,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: TextFormField(
|
||||
controller: _longitudeController,
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
fontFamily: 'monospace',
|
||||
color: isDark ? AppColors.darkText : AppColors.lightText,
|
||||
),
|
||||
decoration: InputDecoration(
|
||||
hintText: '경도',
|
||||
isDense: true,
|
||||
contentPadding: const EdgeInsets.symmetric(
|
||||
horizontal: 12,
|
||||
vertical: 8,
|
||||
),
|
||||
filled: true,
|
||||
fillColor: isDark
|
||||
? AppColors.darkSurface
|
||||
: Colors.white,
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
borderSide: BorderSide(
|
||||
color: isDark
|
||||
? AppColors.darkDivider
|
||||
: AppColors.lightDivider,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
)
|
||||
else
|
||||
TextFormField(
|
||||
controller: controller,
|
||||
maxLines: maxLines,
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
fontFamily: isLink ? 'monospace' : null,
|
||||
color: isLink
|
||||
? AppColors.lightPrimary
|
||||
: isDark ? AppColors.darkText : AppColors.lightText,
|
||||
decoration: isLink ? TextDecoration.underline : null,
|
||||
),
|
||||
decoration: InputDecoration(
|
||||
isDense: true,
|
||||
contentPadding: const EdgeInsets.symmetric(
|
||||
horizontal: 12,
|
||||
vertical: 8,
|
||||
),
|
||||
filled: true,
|
||||
fillColor: isDark
|
||||
? AppColors.darkSurface
|
||||
: Colors.white,
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
borderSide: BorderSide(
|
||||
color: isDark
|
||||
? AppColors.darkDivider
|
||||
: AppColors.lightDivider,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// 컨트롤러 초기화
|
||||
void _clearControllers() {
|
||||
_nameController.clear();
|
||||
_categoryController.clear();
|
||||
_subCategoryController.clear();
|
||||
_descriptionController.clear();
|
||||
_phoneController.clear();
|
||||
_roadAddressController.clear();
|
||||
_jibunAddressController.clear();
|
||||
_latitudeController.clear();
|
||||
_longitudeController.clear();
|
||||
_linkController.clear();
|
||||
}
|
||||
|
||||
// 네이버 URL에서 정보 가져오기
|
||||
Future<void> _fetchFromNaverUrl() async {
|
||||
final url = _naverUrlController.text.trim();
|
||||
|
||||
if (url.isEmpty) {
|
||||
setState(() {
|
||||
_errorMessage = 'URL을 입력해주세요.';
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setState(() {
|
||||
_isLoading = true;
|
||||
_errorMessage = null;
|
||||
});
|
||||
|
||||
try {
|
||||
final notifier = ref.read(restaurantNotifierProvider.notifier);
|
||||
final restaurant = await notifier.addRestaurantFromUrl(url);
|
||||
|
||||
// 성공 시 폼에 정보 채우고 _fetchedRestaurantData 설정
|
||||
setState(() {
|
||||
_nameController.text = restaurant.name;
|
||||
_categoryController.text = restaurant.category;
|
||||
_subCategoryController.text = restaurant.subCategory;
|
||||
_descriptionController.text = restaurant.description ?? '';
|
||||
_phoneController.text = restaurant.phoneNumber ?? '';
|
||||
_roadAddressController.text = restaurant.roadAddress;
|
||||
_jibunAddressController.text = restaurant.jibunAddress;
|
||||
_latitudeController.text = restaurant.latitude.toString();
|
||||
_longitudeController.text = restaurant.longitude.toString();
|
||||
|
||||
// 링크 정보가 있다면 설정
|
||||
_linkController.text = restaurant.naverUrl ?? '';
|
||||
|
||||
// Restaurant 객체 저장
|
||||
_fetchedRestaurantData = restaurant;
|
||||
|
||||
_isLoading = false;
|
||||
});
|
||||
|
||||
// 성공 메시지 표시
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Row(
|
||||
children: [
|
||||
Icon(Icons.check_circle, color: Colors.white, size: 20),
|
||||
const SizedBox(width: 8),
|
||||
Text('맛집 정보를 가져왔습니다. 확인 후 저장해주세요.'),
|
||||
],
|
||||
),
|
||||
backgroundColor: AppColors.lightPrimary,
|
||||
behavior: SnackBarBehavior.floating,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
setState(() {
|
||||
_isLoading = false;
|
||||
_errorMessage = e.toString().replaceFirst('Exception: ', '');
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _saveRestaurant() async {
|
||||
if (_formKey.currentState?.validate() != true) {
|
||||
return;
|
||||
}
|
||||
|
||||
final notifier = ref.read(restaurantNotifierProvider.notifier);
|
||||
|
||||
try {
|
||||
// _fetchedRestaurantData가 있으면 해당 데이터 사용 (네이버에서 가져온 경우)
|
||||
final fetchedData = _fetchedRestaurantData;
|
||||
if (fetchedData != null) {
|
||||
// 사용자가 수정한 필드만 업데이트
|
||||
final updatedRestaurant = fetchedData.copyWith(
|
||||
name: _nameController.text.trim(),
|
||||
category: _categoryController.text.trim(),
|
||||
subCategory: _subCategoryController.text.trim().isEmpty
|
||||
? _categoryController.text.trim()
|
||||
: _subCategoryController.text.trim(),
|
||||
description: _descriptionController.text.trim().isEmpty
|
||||
? null
|
||||
: _descriptionController.text.trim(),
|
||||
phoneNumber: _phoneController.text.trim().isEmpty
|
||||
? null
|
||||
: _phoneController.text.trim(),
|
||||
roadAddress: _roadAddressController.text.trim(),
|
||||
jibunAddress: _jibunAddressController.text.trim().isEmpty
|
||||
? _roadAddressController.text.trim()
|
||||
: _jibunAddressController.text.trim(),
|
||||
latitude: double.tryParse(_latitudeController.text.trim()) ?? fetchedData.latitude,
|
||||
longitude: double.tryParse(_longitudeController.text.trim()) ?? fetchedData.longitude,
|
||||
updatedAt: DateTime.now(),
|
||||
);
|
||||
|
||||
// 이미 완성된 Restaurant 객체를 직접 추가
|
||||
await notifier.addRestaurantDirect(updatedRestaurant);
|
||||
} else {
|
||||
// 직접 입력한 경우 (기존 로직)
|
||||
await notifier.addRestaurant(
|
||||
name: _nameController.text.trim(),
|
||||
category: _categoryController.text.trim(),
|
||||
subCategory: _subCategoryController.text.trim().isEmpty
|
||||
? _categoryController.text.trim()
|
||||
: _subCategoryController.text.trim(),
|
||||
description: _descriptionController.text.trim().isEmpty
|
||||
? null
|
||||
: _descriptionController.text.trim(),
|
||||
phoneNumber: _phoneController.text.trim().isEmpty
|
||||
? null
|
||||
: _phoneController.text.trim(),
|
||||
roadAddress: _roadAddressController.text.trim(),
|
||||
jibunAddress: _jibunAddressController.text.trim().isEmpty
|
||||
? _roadAddressController.text.trim()
|
||||
: _jibunAddressController.text.trim(),
|
||||
latitude: _latitudeController.text.trim().isEmpty
|
||||
? _defaultLatitude
|
||||
: double.tryParse(_latitudeController.text.trim()) ?? _defaultLatitude,
|
||||
longitude: _longitudeController.text.trim().isEmpty
|
||||
? _defaultLongitude
|
||||
: double.tryParse(_longitudeController.text.trim()) ?? _defaultLongitude,
|
||||
source: DataSource.USER_INPUT,
|
||||
);
|
||||
}
|
||||
|
||||
if (mounted) {
|
||||
Navigator.pop(context);
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('맛집이 추가되었습니다'),
|
||||
backgroundColor: AppColors.lightPrimary,
|
||||
),
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('오류가 발생했습니다: ${e.toString()}'),
|
||||
backgroundColor: AppColors.lightError,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
|
||||
import '../../../services/restaurant_form_validator.dart';
|
||||
|
||||
/// 식당 추가 폼 위젯
|
||||
@@ -18,6 +20,7 @@ class AddRestaurantForm extends StatefulWidget {
|
||||
final List<String> categories;
|
||||
final List<String> subCategories;
|
||||
final String geocodingStatus;
|
||||
final TextEditingController? naverUrlController; // 네이버 지도 URL 입력
|
||||
|
||||
const AddRestaurantForm({
|
||||
super.key,
|
||||
@@ -35,6 +38,7 @@ class AddRestaurantForm extends StatefulWidget {
|
||||
this.categories = const <String>[],
|
||||
this.subCategories = const <String>[],
|
||||
this.geocodingStatus = '',
|
||||
this.naverUrlController,
|
||||
});
|
||||
|
||||
@override
|
||||
@@ -196,90 +200,22 @@ class _AddRestaurantFormState extends State<AddRestaurantForm> {
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// 위도/경도 입력
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: TextFormField(
|
||||
controller: widget.latitudeController,
|
||||
keyboardType: const TextInputType.numberWithOptions(
|
||||
decimal: true,
|
||||
),
|
||||
decoration: InputDecoration(
|
||||
labelText: '위도',
|
||||
hintText: '37.5665',
|
||||
prefixIcon: const Icon(Icons.explore),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
),
|
||||
onChanged: widget.onFieldChanged,
|
||||
validator: (value) {
|
||||
if (value != null && value.isNotEmpty) {
|
||||
final latitude = double.tryParse(value);
|
||||
if (latitude == null || latitude < -90 || latitude > 90) {
|
||||
return '올바른 위도값을 입력해주세요';
|
||||
}
|
||||
}
|
||||
return null;
|
||||
},
|
||||
// 네이버 지도 URL (컨트롤러가 있는 경우 항상 표시)
|
||||
if (widget.naverUrlController != null)
|
||||
_buildNaverUrlField(context),
|
||||
|
||||
if (widget.geocodingStatus.isNotEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 8),
|
||||
child: Text(
|
||||
widget.geocodingStatus,
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: Colors.blueGrey,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: TextFormField(
|
||||
controller: widget.longitudeController,
|
||||
keyboardType: const TextInputType.numberWithOptions(
|
||||
decimal: true,
|
||||
),
|
||||
decoration: InputDecoration(
|
||||
labelText: '경도',
|
||||
hintText: '126.9780',
|
||||
prefixIcon: const Icon(Icons.explore),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
),
|
||||
onChanged: widget.onFieldChanged,
|
||||
validator: (value) {
|
||||
if (value != null && value.isNotEmpty) {
|
||||
final longitude = double.tryParse(value);
|
||||
if (longitude == null ||
|
||||
longitude < -180 ||
|
||||
longitude > 180) {
|
||||
return '올바른 경도값을 입력해주세요';
|
||||
}
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.center,
|
||||
children: [
|
||||
Text(
|
||||
'주소가 정확하지 않을 경우 위도/경도를 현재 위치로 입력합니다.',
|
||||
style: Theme.of(
|
||||
context,
|
||||
).textTheme.bodySmall?.copyWith(color: Colors.grey),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
if (widget.geocodingStatus.isNotEmpty) ...[
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
widget.geocodingStatus,
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: Colors.blueGrey,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
@@ -459,4 +395,66 @@ class _AddRestaurantFormState extends State<AddRestaurantForm> {
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildNaverUrlField(BuildContext context) {
|
||||
final url = widget.naverUrlController!.text.trim();
|
||||
final hasUrl = url.isNotEmpty && url.startsWith('http');
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
TextFormField(
|
||||
controller: widget.naverUrlController,
|
||||
keyboardType: TextInputType.multiline,
|
||||
minLines: 1,
|
||||
maxLines: 4,
|
||||
decoration: InputDecoration(
|
||||
labelText: '네이버 지도 링크',
|
||||
hintText: '네이버 지도 공유 링크를 붙여넣으세요',
|
||||
prefixIcon: const Icon(Icons.link),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
suffixIcon: hasUrl
|
||||
? IconButton(
|
||||
icon: Icon(Icons.open_in_new, color: Colors.blue[700]),
|
||||
onPressed: () => _launchNaverUrl(url),
|
||||
tooltip: '네이버 지도에서 열기',
|
||||
)
|
||||
: null,
|
||||
),
|
||||
onChanged: widget.onFieldChanged,
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'공유 텍스트 전체를 붙여넣으면 URL만 자동 추출됩니다.',
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: Colors.grey,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _launchNaverUrl(String text) async {
|
||||
// URL 추출
|
||||
final urlRegex = RegExp(
|
||||
r'(https?://(?:map\.naver\.com|naver\.me)[^\s]+)',
|
||||
caseSensitive: false,
|
||||
);
|
||||
final match = urlRegex.firstMatch(text);
|
||||
final url = match?.group(0) ?? text;
|
||||
|
||||
final uri = Uri.tryParse(url);
|
||||
if (uri == null) return;
|
||||
|
||||
try {
|
||||
await launchUrl(uri, mode: LaunchMode.externalApplication);
|
||||
} catch (_) {
|
||||
await launchUrl(uri, mode: LaunchMode.platformDefault);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,7 +75,7 @@ class AddRestaurantUrlTab extends StatelessWidget {
|
||||
minLines: 1,
|
||||
maxLines: 6,
|
||||
decoration: InputDecoration(
|
||||
labelText: '네이버 지도 URL',
|
||||
labelText: '네이버 지도 링크',
|
||||
hintText: kIsWeb
|
||||
? 'https://map.naver.com/...'
|
||||
: 'https://naver.me/...',
|
||||
|
||||
@@ -32,6 +32,7 @@ class _EditRestaurantDialogState extends ConsumerState<EditRestaurantDialog> {
|
||||
late final TextEditingController _jibunAddressController;
|
||||
late final TextEditingController _latitudeController;
|
||||
late final TextEditingController _longitudeController;
|
||||
late final TextEditingController _naverUrlController;
|
||||
|
||||
bool _isSaving = false;
|
||||
late final String _originalRoadAddress;
|
||||
@@ -64,6 +65,9 @@ class _EditRestaurantDialogState extends ConsumerState<EditRestaurantDialog> {
|
||||
_longitudeController = TextEditingController(
|
||||
text: restaurant.longitude.toString(),
|
||||
);
|
||||
_naverUrlController = TextEditingController(
|
||||
text: restaurant.naverUrl ?? '',
|
||||
);
|
||||
_originalRoadAddress = restaurant.roadAddress;
|
||||
_originalJibunAddress = restaurant.jibunAddress;
|
||||
}
|
||||
@@ -79,6 +83,7 @@ class _EditRestaurantDialogState extends ConsumerState<EditRestaurantDialog> {
|
||||
_jibunAddressController.dispose();
|
||||
_latitudeController.dispose();
|
||||
_longitudeController.dispose();
|
||||
_naverUrlController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@@ -107,6 +112,9 @@ class _EditRestaurantDialogState extends ConsumerState<EditRestaurantDialog> {
|
||||
_latitudeController.text = coords.latitude.toString();
|
||||
_longitudeController.text = coords.longitude.toString();
|
||||
|
||||
// URL 추출: 공유 텍스트에서 URL만 추출
|
||||
final extractedUrl = _extractNaverUrl(_naverUrlController.text.trim());
|
||||
|
||||
final updatedRestaurant = widget.restaurant.copyWith(
|
||||
name: _nameController.text.trim(),
|
||||
category: _categoryController.text.trim(),
|
||||
@@ -125,6 +133,7 @@ class _EditRestaurantDialogState extends ConsumerState<EditRestaurantDialog> {
|
||||
: _jibunAddressController.text.trim(),
|
||||
latitude: coords.latitude,
|
||||
longitude: coords.longitude,
|
||||
naverUrl: extractedUrl.isEmpty ? null : extractedUrl,
|
||||
updatedAt: DateTime.now(),
|
||||
needsAddressVerification: coords.usedCurrentLocation,
|
||||
);
|
||||
@@ -201,6 +210,7 @@ class _EditRestaurantDialogState extends ConsumerState<EditRestaurantDialog> {
|
||||
onFieldChanged: _onFieldChanged,
|
||||
categories: categories,
|
||||
subCategories: subCategories,
|
||||
naverUrlController: _naverUrlController,
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
Row(
|
||||
@@ -288,4 +298,17 @@ class _EditRestaurantDialogState extends ConsumerState<EditRestaurantDialog> {
|
||||
usedCurrentLocation: true,
|
||||
);
|
||||
}
|
||||
|
||||
/// 공유 텍스트에서 네이버 지도 URL만 추출
|
||||
String _extractNaverUrl(String text) {
|
||||
if (text.isEmpty) return '';
|
||||
|
||||
// URL 패턴 추출
|
||||
final urlRegex = RegExp(
|
||||
r'(https?://(?:map\.naver\.com|naver\.me)[^\s]+)',
|
||||
caseSensitive: false,
|
||||
);
|
||||
final match = urlRegex.firstMatch(text);
|
||||
return match?.group(0) ?? text;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
|
||||
import '../../../../core/constants/app_colors.dart';
|
||||
import '../../../../core/constants/app_typography.dart';
|
||||
@@ -17,6 +18,7 @@ class FetchedRestaurantJsonView extends StatefulWidget {
|
||||
final TextEditingController longitudeController;
|
||||
final TextEditingController naverUrlController;
|
||||
final ValueChanged<String> onFieldChanged;
|
||||
final String? naverUrl; // 순수 URL (클릭 가능한 링크용)
|
||||
|
||||
const FetchedRestaurantJsonView({
|
||||
super.key,
|
||||
@@ -32,6 +34,7 @@ class FetchedRestaurantJsonView extends StatefulWidget {
|
||||
required this.longitudeController,
|
||||
required this.naverUrlController,
|
||||
required this.onFieldChanged,
|
||||
this.naverUrl,
|
||||
});
|
||||
|
||||
@override
|
||||
@@ -126,7 +129,7 @@ class _FetchedRestaurantJsonViewState extends State<FetchedRestaurantJsonView> {
|
||||
controller: widget.jibunAddressController,
|
||||
icon: Icons.map,
|
||||
),
|
||||
_buildCoordinateFields(context),
|
||||
_buildNaverUrlField(context),
|
||||
_buildJsonField(
|
||||
context,
|
||||
label: '전화번호',
|
||||
@@ -154,80 +157,79 @@ class _FetchedRestaurantJsonViewState extends State<FetchedRestaurantJsonView> {
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildCoordinateFields(BuildContext context) {
|
||||
final border = OutlineInputBorder(borderRadius: BorderRadius.circular(8));
|
||||
Widget _buildNaverUrlField(BuildContext context) {
|
||||
final url = widget.naverUrl ?? '';
|
||||
if (url.isEmpty) return const SizedBox.shrink();
|
||||
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: const [
|
||||
Icon(Icons.my_location, size: 16),
|
||||
SizedBox(width: 8),
|
||||
Text('좌표'),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: TextFormField(
|
||||
controller: widget.latitudeController,
|
||||
keyboardType: const TextInputType.numberWithOptions(
|
||||
decimal: true,
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 12),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: const [
|
||||
Icon(Icons.link, size: 16),
|
||||
SizedBox(width: 8),
|
||||
Text('네이버 지도:'),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
InkWell(
|
||||
onTap: () => _launchNaverUrl(url),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
child: Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 14),
|
||||
decoration: BoxDecoration(
|
||||
border: Border.all(
|
||||
color: widget.isDark
|
||||
? AppColors.darkDivider
|
||||
: AppColors.lightDivider,
|
||||
),
|
||||
decoration: InputDecoration(
|
||||
labelText: '위도',
|
||||
border: border,
|
||||
isDense: true,
|
||||
),
|
||||
onChanged: widget.onFieldChanged,
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return '위도를 입력해주세요';
|
||||
}
|
||||
final latitude = double.tryParse(value);
|
||||
if (latitude == null || latitude < -90 || latitude > 90) {
|
||||
return '올바른 위도값을 입력해주세요';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
color: widget.isDark
|
||||
? AppColors.darkSurface
|
||||
: AppColors.lightSurface,
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
url,
|
||||
style: TextStyle(
|
||||
color: Colors.blue[700],
|
||||
decoration: TextDecoration.underline,
|
||||
),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Icon(
|
||||
Icons.open_in_new,
|
||||
size: 18,
|
||||
color: Colors.blue[700],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: TextFormField(
|
||||
controller: widget.longitudeController,
|
||||
keyboardType: const TextInputType.numberWithOptions(
|
||||
decimal: true,
|
||||
),
|
||||
decoration: InputDecoration(
|
||||
labelText: '경도',
|
||||
border: border,
|
||||
isDense: true,
|
||||
),
|
||||
onChanged: widget.onFieldChanged,
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return '경도를 입력해주세요';
|
||||
}
|
||||
final longitude = double.tryParse(value);
|
||||
if (longitude == null ||
|
||||
longitude < -180 ||
|
||||
longitude > 180) {
|
||||
return '올바른 경도값을 입력해주세요';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _launchNaverUrl(String url) async {
|
||||
final uri = Uri.tryParse(url);
|
||||
if (uri == null) return;
|
||||
|
||||
try {
|
||||
await launchUrl(uri, mode: LaunchMode.externalApplication);
|
||||
} catch (_) {
|
||||
// 웹 환경에서 실패 시 platformDefault 모드로 재시도
|
||||
await launchUrl(uri, mode: LaunchMode.platformDefault);
|
||||
}
|
||||
}
|
||||
|
||||
Widget _buildCategoryField(BuildContext context) {
|
||||
return RawAutocomplete<String>(
|
||||
textEditingController: widget.categoryController,
|
||||
|
||||
@@ -1,27 +1,38 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
|
||||
import 'package:lunchpick/core/constants/app_colors.dart';
|
||||
import 'package:lunchpick/core/constants/app_typography.dart';
|
||||
import 'package:lunchpick/domain/entities/restaurant.dart';
|
||||
import 'package:lunchpick/presentation/providers/restaurant_provider.dart';
|
||||
import 'package:lunchpick/presentation/providers/visit_provider.dart';
|
||||
import 'edit_restaurant_dialog.dart';
|
||||
|
||||
/// 맛집 카드 위젯
|
||||
/// [lastVisitDate]를 외부에서 주입받아 리스트 렌더링 최적화
|
||||
class RestaurantCard extends ConsumerWidget {
|
||||
final Restaurant restaurant;
|
||||
final double? distanceKm;
|
||||
final DateTime? lastVisitDate;
|
||||
|
||||
const RestaurantCard({super.key, required this.restaurant, this.distanceKm});
|
||||
const RestaurantCard({
|
||||
super.key,
|
||||
required this.restaurant,
|
||||
this.distanceKm,
|
||||
this.lastVisitDate,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
final lastVisitAsync = ref.watch(lastVisitDateProvider(restaurant.id));
|
||||
|
||||
final hasNaverUrl = restaurant.naverUrl != null &&
|
||||
restaurant.naverUrl!.isNotEmpty;
|
||||
|
||||
return Card(
|
||||
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
child: InkWell(
|
||||
onTap: () => _showRestaurantDetail(context, isDark),
|
||||
onTap: hasNaverUrl ? () => _openNaverUrl(restaurant.naverUrl!) : null,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
@@ -177,39 +188,26 @@ class RestaurantCard extends ConsumerWidget {
|
||||
),
|
||||
|
||||
// 마지막 방문일
|
||||
lastVisitAsync.when(
|
||||
data: (lastVisit) {
|
||||
if (lastVisit != null) {
|
||||
final daysSinceVisit = DateTime.now()
|
||||
.difference(lastVisit)
|
||||
.inDays;
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(top: 8),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.schedule,
|
||||
size: 16,
|
||||
color: isDark
|
||||
? AppColors.darkTextSecondary
|
||||
: AppColors.lightTextSecondary,
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
daysSinceVisit == 0
|
||||
? '오늘 방문'
|
||||
: '$daysSinceVisit일 전 방문',
|
||||
style: AppTypography.caption(isDark),
|
||||
),
|
||||
],
|
||||
if (lastVisitDate != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 8),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.schedule,
|
||||
size: 16,
|
||||
color: isDark
|
||||
? AppColors.darkTextSecondary
|
||||
: AppColors.lightTextSecondary,
|
||||
),
|
||||
);
|
||||
}
|
||||
return const SizedBox.shrink();
|
||||
},
|
||||
loading: () => const SizedBox.shrink(),
|
||||
error: (_, __) => const SizedBox.shrink(),
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
_formatLastVisit(lastVisitDate!),
|
||||
style: AppTypography.caption(isDark),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
@@ -217,6 +215,18 @@ class RestaurantCard extends ConsumerWidget {
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _openNaverUrl(String url) async {
|
||||
final uri = Uri.tryParse(url);
|
||||
if (uri == null) return;
|
||||
|
||||
try {
|
||||
await launchUrl(uri, mode: LaunchMode.externalApplication);
|
||||
} catch (_) {
|
||||
// 웹 환경에서 실패 시 platformDefault 모드로 재시도
|
||||
await launchUrl(uri, mode: LaunchMode.platformDefault);
|
||||
}
|
||||
}
|
||||
|
||||
IconData _getCategoryIcon(String category) {
|
||||
switch (category) {
|
||||
case '한식':
|
||||
@@ -240,59 +250,9 @@ class RestaurantCard extends ConsumerWidget {
|
||||
}
|
||||
}
|
||||
|
||||
void _showRestaurantDetail(BuildContext context, bool isDark) {
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
backgroundColor: isDark
|
||||
? AppColors.darkSurface
|
||||
: AppColors.lightSurface,
|
||||
title: Text(restaurant.name),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
_buildDetailRow(
|
||||
'카테고리',
|
||||
'${restaurant.category} > ${restaurant.subCategory}',
|
||||
isDark,
|
||||
),
|
||||
if (restaurant.description != null)
|
||||
_buildDetailRow('설명', restaurant.description!, isDark),
|
||||
if (restaurant.phoneNumber != null)
|
||||
_buildDetailRow('전화번호', restaurant.phoneNumber!, isDark),
|
||||
_buildDetailRow('도로명 주소', restaurant.roadAddress, isDark),
|
||||
_buildDetailRow('지번 주소', restaurant.jibunAddress, isDark),
|
||||
if (restaurant.lastVisitDate != null)
|
||||
_buildDetailRow(
|
||||
'마지막 방문',
|
||||
'${restaurant.lastVisitDate!.year}년 ${restaurant.lastVisitDate!.month}월 ${restaurant.lastVisitDate!.day}일',
|
||||
isDark,
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context),
|
||||
child: const Text('닫기'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildDetailRow(String label, String value, bool isDark) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 4),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(label, style: AppTypography.caption(isDark)),
|
||||
const SizedBox(height: 2),
|
||||
Text(value, style: AppTypography.body2(isDark)),
|
||||
],
|
||||
),
|
||||
);
|
||||
String _formatLastVisit(DateTime date) {
|
||||
final daysSinceVisit = DateTime.now().difference(date).inDays;
|
||||
return daysSinceVisit == 0 ? '오늘 방문' : '$daysSinceVisit일 전 방문';
|
||||
}
|
||||
|
||||
void _handleMenuAction(
|
||||
|
||||
@@ -162,7 +162,7 @@ class _ShareScreenState extends ConsumerState<ShareScreen> {
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
NativeAdPlaceholder(
|
||||
height: 220,
|
||||
height: 360,
|
||||
enabled: !screenshotModeEnabled,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
@@ -211,11 +211,11 @@ class _ShareScreenState extends ConsumerState<ShareScreen> {
|
||||
Text('이 코드를 상대방에게 알려주세요', style: AppTypography.caption(isDark)),
|
||||
const SizedBox(height: 16),
|
||||
TextButton.icon(
|
||||
onPressed: () {
|
||||
onPressed: () async {
|
||||
setState(() {
|
||||
_shareCode = null;
|
||||
});
|
||||
ref.read(bluetoothServiceProvider).stopListening();
|
||||
await ref.read(bluetoothServiceProvider).stopListening();
|
||||
},
|
||||
icon: const Icon(Icons.close),
|
||||
label: const Text('취소'),
|
||||
@@ -551,7 +551,7 @@ class _ShareScreenState extends ConsumerState<ShareScreen> {
|
||||
setState(() {
|
||||
_shareCode = null;
|
||||
});
|
||||
ref.read(bluetoothServiceProvider).stopListening();
|
||||
await ref.read(bluetoothServiceProvider).stopListening();
|
||||
}
|
||||
|
||||
void _showLoadingDialog(String message) {
|
||||
|
||||
@@ -15,10 +15,8 @@ class SplashScreen extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _SplashScreenState extends State<SplashScreen>
|
||||
with TickerProviderStateMixin {
|
||||
late List<AnimationController> _foodControllers;
|
||||
late AnimationController _questionMarkController;
|
||||
late AnimationController _centerIconController;
|
||||
with SingleTickerProviderStateMixin {
|
||||
late AnimationController _animationController;
|
||||
List<Offset>? _iconPositions;
|
||||
Size? _lastScreenSize;
|
||||
|
||||
@@ -42,24 +40,9 @@ class _SplashScreenState extends State<SplashScreen>
|
||||
}
|
||||
|
||||
void _initializeAnimations() {
|
||||
// 음식 아이콘 애니메이션 (여러 개)
|
||||
_foodControllers = List.generate(
|
||||
foodIcons.length,
|
||||
(index) => AnimationController(
|
||||
duration: Duration(seconds: 2 + index % 3),
|
||||
vsync: this,
|
||||
)..repeat(reverse: true),
|
||||
);
|
||||
|
||||
// 물음표 애니메이션
|
||||
_questionMarkController = AnimationController(
|
||||
duration: const Duration(milliseconds: 500),
|
||||
vsync: this,
|
||||
)..repeat();
|
||||
|
||||
// 중앙 아이콘 애니메이션
|
||||
_centerIconController = AnimationController(
|
||||
duration: const Duration(seconds: 1),
|
||||
// 단일 컨트롤러로 모든 애니메이션 제어 (메모리 최적화)
|
||||
_animationController = AnimationController(
|
||||
duration: const Duration(seconds: 2),
|
||||
vsync: this,
|
||||
)..repeat(reverse: true);
|
||||
}
|
||||
@@ -142,9 +125,9 @@ class _SplashScreenState extends State<SplashScreen>
|
||||
children: [
|
||||
// 선택 아이콘
|
||||
ScaleTransition(
|
||||
scale: Tween(begin: 0.8, end: 1.2).animate(
|
||||
scale: Tween(begin: 0.9, end: 1.1).animate(
|
||||
CurvedAnimation(
|
||||
parent: _centerIconController,
|
||||
parent: _animationController,
|
||||
curve: Curves.easeInOut,
|
||||
),
|
||||
),
|
||||
@@ -164,11 +147,11 @@ class _SplashScreenState extends State<SplashScreen>
|
||||
children: [
|
||||
Text('오늘 뭐 먹Z', style: AppTypography.heading1(isDark)),
|
||||
AnimatedBuilder(
|
||||
animation: _questionMarkController,
|
||||
animation: _animationController,
|
||||
builder: (context, child) {
|
||||
final questionMarks =
|
||||
'?' *
|
||||
(((_questionMarkController.value * 3).floor() % 3) +
|
||||
(((_animationController.value * 3).floor() % 3) +
|
||||
1);
|
||||
return Text(
|
||||
questionMarks,
|
||||
@@ -217,29 +200,30 @@ class _SplashScreenState extends State<SplashScreen>
|
||||
|
||||
return List.generate(foodIcons.length, (index) {
|
||||
final position = _iconPositions![index];
|
||||
// 각 아이콘마다 위상(phase)을 다르게 적용
|
||||
final phase = index / foodIcons.length;
|
||||
|
||||
return Positioned(
|
||||
left: position.dx,
|
||||
top: position.dy,
|
||||
child: FadeTransition(
|
||||
opacity: Tween(begin: 0.2, end: 0.8).animate(
|
||||
CurvedAnimation(
|
||||
parent: _foodControllers[index],
|
||||
curve: Curves.easeInOut,
|
||||
),
|
||||
),
|
||||
child: ScaleTransition(
|
||||
scale: Tween(begin: 0.5, end: 1.5).animate(
|
||||
CurvedAnimation(
|
||||
parent: _foodControllers[index],
|
||||
curve: Curves.easeInOut,
|
||||
child: AnimatedBuilder(
|
||||
animation: _animationController,
|
||||
builder: (context, child) {
|
||||
// 위상 차이로 각 아이콘이 다른 타이밍에 애니메이션
|
||||
final value =
|
||||
((_animationController.value + phase) % 1.0 - 0.5).abs() * 2;
|
||||
return Opacity(
|
||||
opacity: 0.2 + value * 0.4,
|
||||
child: Transform.scale(
|
||||
scale: 0.7 + value * 0.5,
|
||||
child: child,
|
||||
),
|
||||
),
|
||||
child: Icon(
|
||||
foodIcons[index],
|
||||
size: 40,
|
||||
color: AppColors.lightPrimary.withOpacity(0.3),
|
||||
),
|
||||
);
|
||||
},
|
||||
child: Icon(
|
||||
foodIcons[index],
|
||||
size: 40,
|
||||
color: AppColors.lightPrimary.withValues(alpha: 0.3),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -247,9 +231,9 @@ class _SplashScreenState extends State<SplashScreen>
|
||||
}
|
||||
|
||||
void _navigateToHome() {
|
||||
// 권한 요청이 지연되어도 스플래시(Splash) 화면이 멈추지 않도록 최대 5초만 대기한다.
|
||||
// 권한 요청이 지연되어도 스플래시(Splash) 화면이 멈추지 않도록 최대 3초만 대기한다.
|
||||
final permissionFuture = _ensurePermissions().timeout(
|
||||
const Duration(seconds: 5),
|
||||
const Duration(seconds: 3),
|
||||
onTimeout: () {},
|
||||
);
|
||||
|
||||
@@ -274,11 +258,7 @@ class _SplashScreenState extends State<SplashScreen>
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
for (final controller in _foodControllers) {
|
||||
controller.dispose();
|
||||
}
|
||||
_questionMarkController.dispose();
|
||||
_centerIconController.dispose();
|
||||
_animationController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -166,8 +166,8 @@ class RecommendationNotifier extends StateNotifier<AsyncValue<Restaurant?>> {
|
||||
required List<String> selectedCategories,
|
||||
List<String> excludedRestaurantIds = const [],
|
||||
}) async {
|
||||
// 현재 위치 가져오기
|
||||
final location = await _ref.read(currentLocationProvider.future);
|
||||
// 현재 위치 가져오기 (StreamProvider에서 최신 위치 사용)
|
||||
final location = _ref.read(currentLocationWithFallbackProvider).valueOrNull;
|
||||
if (location == null) {
|
||||
throw Exception('위치 정보를 가져올 수 없습니다');
|
||||
}
|
||||
@@ -382,8 +382,8 @@ class EnhancedRecommendationNotifier
|
||||
return;
|
||||
}
|
||||
|
||||
// 현재 위치 가져오기
|
||||
final location = await _ref.read(currentLocationProvider.future);
|
||||
// 현재 위치 가져오기 (StreamProvider에서 최신 위치 사용)
|
||||
final location = _ref.read(currentLocationWithFallbackProvider).valueOrNull;
|
||||
if (location == null) {
|
||||
state = state.copyWith(error: '위치 정보를 가져올 수 없습니다', isLoading: false);
|
||||
return;
|
||||
|
||||
@@ -31,6 +31,9 @@ final monthlyVisitStatsProvider =
|
||||
ref,
|
||||
params,
|
||||
) async {
|
||||
// visitRecordsProvider를 watch하여 방문 기록 변경 시 자동 갱신
|
||||
await ref.watch(visitRecordsProvider.future);
|
||||
|
||||
final repository = ref.watch(visitRepositoryProvider);
|
||||
return repository.getMonthlyVisitStats(params.year, params.month);
|
||||
});
|
||||
@@ -41,13 +44,19 @@ final monthlyCategoryVisitStatsProvider =
|
||||
ref,
|
||||
params,
|
||||
) async {
|
||||
final repository = ref.watch(visitRepositoryProvider);
|
||||
// visitRecordsProvider를 watch하여 방문 기록 변경 시 자동 갱신
|
||||
final allRecords = await ref.watch(visitRecordsProvider.future);
|
||||
final restaurants = await ref.watch(restaurantListProvider.future);
|
||||
|
||||
final records = await repository.getVisitRecordsByDateRange(
|
||||
startDate: DateTime(params.year, params.month, 1),
|
||||
endDate: DateTime(params.year, params.month + 1, 0),
|
||||
);
|
||||
// 해당 월의 기록만 필터링
|
||||
final startDate = DateTime(params.year, params.month, 1);
|
||||
final endDate = DateTime(params.year, params.month + 1, 0);
|
||||
final records = allRecords.where((record) {
|
||||
return record.visitDate.isAfter(
|
||||
startDate.subtract(const Duration(days: 1)),
|
||||
) &&
|
||||
record.visitDate.isBefore(endDate.add(const Duration(days: 1)));
|
||||
}).toList();
|
||||
|
||||
final categoryCount = <String, int>{};
|
||||
for (final record in records) {
|
||||
@@ -157,6 +166,23 @@ final lastVisitDateProvider = FutureProvider.family<DateTime?, String>((
|
||||
return repository.getLastVisitDate(restaurantId);
|
||||
});
|
||||
|
||||
/// 모든 맛집의 마지막 방문일을 한 번에 조회 (리스트 최적화용)
|
||||
final allLastVisitDatesProvider =
|
||||
FutureProvider<Map<String, DateTime?>>((ref) async {
|
||||
final records = await ref.watch(visitRecordsProvider.future);
|
||||
|
||||
// restaurantId별 가장 최근 방문일 계산
|
||||
final lastVisitMap = <String, DateTime>{};
|
||||
for (final record in records) {
|
||||
final existing = lastVisitMap[record.restaurantId];
|
||||
if (existing == null || record.visitDate.isAfter(existing)) {
|
||||
lastVisitMap[record.restaurantId] = record.visitDate;
|
||||
}
|
||||
}
|
||||
|
||||
return lastVisitMap;
|
||||
});
|
||||
|
||||
/// 기간별 방문 기록 Provider
|
||||
final visitRecordsByPeriodProvider =
|
||||
FutureProvider.family<
|
||||
|
||||
@@ -8,6 +8,15 @@ import '../providers/di_providers.dart';
|
||||
import '../providers/restaurant_provider.dart';
|
||||
import '../providers/location_provider.dart';
|
||||
|
||||
/// 지오코딩 실패 시 발생하는 예외
|
||||
class GeocodingException implements Exception {
|
||||
final String message;
|
||||
const GeocodingException(this.message);
|
||||
|
||||
@override
|
||||
String toString() => message;
|
||||
}
|
||||
|
||||
/// 식당 추가 화면의 상태 모델
|
||||
class AddRestaurantState {
|
||||
final bool isLoading;
|
||||
@@ -128,10 +137,23 @@ class RestaurantFormData {
|
||||
jibunAddress: jibunAddressController.text.trim(),
|
||||
latitude: latitudeController.text.trim(),
|
||||
longitude: longitudeController.text.trim(),
|
||||
naverUrl: naverUrlController.text.trim(),
|
||||
naverUrl: _extractNaverUrl(naverUrlController.text.trim()),
|
||||
);
|
||||
}
|
||||
|
||||
/// 공유 텍스트에서 네이버 지도 URL만 추출
|
||||
static String _extractNaverUrl(String text) {
|
||||
if (text.isEmpty) return '';
|
||||
|
||||
// URL 패턴 추출
|
||||
final urlRegex = RegExp(
|
||||
r'(https?://(?:map\.naver\.com|naver\.me)[^\s]+)',
|
||||
caseSensitive: false,
|
||||
);
|
||||
final match = urlRegex.firstMatch(text);
|
||||
return match?.group(0) ?? text;
|
||||
}
|
||||
|
||||
/// Restaurant 엔티티로부터 폼 데이터 생성
|
||||
factory RestaurantFormData.fromRestaurant(Restaurant restaurant) {
|
||||
return RestaurantFormData(
|
||||
@@ -304,6 +326,7 @@ class AddRestaurantViewModel extends StateNotifier<AddRestaurantState> {
|
||||
jibunAddress: state.formData.jibunAddress,
|
||||
fallbackLatitude: fetchedData.latitude,
|
||||
fallbackLongitude: fetchedData.longitude,
|
||||
allowFallbackWhenGeocodingFails: false,
|
||||
);
|
||||
|
||||
restaurantToSave = fetchedData.copyWith(
|
||||
@@ -350,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;
|
||||
}
|
||||
}
|
||||
@@ -436,6 +463,7 @@ class AddRestaurantViewModel extends StateNotifier<AddRestaurantState> {
|
||||
required String jibunAddress,
|
||||
double? fallbackLatitude,
|
||||
double? fallbackLongitude,
|
||||
bool allowFallbackWhenGeocodingFails = true,
|
||||
}) async {
|
||||
final parsedLat = double.tryParse(latitudeText);
|
||||
final parsedLon = double.tryParse(longitudeText);
|
||||
@@ -468,8 +496,14 @@ class AddRestaurantViewModel extends StateNotifier<AddRestaurantState> {
|
||||
);
|
||||
} else {
|
||||
state = state.copyWith(
|
||||
geocodingStatus: '지오코딩 실패: $address, 현재 위치/기본 좌표로 대체',
|
||||
geocodingStatus: '지오코딩 실패: $address, 주소를 다시 확인해 주세요.',
|
||||
);
|
||||
|
||||
if (!allowFallbackWhenGeocodingFails) {
|
||||
const userMessage = '위치 정보를 가져올 수 없습니다. 주소를 확인해주세요.';
|
||||
state = state.copyWith(errorMessage: userMessage);
|
||||
throw GeocodingException(userMessage);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'dart:async';
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:google_mobile_ads/google_mobile_ads.dart';
|
||||
import 'package:lunchpick/core/constants/app_colors.dart';
|
||||
@@ -54,6 +55,14 @@ class _NativeAdPlaceholderState extends State<NativeAdPlaceholder> {
|
||||
return;
|
||||
}
|
||||
|
||||
final oldType = _templateTypeForHeight(oldWidget.height);
|
||||
final newType = _templateTypeForHeight(widget.height);
|
||||
|
||||
if (oldType != newType) {
|
||||
_loadAd();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!oldWidget.enabled && widget.enabled) {
|
||||
_loadAd();
|
||||
return;
|
||||
@@ -91,10 +100,11 @@ class _NativeAdPlaceholderState extends State<NativeAdPlaceholder> {
|
||||
});
|
||||
|
||||
final adUnitId = AdHelper.nativeAdUnitId;
|
||||
final templateType = _templateTypeForHeight(widget.height);
|
||||
_nativeAd = NativeAd(
|
||||
adUnitId: adUnitId,
|
||||
request: const AdRequest(),
|
||||
nativeTemplateStyle: _buildTemplateStyle(),
|
||||
nativeTemplateStyle: _buildTemplateStyle(templateType),
|
||||
listener: NativeAdListener(
|
||||
onAdLoaded: (ad) {
|
||||
if (!mounted) {
|
||||
@@ -130,23 +140,26 @@ class _NativeAdPlaceholderState extends State<NativeAdPlaceholder> {
|
||||
_refreshTimer = Timer(delay, _loadAd);
|
||||
}
|
||||
|
||||
NativeTemplateStyle _buildTemplateStyle() {
|
||||
NativeTemplateStyle _buildTemplateStyle(TemplateType templateType) {
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
return NativeTemplateStyle(
|
||||
templateType: TemplateType.medium,
|
||||
mainBackgroundColor: isDark ? AppColors.darkSurface : Colors.white,
|
||||
templateType: templateType,
|
||||
mainBackgroundColor:
|
||||
isDark ? AppColors.darkSurface : AppColors.lightSurface,
|
||||
cornerRadius: 0,
|
||||
callToActionTextStyle: NativeTemplateTextStyle(
|
||||
textColor: Colors.white,
|
||||
textColor: AppColors.lightSurface,
|
||||
backgroundColor: AppColors.lightPrimary,
|
||||
style: NativeTemplateFontStyle.bold,
|
||||
),
|
||||
primaryTextStyle: NativeTemplateTextStyle(
|
||||
textColor: isDark ? Colors.white : Colors.black87,
|
||||
textColor:
|
||||
isDark ? AppColors.darkTextPrimary : AppColors.lightTextPrimary,
|
||||
style: NativeTemplateFontStyle.bold,
|
||||
),
|
||||
secondaryTextStyle: NativeTemplateTextStyle(
|
||||
textColor: isDark ? Colors.white70 : Colors.black54,
|
||||
textColor:
|
||||
isDark ? AppColors.darkTextSecondary : AppColors.lightTextSecondary,
|
||||
style: NativeTemplateFontStyle.normal,
|
||||
),
|
||||
);
|
||||
@@ -155,21 +168,29 @@ class _NativeAdPlaceholderState extends State<NativeAdPlaceholder> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
final containerHeight = _resolveContainerHeight();
|
||||
|
||||
if (!AdHelper.isMobilePlatform || !widget.enabled) {
|
||||
return _buildPlaceholder(isDark, isLoading: false);
|
||||
return _buildPlaceholder(
|
||||
isDark,
|
||||
containerHeight: containerHeight,
|
||||
isLoading: false,
|
||||
);
|
||||
}
|
||||
|
||||
return AnimatedSwitcher(
|
||||
duration: const Duration(milliseconds: 250),
|
||||
child: _isLoaded && _nativeAd != null
|
||||
? _buildAdView(isDark)
|
||||
: _buildPlaceholder(isDark, isLoading: _isLoading),
|
||||
? _buildAdView(isDark, containerHeight)
|
||||
: _buildPlaceholder(
|
||||
isDark,
|
||||
containerHeight: containerHeight,
|
||||
isLoading: _isLoading,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildAdView(bool isDark) {
|
||||
final containerHeight = max(widget.height, 200.0);
|
||||
Widget _buildAdView(bool isDark, double containerHeight) {
|
||||
return Container(
|
||||
key: const ValueKey('nativeAdLoaded'),
|
||||
margin: widget.margin ?? EdgeInsets.zero,
|
||||
@@ -180,8 +201,11 @@ class _NativeAdPlaceholderState extends State<NativeAdPlaceholder> {
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildPlaceholder(bool isDark, {required bool isLoading}) {
|
||||
final containerHeight = max(widget.height, 200.0);
|
||||
Widget _buildPlaceholder(
|
||||
bool isDark, {
|
||||
required double containerHeight,
|
||||
required bool isLoading,
|
||||
}) {
|
||||
return Container(
|
||||
key: const ValueKey('nativeAdPlaceholder'),
|
||||
margin: widget.margin ?? EdgeInsets.zero,
|
||||
@@ -205,16 +229,39 @@ class _NativeAdPlaceholderState extends State<NativeAdPlaceholder> {
|
||||
);
|
||||
}
|
||||
|
||||
double _resolveContainerHeight() {
|
||||
final templateType = _templateTypeForHeight(widget.height);
|
||||
final minHeight = _templateMinHeight(templateType);
|
||||
return max(widget.height, minHeight);
|
||||
}
|
||||
|
||||
TemplateType _templateTypeForHeight(double height) {
|
||||
// Medium 템플릿은 SDK 기본 레이아웃이 커서, 높이가 낮을 경우 Small로 대체해 잘림을 방지한다.
|
||||
return height < 320 ? TemplateType.small : TemplateType.medium;
|
||||
}
|
||||
|
||||
double _templateMinHeight(TemplateType type) {
|
||||
if (type == TemplateType.small) {
|
||||
return 100;
|
||||
}
|
||||
return switch (defaultTargetPlatform) {
|
||||
TargetPlatform.iOS => 402.0,
|
||||
TargetPlatform.android => 350.0,
|
||||
_ => 320.0,
|
||||
};
|
||||
}
|
||||
|
||||
BoxDecoration _decoration(bool isDark) {
|
||||
return BoxDecoration(
|
||||
color: isDark ? AppColors.darkSurface : Colors.white,
|
||||
color: isDark ? AppColors.darkSurface : AppColors.lightSurface,
|
||||
border: Border.all(
|
||||
color: isDark ? AppColors.darkDivider : AppColors.lightDivider,
|
||||
width: 2,
|
||||
),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: (isDark ? Colors.black : Colors.grey).withOpacity(0.08),
|
||||
color: (isDark ? AppColors.darkBackground : AppColors.lightDivider)
|
||||
.withValues(alpha: 0.3),
|
||||
blurRadius: 8,
|
||||
offset: const Offset(0, 4),
|
||||
),
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
import FlutterMacOS
|
||||
import Foundation
|
||||
|
||||
import ble_peripheral
|
||||
import flutter_blue_plus_darwin
|
||||
import flutter_local_notifications
|
||||
import geolocator_apple
|
||||
@@ -15,6 +16,7 @@ import url_launcher_macos
|
||||
import webview_flutter_wkwebview
|
||||
|
||||
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
|
||||
BlePeripheralPlugin.register(with: registry.registrar(forPlugin: "BlePeripheralPlugin"))
|
||||
FlutterBluePlusPlugin.register(with: registry.registrar(forPlugin: "FlutterBluePlusPlugin"))
|
||||
FlutterLocalNotificationsPlugin.register(with: registry.registrar(forPlugin: "FlutterLocalNotificationsPlugin"))
|
||||
GeolocatorPlugin.register(with: registry.registrar(forPlugin: "GeolocatorPlugin"))
|
||||
|
||||
@@ -49,6 +49,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.13.0"
|
||||
ble_peripheral:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: ble_peripheral
|
||||
sha256: "858d370709507155bbf69e6160e9cb81d802e664f133a649a38b9ca04439884c"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.4.0"
|
||||
bluez:
|
||||
dependency: transitive
|
||||
description:
|
||||
|
||||
@@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev
|
||||
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
|
||||
# In Windows, build-name is used as the major, minor, and patch parts
|
||||
# of the product and file versions while build-number is used as the build suffix.
|
||||
version: 1.0.0+1
|
||||
version: 1.1.1+5
|
||||
|
||||
environment:
|
||||
sdk: ^3.8.1
|
||||
@@ -63,6 +63,7 @@ dependencies:
|
||||
|
||||
# Bluetooth
|
||||
flutter_blue_plus: ^1.31.0
|
||||
ble_peripheral: ^2.4.0 # Peripheral 역할 (Receiver)
|
||||
|
||||
# Utilities
|
||||
uuid: ^4.2.1
|
||||
|
||||
@@ -6,12 +6,15 @@
|
||||
|
||||
#include "generated_plugin_registrant.h"
|
||||
|
||||
#include <ble_peripheral/ble_peripheral_plugin_c_api.h>
|
||||
#include <geolocator_windows/geolocator_windows.h>
|
||||
#include <permission_handler_windows/permission_handler_windows_plugin.h>
|
||||
#include <share_plus/share_plus_windows_plugin_c_api.h>
|
||||
#include <url_launcher_windows/url_launcher_windows.h>
|
||||
|
||||
void RegisterPlugins(flutter::PluginRegistry* registry) {
|
||||
BlePeripheralPluginCApiRegisterWithRegistrar(
|
||||
registry->GetRegistrarForPlugin("BlePeripheralPluginCApi"));
|
||||
GeolocatorWindowsRegisterWithRegistrar(
|
||||
registry->GetRegistrarForPlugin("GeolocatorWindows"));
|
||||
PermissionHandlerWindowsPluginRegisterWithRegistrar(
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#
|
||||
|
||||
list(APPEND FLUTTER_PLUGIN_LIST
|
||||
ble_peripheral
|
||||
geolocator_windows
|
||||
permission_handler_windows
|
||||
share_plus
|
||||
|
||||
Reference in New Issue
Block a user