본문 바로가기

06. 앱

00014. [APP-00002] 사진 기반 식물/동물 인식 앱 개발기 #5

반응형

#5. 식물 인식 결과 받아오기 (Plant.id 연동 실전)

이번 편에서는 실제로 Plant.id API에 이미지를 전송하고, 식물 이름과 결과를 받아와 표시하는 부분을 구현해볼게.


✅ 1단계: API 요청 함수 만들기

lib/services/plant_id_service.dart 파일 생성:

import 'dart:convert';
import 'package:http/http.dart' as http;
import '../secrets.dart';

Future<map<string, dynamic="">> identifyPlant(String base64Image) async {
  const url = 'https://api.plant.id/v2/identify';

  final headers = {
    'Content-Type': 'application/json',
    'Api-Key': plantIdApiKey,
  };

  final body = jsonEncode({
    "images": [base64Image],
    "organs": ["leaf"],
    "similar_images": true
  });

  final response = await http.post(Uri.parse(url), headers: headers, body: body);

  if (response.statusCode == 200) {
    return jsonDecode(response.body);
  } else {
    throw Exception('Failed to identify plant: ${response.statusCode}');
  }
}</map<string,>

🧩 2단계: 홈 화면에서 요청 연결하기

lib/screens/home_screen.dart의 코드 일부를 아래처럼 확장해줘:

// 중간 생략...
import '../services/image_encoder.dart';
import '../services/plant_id_service.dart';

String? _result;
bool _loading = false;

Future<void> _identifyPlant() async {
  if (_image == null) return;
  setState(() => _loading = true);

  final base64Image = await encodeImageToBase64(_image!);
  try {
    final result = await identifyPlant(base64Image);
    setState(() {
      _result = result['suggestions']?[0]?['plant_name'] ?? '이름을 찾을 수 없어요';
    });
  } catch (e) {
    setState(() {
      _result = '에러 발생: $e';
    });
  } finally {
    setState(() => _loading = false);
  }
}

버튼 하나 더 추가:

ElevatedButton(
  onPressed: _identifyPlant,
  child: const Text('식물 인식하기'),
),

결과 출력도 아래처럼 추가:

if (_loading)
  const CircularProgressIndicator()
else if (_result != null)
  Text(_result!, style: const TextStyle(fontSize: 16))

✅ 실행 결과

  • 이미지 선택 후 "식물 인식하기" 버튼 클릭 시 API 요청
  • 결과 식물 이름을 화면에 출력
  • 오류 발생 시 메시지 출력

다음 에피소드 예고

#6. 결과 더 예쁘게 보여주기 (카드 UI + 유사 이미지 출력)

  • 인식 결과 카드 디자인
  • Plant.id의 similar_images 활용해 사진 출력
  • Flutter에서 이미지 리스트 구성
반응형