import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; import 'package:loris/business_logic/timeline/timeline.dart'; import '../business_logic/interactions/interactions.dart' as interactions; import 'package:loris/global.dart' as global; class InteractionButton extends StatefulWidget { const InteractionButton({required this.model, required this.type, Key? key}) : super(key: key); final interactions.InteractionType type; final PostModel model; @override State createState() => _InteractionButtonState(); } class _InteractionButtonState extends State { IconData icon = Icons.question_mark; String idkey = global.settings!.activeIdentity; bool active = false; bool busy = false; @override void initState() { switch (widget.type) { case interactions.InteractionType.favorite: active = widget.model.favourited; break; case interactions.InteractionType.reblog: active = widget.model.reblogged; break; } icon = active ? widget.type.revokeIcon : widget.type.icon; super.initState(); } Future sendRequest({ required String id, bool fromUrl = false, }) async { if (!busy) { busy = true; int status = fromUrl ? await interactions.makeFullInteraction( id, widget.model.originalId, widget.model.uri, widget.type, revoke: active, ) : await interactions.makeInteractionFromId( id, widget.model.originalId, widget.type, revoke: active, ); if (status == 200 && mounted) { setState(() { active = !active; icon = active ? widget.type.revokeIcon : widget.type.icon; }); } else { await showError(status); } busy = false; } } Future showError(int status) async { ScaffoldMessenger.of(context) .showSnackBar(SnackBar(content: Text("error: $status"))); setState(() { icon = Icons.dangerous; }); await Future.delayed(const Duration(seconds: 1)); setState(() { icon = active ? widget.type.revokeIcon : widget.type.icon; }); } @override Widget build(BuildContext context) { if (global.settings!.identities.length == 1) { return IconButton( onPressed: () async { await sendRequest(id: global.settings!.identities.keys.first); }, icon: Icon(icon), ); } // user is logged into multiple accounts List identityPickers = []; global.settings!.identities.forEach( (key, value) { identityPickers.add( PopupMenuItem( value: key, child: Text(key), ), ); }, ); return PopupMenuButton( onSelected: ((value) { if (mounted) { setState(() { idkey = value as String; }); } sendRequest( id: value as String, fromUrl: true, ); }), itemBuilder: (context) => identityPickers, initialValue: idkey, icon: Icon(icon), ); } }