[flutter] 플러터(expandable)을 이용한 음식 및 요리 레시피 앱 개발 방법

이 글에서는 플러터의 ‘expandable’ 위젯을 활용하여 음식 및 요리 레시피 앱을 개발하는 방법에 대해 알아보겠습니다.

1. Expandable 패키지 설치

먼저, expandable 패키지를 프로젝트에 설치해야 합니다. pubspec.yaml 파일에 아래와 같이 패키지를 추가하세요:

dependencies:
  expandable: ^5.0.0

그리고 터미널을 열고 다음 명령어를 실행하여 패키지를 다운로드하세요:

flutter pub get

2. Expandable 위젯 추가

이제 expandable 패키지를 사용하여 expandable 위젯을 추가할 수 있습니다. 아래와 같은 코드를 참고하세요:

import 'package:expandable/expandable.dart';

class RecipeItem extends StatelessWidget {
  final Recipe recipe;

  RecipeItem(this.recipe);

  @override
  Widget build(BuildContext context) {
    return ExpandablePanel(
      header: Text(recipe.title),
      collapsed: Text(
        recipe.shortDescription,
        softWrap: true,
        maxLines: 2,
        overflow: TextOverflow.ellipsis,
      ),
      expanded: Text(recipe.description),
      tapHeaderToExpand: true,
      hasIcon: true,
    );
  }
}

위 코드에서는 ExpandablePanel을 사용하여 레시피의 제목을 header로, 짧은 설명을 collapsed로, 전체 설명을 expanded로 보여주고 있습니다. 이 외에도 탭하여 확장되도록 하는 tapHeaderToExpand와 아이콘을 표시하는 hasIcon 등의 옵션을 설정할 수 있습니다.

3. 레시피 목록 화면에 적용

이제 RecipeItem 위젯을 사용하여 레시피 목록 화면을 구성해보겠습니다. 아래와 같은 코드를 참고하세요:

class RecipeListScreen extends StatelessWidget {
  final List<Recipe> recipes;

  RecipeListScreen(this.recipes);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("음식 및 요리 레시피"),
      ),
      body: ListView.builder(
        itemCount: recipes.length,
        itemBuilder: (BuildContext context, int index) {
          return RecipeItem(recipes[index]);
        },
      ),
    );
  }
}

위 코드에서는 ListView.builder를 사용하여 RecipeItem 위젯을 목록으로 렌더링하고 있습니다. recipes 변수는 레시피 데이터가 담긴 리스트입니다. 이 리스트를 받아서 RecipeItem 위젯을 여러 개 만들어서 화면에 표시합니다.

4. 데이터 모델 작성

마지막으로, 레시피 데이터를 담을 데이터 모델을 작성해야 합니다. 아래와 같은 코드를 참고하세요:

class Recipe {
  final String title;
  final String shortDescription;
  final String description;

  Recipe({required this.title, required this.shortDescription, required this.description});
}

위 코드에서는 레시피의 제목(title), 짧은 설명(shortDescription), 전체 설명(description)을 저장하는 Recipe 클래스를 정의하고 있습니다.

마무리

이제 플러터의 expandable 위젯을 이용하여 음식 및 요리 레시피 앱을 개발하는 방법에 대해 알아보았습니다. expandable 패키지를 설치하고 위젯을 추가한 후, 레시피 목록 화면에 적용하고 데이터 모델을 작성하는 과정을 진행하였습니다. 이를 기반으로 원하는 기능을 추가하고 디자인을 개선하여 멋진 앱을 완성해보세요.