♻️ Refactor riverpod pagination loading
This commit is contained in:
@ -141,6 +141,16 @@ class AccountScreen extends HookConsumerWidget {
|
||||
context.router.push(ManagedPublisherRoute());
|
||||
},
|
||||
),
|
||||
ListTile(
|
||||
minTileHeight: 48,
|
||||
leading: const Icon(Symbols.wallet),
|
||||
trailing: const Icon(Symbols.chevron_right),
|
||||
contentPadding: EdgeInsets.symmetric(horizontal: 24),
|
||||
title: Text('wallet').tr(),
|
||||
onTap: () {
|
||||
context.router.push(WalletRoute());
|
||||
},
|
||||
),
|
||||
ListTile(
|
||||
minTileHeight: 48,
|
||||
leading: const Icon(Symbols.edit),
|
||||
|
@ -199,7 +199,10 @@ class EditPublisherScreen extends HookConsumerWidget {
|
||||
CropAspectRatio(height: 1, width: 1),
|
||||
],
|
||||
);
|
||||
if (result == null) return;
|
||||
if (result == null) {
|
||||
if (context.mounted) hideLoadingModal(context);
|
||||
return;
|
||||
}
|
||||
if (!context.mounted) return;
|
||||
showLoadingModal(context);
|
||||
|
||||
|
@ -30,7 +30,10 @@ class UpdateProfileScreen extends HookConsumerWidget {
|
||||
var result = await ref
|
||||
.read(imagePickerProvider)
|
||||
.pickImage(source: ImageSource.gallery);
|
||||
if (result == null) return;
|
||||
if (result == null) {
|
||||
if (context.mounted) hideLoadingModal(context);
|
||||
return;
|
||||
}
|
||||
if (!context.mounted) return;
|
||||
hideLoadingModal(context);
|
||||
result = await cropImage(
|
||||
|
@ -265,7 +265,10 @@ class EditChatScreen extends HookConsumerWidget {
|
||||
CropAspectRatio(height: 1, width: 1),
|
||||
],
|
||||
);
|
||||
if (result == null) return;
|
||||
if (result == null) {
|
||||
if (context.mounted) hideLoadingModal(context);
|
||||
return;
|
||||
}
|
||||
if (!context.mounted) return;
|
||||
showLoadingModal(context);
|
||||
|
||||
|
@ -12,10 +12,12 @@ import 'package:island/models/post.dart';
|
||||
import 'package:island/widgets/check_in.dart';
|
||||
import 'package:island/widgets/post/post_item.dart';
|
||||
import 'package:material_symbols_icons/symbols.dart';
|
||||
import 'package:very_good_infinite_list/very_good_infinite_list.dart';
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'package:riverpod_paging_utils/riverpod_paging_utils.dart';
|
||||
import 'package:island/pods/network.dart';
|
||||
|
||||
part 'explore.g.dart';
|
||||
|
||||
@RoutePage()
|
||||
class ExploreScreen extends ConsumerWidget {
|
||||
const ExploreScreen({super.key});
|
||||
@ -23,8 +25,7 @@ class ExploreScreen extends ConsumerWidget {
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final user = ref.watch(userInfoProvider);
|
||||
final posts = ref.watch(activityListProvider);
|
||||
final postsNotifier = ref.watch(activityListProvider.notifier);
|
||||
final activitiesNotifier = ref.watch(activityListNotifierProvider.notifier);
|
||||
|
||||
return AppScaffold(
|
||||
appBar: AppBar(title: const Text('explore').tr()),
|
||||
@ -33,7 +34,7 @@ class ExploreScreen extends ConsumerWidget {
|
||||
onPressed: () {
|
||||
context.router.push(PostComposeRoute()).then((value) {
|
||||
if (value != null) {
|
||||
ref.invalidate(activityListProvider);
|
||||
activitiesNotifier.forceRefresh();
|
||||
}
|
||||
});
|
||||
},
|
||||
@ -41,108 +42,110 @@ class ExploreScreen extends ConsumerWidget {
|
||||
),
|
||||
floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
|
||||
body: RefreshIndicator(
|
||||
onRefresh: () => postsNotifier.refresh(),
|
||||
child: CustomScrollView(
|
||||
slivers: [
|
||||
if (user.hasValue) SliverToBoxAdapter(child: CheckInWidget()),
|
||||
SliverInfiniteList(
|
||||
itemCount: posts.length,
|
||||
isLoading: postsNotifier.isLoading,
|
||||
hasReachedMax: postsNotifier.hasReachedMax,
|
||||
onFetchData: postsNotifier.fetchMore,
|
||||
itemBuilder: (context, index) {
|
||||
final item = posts[index];
|
||||
switch (item.type) {
|
||||
case 'posts.new':
|
||||
return PostItem(
|
||||
item: SnPost.fromJson(item.data),
|
||||
onRefresh: (_) {
|
||||
ref.invalidate(activityListProvider);
|
||||
},
|
||||
onUpdate: (post) {
|
||||
postsNotifier.updateOne(
|
||||
index,
|
||||
item.copyWith(data: post.toJson()),
|
||||
);
|
||||
},
|
||||
);
|
||||
case 'accounts.check-in':
|
||||
return CheckInActivityWidget(item: item);
|
||||
case 'accounts.status':
|
||||
return StatusActivityWidget(item: item);
|
||||
default:
|
||||
return Placeholder();
|
||||
}
|
||||
},
|
||||
separatorBuilder: (_, __) => const Divider(height: 1),
|
||||
),
|
||||
SliverGap(MediaQuery.of(context).padding.bottom + 16),
|
||||
],
|
||||
onRefresh: () => Future.sync(activitiesNotifier.forceRefresh),
|
||||
child: PagingHelperView(
|
||||
provider: activityListNotifierProvider,
|
||||
futureRefreshable: activityListNotifierProvider.future,
|
||||
notifierRefreshable: activityListNotifierProvider.notifier,
|
||||
contentBuilder:
|
||||
(data, widgetCount, endItemView) => CustomScrollView(
|
||||
slivers: [
|
||||
if (user.hasValue) SliverToBoxAdapter(child: CheckInWidget()),
|
||||
SliverList.builder(
|
||||
itemCount: widgetCount,
|
||||
itemBuilder: (context, index) {
|
||||
if (index == widgetCount - 1) {
|
||||
return endItemView;
|
||||
}
|
||||
|
||||
final item = data.items[index];
|
||||
Widget itemWidget;
|
||||
|
||||
switch (item.type) {
|
||||
case 'posts.new':
|
||||
itemWidget = PostItem(
|
||||
item: SnPost.fromJson(item.data),
|
||||
onRefresh: (_) {
|
||||
activitiesNotifier.forceRefresh();
|
||||
},
|
||||
onUpdate: (post) {
|
||||
activitiesNotifier.updateOne(
|
||||
index,
|
||||
item.copyWith(data: post.toJson()),
|
||||
);
|
||||
},
|
||||
);
|
||||
break;
|
||||
case 'accounts.check-in':
|
||||
itemWidget = CheckInActivityWidget(item: item);
|
||||
break;
|
||||
case 'accounts.status':
|
||||
itemWidget = StatusActivityWidget(item: item);
|
||||
break;
|
||||
default:
|
||||
itemWidget = const Placeholder();
|
||||
}
|
||||
|
||||
return Column(
|
||||
children: [itemWidget, const Divider(height: 1)],
|
||||
);
|
||||
},
|
||||
),
|
||||
SliverGap(MediaQuery.of(context).padding.bottom + 16),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
final activityListProvider =
|
||||
StateNotifierProvider<_ActivityListController, List<SnActivity>>((ref) {
|
||||
final client = ref.watch(apiClientProvider);
|
||||
return _ActivityListController(client);
|
||||
});
|
||||
@riverpod
|
||||
class ActivityListNotifier extends _$ActivityListNotifier
|
||||
with CursorPagingNotifierMixin<SnActivity> {
|
||||
@override
|
||||
Future<CursorPagingData<SnActivity>> build() => fetch(cursor: null);
|
||||
|
||||
class _ActivityListController extends StateNotifier<List<SnActivity>> {
|
||||
_ActivityListController(this._dio) : super([]);
|
||||
@override
|
||||
Future<CursorPagingData<SnActivity>> fetch({required String? cursor}) async {
|
||||
final client = ref.read(apiClientProvider);
|
||||
final offset = cursor == null ? 0 : int.parse(cursor);
|
||||
final take = 20;
|
||||
|
||||
final Dio _dio;
|
||||
bool isLoading = false;
|
||||
bool hasReachedMax = false;
|
||||
int offset = 0;
|
||||
final int take = 20;
|
||||
int total = 0;
|
||||
final response = await client.get(
|
||||
'/activities',
|
||||
queryParameters: {'offset': offset, 'take': take},
|
||||
);
|
||||
|
||||
Future<void> fetchMore() async {
|
||||
if (isLoading || hasReachedMax) return;
|
||||
isLoading = true;
|
||||
final List<SnActivity> items =
|
||||
(response.data as List)
|
||||
.map((e) => SnActivity.fromJson(e as Map<String, dynamic>))
|
||||
.toList();
|
||||
|
||||
try {
|
||||
final response = await _dio.get(
|
||||
'/activities',
|
||||
queryParameters: {'offset': offset, 'take': take},
|
||||
);
|
||||
final total = int.tryParse(response.headers['x-total']?.first ?? '') ?? 0;
|
||||
final hasMore = offset + items.length < total;
|
||||
final nextCursor = hasMore ? (offset + items.length).toString() : null;
|
||||
|
||||
final List<SnActivity> fetched =
|
||||
(response.data as List)
|
||||
.map((e) => SnActivity.fromJson(e as Map<String, dynamic>))
|
||||
.toList();
|
||||
|
||||
final headerTotal = int.tryParse(
|
||||
response.headers['x-total']?.first ?? '',
|
||||
);
|
||||
if (headerTotal != null) total = headerTotal;
|
||||
|
||||
if (!mounted) return; // Check if the notifier is still mounted
|
||||
|
||||
state = [...state, ...fetched];
|
||||
offset += fetched.length;
|
||||
if (state.length >= total) hasReachedMax = true;
|
||||
} finally {
|
||||
if (mounted) {
|
||||
isLoading = false;
|
||||
}
|
||||
}
|
||||
return CursorPagingData(
|
||||
items: items,
|
||||
hasMore: hasMore,
|
||||
nextCursor: nextCursor,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> refresh() async {
|
||||
offset = 0;
|
||||
state = [];
|
||||
hasReachedMax = false;
|
||||
await fetchMore();
|
||||
}
|
||||
void updateOne(int index, SnActivity activity) {
|
||||
final currentState = state.valueOrNull;
|
||||
if (currentState == null) return;
|
||||
|
||||
void updateOne(int index, SnActivity post) {
|
||||
if (!mounted) return; // Check if the notifier is still mounted
|
||||
final updatedPosts = [...state];
|
||||
updatedPosts[index] = post;
|
||||
state = updatedPosts;
|
||||
final updatedItems = [...currentState.items];
|
||||
updatedItems[index] = activity;
|
||||
|
||||
state = AsyncData(
|
||||
CursorPagingData(
|
||||
items: updatedItems,
|
||||
hasMore: currentState.hasMore,
|
||||
nextCursor: currentState.nextCursor,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
31
lib/screens/explore.g.dart
Normal file
31
lib/screens/explore.g.dart
Normal file
@ -0,0 +1,31 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'explore.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
String _$activityListNotifierHash() =>
|
||||
r'8a67d302e828408c7c4cf724d84c2c5958f2dc7e';
|
||||
|
||||
/// See also [ActivityListNotifier].
|
||||
@ProviderFor(ActivityListNotifier)
|
||||
final activityListNotifierProvider = AutoDisposeAsyncNotifierProvider<
|
||||
ActivityListNotifier,
|
||||
CursorPagingData<SnActivity>
|
||||
>.internal(
|
||||
ActivityListNotifier.new,
|
||||
name: r'activityListNotifierProvider',
|
||||
debugGetCreateSourceHash:
|
||||
const bool.fromEnvironment('dart.vm.product')
|
||||
? null
|
||||
: _$activityListNotifierHash,
|
||||
dependencies: null,
|
||||
allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
typedef _$ActivityListNotifier =
|
||||
AutoDisposeAsyncNotifier<CursorPagingData<SnActivity>>;
|
||||
// ignore_for_file: type=lint
|
||||
// ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member, invalid_use_of_visible_for_testing_member, deprecated_member_use_from_same_package
|
@ -29,7 +29,7 @@ Future<SnPublisher> publisher(Ref ref, String uname) async {
|
||||
@riverpod
|
||||
Future<List<SnAccountBadge>> publisherBadges(Ref ref, String pubName) async {
|
||||
final pub = await ref.watch(publisherProvider(pubName).future);
|
||||
if (pub.publisherType != 0) return [];
|
||||
if (pub.type != 0) return [];
|
||||
final apiClient = ref.watch(apiClientProvider);
|
||||
final resp = await apiClient.get("/accounts/${pub.name}/badges");
|
||||
return List<SnAccountBadge>.from(
|
||||
@ -177,7 +177,7 @@ class PublisherProfileScreen extends HookConsumerWidget {
|
||||
).fontSize(14).opacity(0.85),
|
||||
],
|
||||
),
|
||||
if (data.publisherType == 0)
|
||||
if (data.type == 0)
|
||||
AccountStatusWidget(
|
||||
uname: name,
|
||||
padding: EdgeInsets.zero,
|
||||
|
@ -145,7 +145,7 @@ class _PublisherProviderElement
|
||||
String get uname => (origin as PublisherProvider).uname;
|
||||
}
|
||||
|
||||
String _$publisherBadgesHash() => r'69a5bbc9e1528da65ae8b1e5e6c4f57c3dcf4071';
|
||||
String _$publisherBadgesHash() => r'b26d8804ddc9734c453bdf76af0a9336f166542c';
|
||||
|
||||
/// See also [publisherBadges].
|
||||
@ProviderFor(publisherBadges)
|
||||
|
@ -163,7 +163,10 @@ class EditRealmScreen extends HookConsumerWidget {
|
||||
var result = await ref
|
||||
.read(imagePickerProvider)
|
||||
.pickImage(source: ImageSource.gallery);
|
||||
if (result == null) return;
|
||||
if (result == null) {
|
||||
if (context.mounted) hideLoadingModal(context);
|
||||
return;
|
||||
}
|
||||
if (!context.mounted) return;
|
||||
hideLoadingModal(context);
|
||||
result = await cropImage(
|
||||
|
69
lib/screens/wallet.dart
Normal file
69
lib/screens/wallet.dart
Normal file
@ -0,0 +1,69 @@
|
||||
import 'package:auto_route/annotations.dart';
|
||||
import 'package:easy_localization/easy_localization.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:island/models/wallet.dart';
|
||||
import 'package:island/pods/network.dart';
|
||||
import 'package:island/widgets/app_scaffold.dart';
|
||||
import 'package:material_symbols_icons/symbols.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'package:styled_widget/styled_widget.dart';
|
||||
|
||||
part 'wallet.g.dart';
|
||||
|
||||
@riverpod
|
||||
Future<SnWallet> walletCurrent(Ref ref) async {
|
||||
final apiClient = ref.watch(apiClientProvider);
|
||||
final resp = await apiClient.get('/wallets');
|
||||
return SnWallet.fromJson(resp.data);
|
||||
}
|
||||
|
||||
const Map<String, IconData> kCurrencyIconData = {
|
||||
'points': Symbols.toll,
|
||||
'golds': Symbols.attach_money,
|
||||
};
|
||||
|
||||
@RoutePage()
|
||||
class WalletScreen extends HookConsumerWidget {
|
||||
const WalletScreen({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final wallet = ref.watch(walletCurrentProvider);
|
||||
|
||||
String getCurrencyTranslationKey(String currency, {bool isShort = false}) {
|
||||
return 'walletCurrency${isShort ? 'Short' : ''}${currency[0].toUpperCase()}${currency.substring(1).toLowerCase()}';
|
||||
}
|
||||
|
||||
return AppScaffold(
|
||||
appBar: AppBar(title: Text('wallet').tr()),
|
||||
body: wallet.when(
|
||||
data: (data) {
|
||||
return Column(
|
||||
spacing: 8,
|
||||
children: [
|
||||
...data.pockets.map(
|
||||
(pocket) => Card(
|
||||
margin: EdgeInsets.zero,
|
||||
child: ListTile(
|
||||
leading: Icon(
|
||||
kCurrencyIconData[pocket.currency] ??
|
||||
Symbols.universal_currency_alt,
|
||||
),
|
||||
title:
|
||||
Text(getCurrencyTranslationKey(pocket.currency)).tr(),
|
||||
subtitle: Text(
|
||||
'${pocket.amount.toStringAsFixed(2)} ${getCurrencyTranslationKey(pocket.currency, isShort: true).tr()}',
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
).padding(horizontal: 16, vertical: 16);
|
||||
},
|
||||
error: (error, stackTrace) => Center(child: Text('Error: $error')),
|
||||
loading: () => const Center(child: CircularProgressIndicator()),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
28
lib/screens/wallet.g.dart
Normal file
28
lib/screens/wallet.g.dart
Normal file
@ -0,0 +1,28 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'wallet.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
String _$walletCurrentHash() => r'9123af148c4a27e079bbe90c7d4e41d08e408a39';
|
||||
|
||||
/// See also [walletCurrent].
|
||||
@ProviderFor(walletCurrent)
|
||||
final walletCurrentProvider = AutoDisposeFutureProvider<SnWallet>.internal(
|
||||
walletCurrent,
|
||||
name: r'walletCurrentProvider',
|
||||
debugGetCreateSourceHash:
|
||||
const bool.fromEnvironment('dart.vm.product')
|
||||
? null
|
||||
: _$walletCurrentHash,
|
||||
dependencies: null,
|
||||
allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@Deprecated('Will be removed in 3.0. Use Ref instead')
|
||||
// ignore: unused_element
|
||||
typedef WalletCurrentRef = AutoDisposeFutureProviderRef<SnWallet>;
|
||||
// ignore_for_file: type=lint
|
||||
// ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member, invalid_use_of_visible_for_testing_member, deprecated_member_use_from_same_package
|
Reference in New Issue
Block a user