List 항목 구현

Obx 위젯으로 상태 변화 감지

Listview를 RefeshIndicator로 감싸고 GlobalKey를 넣어줌으로 화면을 아래로 드래그할때 새로고침 구현

class HomePage extends StatelessWidget {
  var scaffoldKey = GlobalKey<ScaffoldState>();
  var refreshKey = GlobalKey<RefreshIndicatorState>();
  PostController postController = Get.put(PostController());
  @override
  Widget build(BuildContext context) {
    postController.findAll();
    return Scaffold(
      key: scaffoldKey,
      appBar: AppBar(),
      drawer: _navigation(context),
      body: Obx(
        () => RefreshIndicator(
          key: refreshKey,
          onRefresh: () async {
            await postController.findAll();
          },
          child: ListView.separated(
              itemBuilder: (context, index) {
                return ListTile(
                  onTap: () {
                    postController.findAll();
                  },
                  title: Text("${postController.posts[index].title} : ${postController.posts[index].id}"),
                  leading: Text("$index"),
                );
              },
              separatorBuilder: (context, index) {
                return Divider();
              },
              itemCount: postController.posts.length),
        ),
      ),
    );
  }
}

Controller

전체 게시글을 Rx 타입으로 받아 관찰

class PostController extends GetxController {
  static PostController get to => Get.find();
  final _postRepository = PostRepository();
  final posts = <PostResDto>[].obs;
  final post = Post().obs;

  Future<void> findAll() async {
    List<PostResDto> posts = await _postRepository.findAll();
    this.posts.value = posts;
  }
}

PostResDto

게시글을 받아올때 문서 id 추가를 위해 dto 생성

import 'package:flutter_firebase_blog/domain/user/user.dart';

class PostResDto {
  final String? id;
  final String? title;
  final String? content;
  final UserModel? user;
  final DateTime? created;
  final DateTime? updated;

  PostResDto({
    this.id,
    this.title,
    this.content,
    this.user,
    this.created,
    this.updated,
  });

  PostResDto.fromJson(Map<String, dynamic> json)
      : id = json['id'],
        title = json['title'],
        content = json['content'],
        user = UserModel.fromMap(json['user']),
        created = json['created'].toDate(),
        updated = json['updated'].toDate();

  Map<String, Object?> toJson() {
    return {
      'id': id,
      'title': title,
      'content': content,
      'user': user!.toJson(),
      'created': created,
      'updated': updated,
    };
  }
}

Provider

post collection의 전체 데이터 요청

class PostProvider {
  final postRef = firebaseFirestore.collection("post").withConverter<Post>(
        fromFirestore: (snapshot, options) => Post.fromJson(snapshot.data()!),
        toFirestore: (post, options) => post.toJson(),
      );

  Future<List<QueryDocumentSnapshot<Post>>> findAll() async =>
      await postRef.get().then((snapshot) => snapshot.docs);
}

Repository

요청 결과값을 controller에 전달

class PostRepository {
  final _postProvider = PostProvider();

  Future<List<PostResDto>> findAll() async {
    List<QueryDocumentSnapshot<Post>> posts = await _postProvider.findAll();
    List<PostResDto> result = posts
        .map((e) => PostResDto(
            id: e.reference.id,
            title: e.data().title,
            content: e.data().content,
            user: e.data().user,
            created: e.data().created,
            updated: e.data().updated))
        .toList();
    return result;
  }
 }

Git commit

https://github.com/mugon-dev/flutter_firebase_blog/commit/82d8d63c0f17a86be21c327033d9c0cae86d6682

 

home page 전체 게시글 불러오기 구현 및 새로고침 구현 · mugon-dev/flutter_firebase_blog@82d8d63

Permalink This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository. Browse files home page 전체 게시글 불러오기 구현 및 새로고침 구현 Loading branch information Showing 4 changed fil

github.com

문서 id 추가 수정

https://github.com/mugon-dev/flutter_firebase_blog/commit/99878565c8ead21b37753ebb91ebfd32d5966d3b

 

게시글 리스트 가져올때 문서 id 추가 · mugon-dev/flutter_firebase_blog@9987856

Permalink This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository. Browse files 게시글 리스트 가져올때 문서 id 추가 Loading branch information Showing 5 changed files with 56 additions

github.com

 

728x90

+ Recent posts