lemmur-app-android/lib/widgets/save_post_button.dart

57 lines
1.6 KiB
Dart
Raw Normal View History

2020-09-17 22:50:18 +02:00
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
2021-04-05 20:14:39 +02:00
import 'package:lemmy_api_client/v3.dart';
2020-09-17 22:50:18 +02:00
import '../hooks/delayed_loading.dart';
2020-09-18 15:55:23 +02:00
import '../hooks/logged_in_action.dart';
2020-09-17 22:50:18 +02:00
2020-09-18 15:49:36 +02:00
// TODO: sync this button between post and fullpost. the same with voting
2020-09-17 22:50:18 +02:00
class SavePostButton extends HookWidget {
final PostView post;
2021-01-03 18:21:56 +01:00
const SavePostButton(this.post);
2020-09-17 22:50:18 +02:00
@override
Widget build(BuildContext context) {
final isSaved = useState(post.saved);
2020-09-17 22:50:18 +02:00
final savedIcon = isSaved.value ? Icons.bookmark : Icons.bookmark_border;
2021-01-03 19:43:39 +01:00
final loading = useDelayedLoading();
final loggedInAction = useLoggedInAction(post.instanceHost);
2020-09-17 22:50:18 +02:00
2020-09-18 15:49:36 +02:00
savePost(Jwt token) async {
2021-04-05 20:14:39 +02:00
final api = LemmyApiV3(post.instanceHost);
2020-09-17 22:50:18 +02:00
loading.start();
try {
2021-01-24 20:01:55 +01:00
final res = await api.run(SavePost(
postId: post.post.id, save: !isSaved.value, auth: token.raw));
2020-09-17 22:50:18 +02:00
isSaved.value = res.saved;
2020-09-18 15:55:39 +02:00
// ignore: avoid_catches_without_on_clauses
2020-09-17 22:50:18 +02:00
} catch (e) {
2021-03-10 08:34:30 +01:00
ScaffoldMessenger.of(context)
2021-01-03 19:43:39 +01:00
.showSnackBar(const SnackBar(content: Text('saving failed :(')));
2020-09-17 22:50:18 +02:00
}
loading.cancel();
}
2020-09-18 01:29:17 +02:00
if (loading.loading) {
return Padding(
2020-09-18 15:49:36 +02:00
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 5),
2020-09-18 01:29:17 +02:00
child: SizedBox(
width: 30,
height: 30,
child: CircularProgressIndicator(
backgroundColor: Theme.of(context).iconTheme.color,
)),
);
}
2020-09-17 22:50:18 +02:00
2020-09-18 01:29:17 +02:00
return IconButton(
2020-09-18 12:48:32 +02:00
tooltip: 'Save post',
icon: Icon(savedIcon),
2020-09-18 15:49:36 +02:00
onPressed: loggedInAction(loading.pending ? (_) {} : savePost),
2020-09-18 12:48:32 +02:00
);
2020-09-17 22:50:18 +02:00
}
}