Contents
VM에 페이징, 페이지 로드 기능 구현하기페이징 처리를 하기 위해서는
pull_to_refresh: ^2.0.0
<< 라이브러리가 필요합니다. pubspec.yaml 에 추가해주세요.Body의 build에 ref.read를 해줍니다. (refreshController 때문에 사용합니다.)

페이징 처리를 할 목록페이지에
SmartRefresher
위젯을 사용해줍니다.컨트롤러가 필수적인 요소입니다.
controller: vm.refreshCtrl,
이 컨트롤러는 목록 페이지의 ViewModel에 넣어주면 됩니다.

enablePullUp과 onRefresh
두 개는 쌍을 이룹니다.
기능으로는 화면 제일 상단에서 손가락으로 아래를 당길 시
다시 목록 아이템을 불러오는 역할을 합니다.

enablePullDown과 onLoading (페이징)
이 두 가지도 서로 쌍을 이루는 관계를 가집니다.
아래로 내리면 다음 페이지를 가져오는 역할을 합니다.

VM에 페이징, 페이지 로드 기능 구현하기
Future<void> nextList() async {
PostListModel model = state!;
if (model.isLast) {
await Future.delayed(Duration(milliseconds: 500));
refreshCtrl.loadComplete();
return;
}
// 마지막 페이지가 아닐 시
Map<String, dynamic> responseBody =
await postRepo.findAll(page: state!.pageNumber + 1);
if (!responseBody["success"]) {
ScaffoldMessenger.of(mContext!).showSnackBar(
SnackBar(content: Text("게시글 로드 실패 : ${responseBody["errorMessage"]}")),
);
return;
}
PostListModel nextModel = PostListModel.fromMap(responseBody["response"]);
PostListModel prevModel = state!;
// 이전 상태(prevModel) 다음에 nextModel을 추가한다.
state = nextModel.copyWith(posts: [...prevModel.posts, ...nextModel.posts]);
refreshCtrl.loadComplete();
}
먼저 PostListModel에 상태를 넣어줍니다.
만약 model의 상태에서 isLast가 true일 경우 >>
if (model.isLast)
loadComplete를 통해 더 이상 로드되지 않도록 해줍니다.
마지막 페이지가 아닐 때에는 통신을 통해서
(현재 상태에서 페이지 + 1) 을 해서 다음 페이지를 가져오게 해줍니다.
Map<String, dynamic> responseBody =
await postRepo.findAll(page: state!.pageNumber + 1);
통신이 완료가 되어 다음 페이지 데이터가 오게되면
다음 페이지 모델 nextModel 에 담아주고,
이전 상태의 페이지 모델을 prevModel에 넣어줍니다.
이전 상태 다음에 새로 가져온 페이지 모델을 추가 해 줍니다.
state = nextModel.copyWith(posts: [...prevModel.posts, ...nextModel.posts]);
그리고 loadComplete를 통해 로드를 중지 시켜 줍니다.
Share article