Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: 해시태그 뷰 api, 페이지네이션 #49

Merged
merged 2 commits into from
Aug 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion lib/providers/hashtag_provider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ class Hashtag extends _$Hashtag {
state = const AsyncValue.loading();

state = await AsyncValue.guard(() async {
// await ItemRepository.instance.addItem(item: item);
var data = await fetchItem();
return [hashtag, ...data];
});
Expand Down
17 changes: 16 additions & 1 deletion lib/providers/hashtag_view_provider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,27 @@ class HashtagView extends _$HashtagView {
timer?.cancel();
});

var data = HashtagRepository.instance.getHashtagView();
var data = await HashtagRepository.instance.getHashtagView();
return data;
}

@override
Future<(List<ContentModel>, int)> build() async {
return fetchItem();
}

Future<(List<ContentModel>, int)> loadMoreData({
int? page,
int? size,
}) async {
state = const AsyncValue.loading();

state = await AsyncValue.guard(() async {
var data = await HashtagRepository.instance
.getHashtagView(page: page, size: size);
return data;
});

return state.value!;
}
}
24 changes: 20 additions & 4 deletions lib/repositories/hashtag_repository.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ import 'package:moa_app/repositories/token_repository.dart';
import 'package:moa_app/utils/api.dart';

abstract class IHashtagRepository {
Future<(List<ContentModel>, int)> getHashtagView();
Future<(List<ContentModel>, int)> getHashtagView({
int? page,
int? size,
});
Future<List<HashtagModel>> getHashtagList();
}

