This repository has been archived on 2024-06-08. You can view files and clone it, but cannot push or open issues or pull requests.
SolarAgent/lib/widgets/notification.dart
2024-03-24 15:52:32 +08:00

95 lines
2.8 KiB
Dart

import 'package:flutter/material.dart';
import 'package:solaragent/models/notification.dart' as model;
import 'package:solaragent/auth.dart';
import 'package:url_launcher/url_launcher.dart';
class NotificationItem extends StatelessWidget {
final int index;
final model.Notification item;
final void Function()? onDismiss;
const NotificationItem(
{super.key, required this.index, required this.item, this.onDismiss});
bool hasLinks() => item.links != null && item.links!.isNotEmpty;
void showLinks(BuildContext context) {
if (!hasLinks()) return;
showModalBottomSheet<void>(
context: context,
builder: (BuildContext context) {
return ListView.builder(
padding: const EdgeInsets.all(8),
itemCount: item.links!.length,
itemBuilder: (BuildContext context, int index) {
var element = item.links![index];
return InkWell(
borderRadius: const BorderRadius.all(
Radius.circular(64),
),
onTap: () async {
await launchUrl(Uri.parse(element.url));
},
child: ListTile(title: Text(element.label)),
);
});
},
);
}
Future<void> markAsRead(model.Notification element) async {
if (authClient.client != null) {
var id = element.id;
var uri = Uri.parse('https://id.solsynth.dev/api/notifications/$id/read');
await authClient.client!.put(uri);
}
}
@override
Widget build(BuildContext context) {
return Dismissible(
key: Key('notification-$index'),
onDismissed: (direction) {
markAsRead(item).then((value) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: RichText(
text: TextSpan(children: [
TextSpan(
text: item.subject,
style: const TextStyle(fontWeight: FontWeight.bold),
),
const TextSpan(
text: " is marked as read",
)
]),
),
),
);
});
if (onDismiss != null) {
onDismiss!();
}
},
background: Container(
color: Colors.grey,
),
child: Container(
padding: const EdgeInsets.only(left: 10),
child: ListTile(
title: Text(item.subject),
subtitle: Text(item.content),
trailing: hasLinks()
? TextButton(
onPressed: () => showLinks(context),
style: TextButton.styleFrom(shape: const CircleBorder()),
child: const Icon(Icons.more_vert),
)
: null,
),
),
);
}
}