[flutter] 플러터(expandable)을 사용하는 게시판 및 포럼 앱 개발 방법

플러터는 Google에서 개발한 크로스 플랫폼 개발 프레임워크로, iOS와 Android를 포함한 다양한 플랫폼에서 동작하는 앱을 만들 수 있습니다. 이번 블로그 포스트에서는 플러터의 expandable 위젯을 사용하여 게시판 및 포럼 앱을 개발하는 방법에 대해 알아보겠습니다.

1. 필요한 패키지 설치

먼저, expandable 위젯을 사용하기 위해 expandable 패키지를 설치해야 합니다. pubspec.yaml 파일에서 다음과 같이 패키지를 추가해주세요:

dependencies:
  flutter:
    sdk: flutter

  expandable: ^5.0.0

flutter packages get 명령어를 실행하여 패키지를 다운로드하고, 종속성을 업데이트합니다.

2. Expandable 위젯 사용하기

Expandable 위젯은 확장 가능한 컨테이너를 생성하는 데 사용됩니다. 앱의 게시판 화면에서 각각의 게시물은 확장 가능한 컨테이너로 표시됩니다. 사용자가 게시물을 터치하면 해당 게시물이 확장되거나 축소됩니다.

먼저, ExpandableNotifier 위젯으로 게시물이 확장되었는지 여부를 추적할 수 있도록 설정해야 합니다. 이 위젯을 사용하면 expandable 상태를 관리하는 데 도움이 됩니다. 다음과 같이 코드를 작성해주세요:

ExpandableNotifier(
  child: ListView.builder(
    itemCount: posts.length,
    itemBuilder: (context, index) {
      return ExpandablePanel(
        header: Text(posts[index].title),
        expanded: Text(posts[index].content),
        tapHeaderToExpand: true,
        tapBodyToCollapse: true,
      );
    }
  ),
);

위의 코드에서 ExpandableNotifier는 게시물이 확장되었는지 여부를 추적합니다. 그리고 ListView.builder를 사용하여 여러 개의 게시물을 표시합니다. ExpandablePanel은 게시물의 제목을 header로, 내용을 expanded로 설정합니다. 또한, tapHeaderToExpandtapBodyToCollapsetrue로 설정하여 헤더 또는 본문을 터치하면 확장 또는 축소되도록 합니다.

3. 게시물 데이터 가져오기

실제로 게시물 데이터를 가져오는 방법은 앱의 요구사항에 따라 다를 수 있습니다. 예를 들어, API 호출, 데이터베이스 쿼리 등을 사용하여 게시물 목록을 가져올 수 있습니다. 이 예제에서는 단순화를 위해 하드코딩된 데이터를 사용하도록 하겠습니다.

class Post {
  final String title;
  final String content;

  Post(this.title, this.content);
}

List<Post> posts = [
  Post('첫 번째 게시물', '첫 번째 게시물 내용입니다.'),
  Post('두 번째 게시물', '두 번째 게시물 내용입니다.'),
  // 추가 게시물들...
];

4. 전체 코드

import 'package:flutter/material.dart';
import 'package:expandable/expandable.dart';

class Post {
  final String title;
  final String content;

  Post(this.title, this.content);
}

List<Post> posts = [
  Post('첫 번째 게시물', '첫 번째 게시물 내용입니다.'),
  Post('두 번째 게시물', '두 번째 게시물 내용입니다.'),
  // 추가 게시물들...
];

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('게시판'),
        ),
        body: ExpandableNotifier(
          child: ListView.builder(
            itemCount: posts.length,
            itemBuilder: (context, index) {
              return ExpandablePanel(
                header: Text(posts[index].title),
                expanded: Text(posts[index].content),
                tapHeaderToExpand: true,
                tapBodyToCollapse: true,
              );
            }
          ),
        ),
      ),
    );
  }
}

이제 앱을 실행하면 게시판 화면이 표시되고, 사용자가 게시물을 터치하면 해당 게시물이 확장됩니다. 다시 터치하면 축소됩니다.

플러터의 expandable 위젯을 사용하여 게시판 및 포럼 앱을 개발하는 방법에 대해 알아보았습니다. 플러터의 다른 위젯과 함께 사용하면 보다 다양한 기능을 구현할 수 있습니다. 자세한 내용은 expandable 패키지의 공식 문서를 참조해주세요.