Expand All @@ -14,21 +17,34 @@ class HashtagRepository implements IHashtagRepository {
static HashtagRepository instance = const HashtagRepository._();

@override
Future<(List<ContentModel>, int)> getHashtagView() async {
Future<(List<ContentModel>, int)> getHashtagView({
int? page = 0,
int? size = 10,
}) async {
var token = await TokenRepository.instance.getToken();

var res = await dio.get(
'/api/v1/hashtag/view',
'/api/v1/hashtag/view?page=$page&size=$size',
options: Options(
headers: {
'Authorization': 'Bearer $token',
},
),
);

/// 백엔드 ContentModel 타입이 통일되지 않았으므로 임시로 타입 변환해서 넣어줌
return (
res.data['data']
.map<ContentModel>((e) => ContentModel.fromJson(e))
.map<ContentModel>(
(e) => ContentModel.fromJson({
'contentId': e['contentId'],
'contentImageUrl': e['imageUrl'],
'contentUrl': e['contentUrl'] ?? '',
'contentMemo': e['memo'],
'contentName': e['name'],
'contentHashTag': e['hashTags'],
}),
)
.toList() as List<ContentModel>,
res.data['count'] as int
);
Expand Down
39 changes: 28 additions & 11 deletions lib/screens/home/home.dart
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import 'package:moa_app/models/folder_model.dart';
import 'package:moa_app/models/user_model.dart';
import 'package:moa_app/providers/button_click_provider.dart';
import 'package:moa_app/providers/folder_view_provider.dart';
import 'package:moa_app/providers/hashtag_view_provider.dart';
import 'package:moa_app/repositories/hashtag_repository.dart';
import 'package:moa_app/repositories/user_repository.dart';
import 'package:moa_app/screens/home/tab_view/folder_tab_view.dart';
Expand All @@ -24,7 +25,7 @@ class Home extends HookConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
var folderAsync = ref.watch(folderViewProvider.notifier);
// var hashtagAsync = ref.watch(hashtagViewProvider.notifier);
var hashtagAsync = ref.watch(hashtagViewProvider.notifier);
var isClick = ref.watch(buttonClickStateProvider);
var tabIdx = useState(0);
TabController tabController = useTabController(initialLength: 2);
Expand Down Expand Up @@ -117,7 +118,7 @@ class Home extends HookConsumerWidget {
contentCount: contentCount,
),
TabViewItem(
futureList: Future.value([]),
futureList: hashtagAsync,
uniqueKey: const Key('hashtagTab'),
folderCount: folderCount,
contentCount: contentCount,
Expand Down Expand Up @@ -318,18 +319,22 @@ class FolderSource extends LoadingMoreBase<FolderModel> {
}

class HashtagSource extends LoadingMoreBase<ContentModel> {
HashtagSource({required this.contentCount});
HashtagSource({required this.contentCount, required this.futureList});
final ValueNotifier<int> contentCount;
final HashtagView futureList;
int pageIndex = 1;
int size = 10;
bool _hasMore = true;
bool forceRefresh = false;

var contentList = <ContentModel>[];
@override
bool get hasMore => (_hasMore && length < 30) || forceRefresh;
bool get hasMore => _hasMore || forceRefresh;

@override
Future<bool> refresh([bool notifyStateChanged = false]) async {
_hasMore = true;
pageIndex = 1;
pageIndex = 0;
//force to refresh list when you don't want clear list before request
//for the case, if your list already has 20 items.
forceRefresh = !notifyStateChanged;
Expand All @@ -343,14 +348,25 @@ class HashtagSource extends LoadingMoreBase<ContentModel> {
bool isSuccess = false;

try {
var (list, count) = await HashtagRepository.instance.getHashtagView();
contentCount.value = count;
for (ContentModel content in list) {
if (pageIndex == 0) {
var (initialList, count) = await futureList.future;
// 최초렌더시 컨텐츠 전체 개수 가져오기
contentCount.value = count;

contentList.addAll(initialList);
} else {
var (list, _) = await HashtagRepository.instance
.getHashtagView(page: pageIndex, size: size);
contentList.addAll(list);
_hasMore = list.length >= 10;
}

for (ContentModel content in contentList) {
if (!contains(content) && _hasMore) {
add(content);
}
}
_hasMore = false;

pageIndex++;
isSuccess = true;
} catch (e) {
Expand All @@ -371,7 +387,7 @@ class TabViewItem extends StatefulWidget {
required this.contentCount,
});
final Key uniqueKey;
final Future<List<FolderModel>> futureList;
final dynamic futureList;
final ValueNotifier<int> folderCount;
final ValueNotifier<int> contentCount;

Expand All @@ -382,10 +398,11 @@ class TabViewItem extends StatefulWidget {
class TabViewItemState extends State<TabViewItem>
with AutomaticKeepAliveClientMixin {
late final FolderSource folderSource = FolderSource(
futureList: widget.futureList,
futureList: widget.futureList as Future<List<FolderModel>>,
folderCount: widget.folderCount,
);
late final HashtagSource hashtagSource = HashtagSource(
futureList: widget.futureList as HashtagView,
contentCount: widget.contentCount,
);

Expand Down
49 changes: 32 additions & 17 deletions lib/screens/home/tab_view/hashtag_tab_view.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@ import 'package:loading_more_list/loading_more_list.dart';
import 'package:moa_app/constants/app_constants.dart';
import 'package:moa_app/constants/file_constants.dart';
import 'package:moa_app/models/content_model.dart';
import 'package:moa_app/screens/home/content_view.dart';
import 'package:moa_app/screens/home/home.dart';
import 'package:moa_app/screens/home/widgets/hashtag_card.dart';
import 'package:moa_app/screens/home/widgets/content_card.dart';
import 'package:moa_app/screens/home/widgets/type_header.dart';
import 'package:moa_app/utils/router_provider.dart';
import 'package:moa_app/utils/utils.dart';
import 'package:moa_app/widgets/button.dart';
import 'package:moa_app/widgets/edit_text.dart';
import 'package:moa_app/widgets/loading_indicator.dart';
Expand All @@ -32,6 +34,7 @@ class HashtagTabView extends HookWidget {
void goContentView(String contentId) {
context.go(
'${GoRoutes.content.fullPath}/$contentId',
extra: ContentView(id: contentId, folderName: 'folderName'),
);
}

Expand Down Expand Up @@ -74,15 +77,18 @@ class HashtagTabView extends HookWidget {
uniqueKey: uniqueKey,
child: RefreshIndicator(
onRefresh: () {
// return source.refresh(true);
return Future.delayed(
const Duration(seconds: 2),
() {
source.refresh(false);
},
);
return source.refresh(true);
},
child: LoadingMoreList<ContentModel>(
onScrollNotification: (notification) {
if (notification is ScrollEndNotification) {
if (notification.metrics.pixels ==
notification.metrics.maxScrollExtent) {
source.loadMore();
}
}
return false;
},
ListConfig<ContentModel>(
addRepaintBoundaries: true,
padding: const EdgeInsets.only(
Expand All @@ -94,7 +100,6 @@ class HashtagTabView extends HookWidget {
extendedListDelegate:
SliverWaterfallFlowDelegateWithFixedCrossAxisCount(
crossAxisCount: width > Breakpoints.md ? 3 : 2,
// crossAxisCount: 2,
mainAxisSpacing: 20.0,
crossAxisSpacing: 12.0,
),
Expand All @@ -107,14 +112,24 @@ class HashtagTabView extends HookWidget {
return const SizedBox();
},
itemBuilder: (c, item, index) {
// todo image width, height 계선해서 aspectRatio 주기
return AspectRatio(
aspectRatio: 0.7,
child: ContentCard(
onPressContent: () => goContentView('5'),
content: item,
onPressHashtag: (tag) => goHashtagDetailView(tag),
),
return FutureBuilder(
future: getImageSize(imageURL: item.contentImageUrl),
builder: (context, snapshot) {
var rate = snapshot.data?.toDouble() ?? 1.4;

return AspectRatio(
aspectRatio: rate == 1.9
? 0.6
: rate == 1.2
? 0.95
: 0.7,
child: ContentCard(
onPressContent: () => goContentView(item.contentId),
content: item,
onPressHashtag: (tag) => goHashtagDetailView(tag),
),
);
},
);
},
),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,17 +30,19 @@ class ContentCard extends HookWidget {
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Container(
width: double.infinity,
decoration: BoxDecoration(
border: Border.all(color: AppColors.moaOpacity30),
borderRadius: BorderRadius.circular(10),
image: DecorationImage(
image: NetworkImage(content.contentImageUrl),
fit: BoxFit.contain,
),
),
),
child: content.contentImageUrl == ''
? const Text('이미지 없을 경우 모아 이미지로 대체')
: Container(
width: double.infinity,
decoration: BoxDecoration(
border: Border.all(color: AppColors.moaOpacity30),
borderRadius: BorderRadius.circular(10),
image: DecorationImage(
image: NetworkImage(content.contentImageUrl),
fit: BoxFit.contain,
),
),
),
),
const SizedBox(height: 10),
Text(
Expand Down
5 changes: 4 additions & 1 deletion lib/utils/utils.dart
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ Future<String> xFileToBase64(XFile xFile) async {
}

Future<num> getImageSize({required String imageURL}) async {
if (imageURL == '') {
return 1.4;
}
Image image = Image.network(imageURL);
Completer<ui.Image> completer = Completer<ui.Image>();
image.image.resolve(const ImageConfiguration()).addListener(
Expand All @@ -24,7 +27,7 @@ Future<num> getImageSize({required String imageURL}) async {
? 1.9
: imageRate < 1.2
? 1.2
: imageRate;
: 1.4;
}

bool isStringEncoded(String value) {
Expand Down
4 changes: 2 additions & 2 deletions lib/widgets/moa_widgets/dynamic_grid_list.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import 'package:go_router/go_router.dart';
import 'package:moa_app/constants/app_constants.dart';
import 'package:moa_app/models/content_model.dart';
import 'package:moa_app/screens/home/content_view.dart';
import 'package:moa_app/screens/home/widgets/hashtag_card.dart';
import 'package:moa_app/screens/home/widgets/content_card.dart';
import 'package:moa_app/utils/router_provider.dart';
import 'package:moa_app/utils/utils.dart';

Expand Down Expand Up @@ -35,7 +35,7 @@ class DynamicGridList extends HookWidget {
child: SingleChildScrollView(
padding: const EdgeInsets.only(bottom: kBottomNavigationBarHeight),
child: StaggeredGrid.count(
axisDirection: AxisDirection.down, // <----- Add this line
axisDirection: AxisDirection.down,
crossAxisCount: width > Breakpoints.md ? 3 : 2,
crossAxisSpacing: 10,
mainAxisSpacing: 20,
Expand Down
Loading