fix performance issues

This commit is contained in:
otsmr 2026-07-15 13:25:16 +02:00
parent 9a579e818c
commit aeea5c9c8b
12 changed files with 438 additions and 326 deletions

File diff suppressed because one or more lines are too long

View file

@ -98,6 +98,7 @@ class _FlameCounterWidgetState extends State<FlameCounterWidget> {
height: 11,
child: EmojiAnimationComp(
emoji: '',
repeat: false,
),
),
],

View file

@ -22,15 +22,14 @@ class _MediaViewSizingHelperState extends State<MediaViewSizingHelper> {
@override
Widget build(BuildContext context) {
var needToDownSizeImage = false;
var availableHeight = MediaQuery.of(context).size.height;
// Get the screen size and safe area padding
final screenSize = MediaQuery.of(context).size;
final safeAreaPadding = MediaQuery.of(context).padding;
// Use narrow MediaQuery selectors to avoid rebuilding on keyboard inset changes
final screenSize = MediaQuery.sizeOf(context);
final safeAreaPadding = MediaQuery.paddingOf(context);
// Calculate the available width and height
final availableWidth = screenSize.width;
availableHeight =
final availableHeight =
screenSize.height -
safeAreaPadding.top -
safeAreaPadding.bottom -

View file

@ -38,7 +38,7 @@ class _ChatListViewState extends State<ChatListView> with AutomaticKeepAliveClie
List<Group> _groupsPinned = [];
List<Group> _groupsArchived = [];
bool _hasContacts = false;
final ValueNotifier<bool> _hasContacts = ValueNotifier(false);
bool _loading = true;
bool get _hasOpenGroup =>
_groupsNotPinned.isNotEmpty ||
@ -50,6 +50,7 @@ class _ChatListViewState extends State<ChatListView> with AutomaticKeepAliveClie
int _countContactRequest = 0;
int _countAnnouncedUsers = 0;
final ValueNotifier<int> _badgeCount = ValueNotifier(0);
late StreamSubscription<int?> _countContactRequestStream;
late StreamSubscription<int?> _countAnnouncedStream;
@ -80,9 +81,7 @@ class _ChatListViewState extends State<ChatListView> with AutomaticKeepAliveClie
contacts,
) {
if (!mounted) return;
setState(() {
_hasContacts = contacts.isNotEmpty;
});
_hasContacts.value = contacts.isNotEmpty;
});
_countContactRequestStream = twonlyDB.contactsDao
@ -90,9 +89,8 @@ class _ChatListViewState extends State<ChatListView> with AutomaticKeepAliveClie
.listen((update) {
if (update != null) {
if (!mounted) return;
setState(() {
_countContactRequest = update;
});
_badgeCount.value = _countAnnouncedUsers + _countContactRequest;
}
});
@ -100,9 +98,8 @@ class _ChatListViewState extends State<ChatListView> with AutomaticKeepAliveClie
.watchNewAnnouncementsWithDataCount()
.listen((update) {
if (!mounted) return;
setState(() {
_countAnnouncedUsers = update;
});
_badgeCount.value = _countAnnouncedUsers + _countContactRequest;
});
_precacheSub = twonlyDB.messagesDao.watchUnopenedMediaFiles().listen((mediaFiles) {
@ -141,7 +138,10 @@ class _ChatListViewState extends State<ChatListView> with AutomaticKeepAliveClie
@override
Widget build(BuildContext context) {
super.build(context);
final plan = context.watch<PurchasesProvider>().plan;
final plan = context.select<PurchasesProvider, SubscriptionPlan>(
(p) => p.plan,
);
final dark = isDarkMode(context);
return Scaffold(
appBar: AppBar(
title: Row(
@ -175,7 +175,7 @@ class _ChatListViewState extends State<ChatListView> with AutomaticKeepAliveClie
style: TextStyle(
fontSize: 10,
fontWeight: FontWeight.bold,
color: isDarkMode(context) ? Colors.black : Colors.white,
color: dark ? Colors.black : Colors.white,
),
),
),
@ -184,9 +184,12 @@ class _ChatListViewState extends State<ChatListView> with AutomaticKeepAliveClie
),
actions: [
const FeedbackIconButtonComp(),
Stack(
ValueListenableBuilder<int>(
valueListenable: _badgeCount,
builder: (context, badgeCount, child) {
return Stack(
children: [
if (_countAnnouncedUsers + _countContactRequest > 0)
if (badgeCount > 0)
Positioned.fill(
child: Center(
child: Container(
@ -201,16 +204,11 @@ class _ChatListViewState extends State<ChatListView> with AutomaticKeepAliveClie
),
Center(
child: NotificationBadgeComp(
backgroundColor: isDarkMode(context)
? Colors.white
: Colors.black,
textColor: isDarkMode(context) ? Colors.black : Colors.white,
count: (_countAnnouncedUsers + _countContactRequest)
.toString(),
backgroundColor: dark ? Colors.white : Colors.black,
textColor: dark ? Colors.black : Colors.white,
count: badgeCount.toString(),
child: IconButton(
color: (_countAnnouncedUsers + _countContactRequest > 0)
? Colors.black
: null,
color: badgeCount > 0 ? Colors.black : null,
key: searchForOtherUsers,
icon: const FaIcon(FontAwesomeIcons.userPlus, size: 18),
onPressed: () => context.push(Routes.chatsAddNewUser),
@ -218,6 +216,8 @@ class _ChatListViewState extends State<ChatListView> with AutomaticKeepAliveClie
),
),
],
);
},
),
IconButton(
@ -303,9 +303,11 @@ class _ChatListViewState extends State<ChatListView> with AutomaticKeepAliveClie
),
),
floatingActionButtonAnimator: FloatingActionButtonAnimator.noAnimation,
floatingActionButton: !_hasContacts
? null
: Padding(
floatingActionButton: ValueListenableBuilder<bool>(
valueListenable: _hasContacts,
builder: (context, hasContacts, child) {
if (!hasContacts) return const SizedBox.shrink();
return Padding(
padding: const EdgeInsets.only(bottom: 30),
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
@ -313,18 +315,12 @@ class _ChatListViewState extends State<ChatListView> with AutomaticKeepAliveClie
FloatingActionButton(
heroTag: 'qrcode_fab',
elevation: 2,
backgroundColor: isDarkMode(context)
? Colors.grey[800]
: Colors.grey[200],
foregroundColor: isDarkMode(context)
? Colors.white
: Colors.black87,
backgroundColor: dark ? Colors.grey[800] : Colors.grey[200],
foregroundColor: dark ? Colors.white : Colors.black87,
onPressed: () => context.push(Routes.settingsPublicProfile),
child: FaIcon(
FontAwesomeIcons.qrcode,
color: isDarkMode(context)
? Colors.white
: Colors.black87,
color: dark ? Colors.white : Colors.black87,
),
),
const SizedBox(height: 12),
@ -341,6 +337,8 @@ class _ChatListViewState extends State<ChatListView> with AutomaticKeepAliveClie
),
],
),
);
},
),
);
}

View file

@ -174,20 +174,24 @@ class _UserListItem extends State<GroupListItemComp> {
/// Fetches any media files referenced by preview messages but not yet in the
/// local cache. Fire-and-forget; updates state when results arrive.
Future<void> _fetchMissingMediaFiles() async {
final missing = <MediaFile>[];
for (final message in _previewMessages) {
if (message.mediaId != null &&
!_previewMediaFiles.any((t) => t.mediaId == message.mediaId)) {
final mediaFile = await twonlyDB.mediaFilesDao.getMediaFileById(
message.mediaId!,
);
if (mediaFile != null && mounted) {
if (mediaFile != null) {
missing.add(mediaFile);
}
}
}
if (missing.isNotEmpty && mounted) {
setState(() {
_previewMediaFiles.add(mediaFile);
_previewMediaFiles.addAll(missing);
});
}
}
}
}
Future<void> onTap() async {
if (_currentMessage == null && widget.group.totalMediaCounter == 0) {

View file

@ -26,11 +26,6 @@ class _LastMessageTimeCompState extends State<LastMessageTimeComp> {
void initState() {
super.initState();
_loadTargetTime();
updateTime = Timer.periodic(
const Duration(milliseconds: 500),
(_) => _updateSeconds(),
);
}
@override
@ -66,6 +61,16 @@ class _LastMessageTimeCompState extends State<LastMessageTimeComp> {
setState(() {
lastMessageInSeconds = seconds < 0 ? 0 : seconds;
});
var nextTickMs = 1000;
if (lastMessageInSeconds >= 120 && lastMessageInSeconds < 3600) {
nextTickMs = 30000;
} else if (lastMessageInSeconds >= 3600) {
nextTickMs = 60000;
}
updateTime?.cancel();
updateTime = Timer(Duration(milliseconds: nextTickMs), _updateSeconds);
}
@override

View file

@ -28,10 +28,6 @@ class _TypingIndicatorSubtitleCompState
void initState() {
super.initState();
_periodicUpdate = Timer.periodic(const Duration(seconds: 1), (_) {
filterOpenUsers(_groupMembers);
});
final membersStream = twonlyDB.groupsDao.watchGroupMembers(
widget.groupId,
);
@ -41,11 +37,22 @@ class _TypingIndicatorSubtitleCompState
}
void filterOpenUsers(List<GroupMember> input) {
if (mounted) {
setState(() {
_groupMembers = input.where(isTyping).toList();
if (!mounted) return;
final typingMembers = input.where(isTyping).toList();
if (typingMembers.isEmpty) {
_periodicUpdate?.cancel();
_periodicUpdate = null;
} else {
_periodicUpdate ??= Timer.periodic(const Duration(seconds: 1), (_) {
filterOpenUsers(_groupMembers);
});
}
setState(() {
_groupMembers = typingMembers;
});
}
@override

View file

@ -4,7 +4,6 @@ import 'dart:collection';
import 'package:clock/clock.dart';
import 'package:drift/drift.dart' show Value;
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:go_router/go_router.dart';
import 'package:mutex/mutex.dart';
import 'package:screen_protector/screen_protector.dart';
@ -24,13 +23,13 @@ import 'package:twonly/src/services/mediafiles/mediafile.service.dart';
import 'package:twonly/src/services/notifications/background.notifications.dart';
import 'package:twonly/src/utils/log.dart';
import 'package:twonly/src/utils/misc.dart';
import 'package:twonly/src/visual/components/animate_icon.comp.dart';
import 'package:twonly/src/visual/elements/my_icon_button.element.dart';
import 'package:twonly/src/visual/helpers/media_view_sizing.helper.dart';
import 'package:twonly/src/visual/loader/three_rotating_dots.loader.dart';
import 'package:twonly/src/visual/views/camera/camera_send_to.view.dart';
import 'package:twonly/src/visual/views/chats/media_viewer_components/additional_message_content.dart';
import 'package:twonly/src/visual/views/chats/media_viewer_components/keyboard_dismiss_observer.comp.dart';
import 'package:twonly/src/visual/views/chats/media_viewer_components/media_content_renderer.comp.dart';
import 'package:twonly/src/visual/views/chats/media_viewer_components/media_viewer_bottom_navigation.comp.dart';
import 'package:twonly/src/visual/views/chats/media_viewer_components/media_viewer_message_input.comp.dart';
import 'package:twonly/src/visual/views/chats/media_viewer_components/reaction_buttons.comp.dart';
import 'package:twonly/src/visual/views/chats/media_viewer_components/twonly_present_overlay.comp.dart';
@ -63,7 +62,6 @@ class _MediaViewerViewState extends State<MediaViewerView> {
DateTime? canBeSeenUntil;
final ValueNotifier<double> progress = ValueNotifier(0);
bool showSendTextMessageInput = false;
double maxBottomInset = 0;
DateTime? _lastTimeInputClosed;
final GlobalKey mediaWidgetKey = GlobalKey();
@ -505,7 +503,7 @@ class _MediaViewerViewState extends State<MediaViewerView> {
advanceToNextMediaOrExit();
}
});
progressTimer = Timer.periodic(const Duration(milliseconds: 10), (timer) {
progressTimer = Timer.periodic(const Duration(milliseconds: 16), (timer) {
final mediaFile = currentMedia?.mediaFile;
if (mediaFile == null) return;
if (mediaFile.displayLimitInMilliseconds == null ||
@ -562,54 +560,15 @@ class _MediaViewerViewState extends State<MediaViewerView> {
}
Widget bottomNavigation() {
return Row(
return MediaViewerBottomNavigationBar(
key: mediaWidgetKey,
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (currentMedia != null &&
currentMessage != null &&
!currentMedia!.mediaFile.requiresAuthentication &&
currentMedia!.mediaFile.displayLimitInMilliseconds == null)
MyIconButton(
variant: MyIconButtonVariant.secondary,
onPressed: (currentMedia == null || currentMessage == null)
? null
: onPressedSaveToGallery,
icon: imageSaving
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator.adaptive(strokeWidth: 2),
)
: imageSaved
? const Icon(Icons.check)
: const FaIcon(FontAwesomeIcons.floppyDisk, size: 20),
),
const SizedBox(width: 10),
IconButton(
icon: SizedBox(
width: 30,
height: 30,
child: GridView.count(
crossAxisCount: 2,
children: List.generate(
4,
(index) {
return SizedBox(
width: 8,
height: 8,
child: Center(
child: EmojiAnimationComp(
emoji: EmojiAnimationComp.animatedIcons.keys
.toList()[index],
),
),
);
},
),
),
),
onPressed: () {
currentMedia: currentMedia,
currentMessage: currentMessage,
imageSaving: imageSaving,
imageSaved: imageSaved,
showShortReactions: showShortReactions,
onSaveToGallery: onPressedSaveToGallery,
onToggleReactions: () {
if (!showShortReactions) {
displayShortReactions();
} else {
@ -618,29 +577,13 @@ class _MediaViewerViewState extends State<MediaViewerView> {
});
}
},
style: ButtonStyle(
padding: WidgetStateProperty.all<EdgeInsets>(
const EdgeInsets.symmetric(vertical: 10, horizontal: 20),
),
),
),
const SizedBox(width: 10),
MyIconButton(
variant: MyIconButtonVariant.secondary,
onPressed: () async {
onMessagePressed: () {
displayShortReactions();
setState(() {
showSendTextMessageInput = true;
});
},
icon: const FaIcon(
FontAwesomeIcons.message,
size: 20,
),
),
const SizedBox(width: 10),
MyIconButton(
onPressed: () async {
onCameraPressed: () async {
nextMediaTimer?.cancel();
progressTimer?.cancel();
await videoController?.pause();
@ -660,9 +603,6 @@ class _MediaViewerViewState extends State<MediaViewerView> {
await videoController?.play();
}
},
icon: const FaIcon(FontAwesomeIcons.camera, size: 24),
),
],
);
}
@ -717,25 +657,16 @@ class _MediaViewerViewState extends State<MediaViewerView> {
@override
Widget build(BuildContext context) {
final bottomInset = MediaQuery.of(context).viewInsets.bottom;
if (bottomInset > maxBottomInset) {
maxBottomInset = bottomInset;
} else if (bottomInset == 0 && maxBottomInset > 0) {
maxBottomInset = 0;
if (showSendTextMessageInput) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) {
return KeyboardDismissObserver(
showSendTextMessageInput: showSendTextMessageInput,
onKeyboardDismissed: () {
setState(() {
showSendTextMessageInput = false;
showShortReactions = false;
_lastTimeInputClosed = clock.now();
});
}
});
}
}
return Scaffold(
},
child: Scaffold(
body: SafeArea(
child: Stack(
fit: StackFit.expand,
@ -745,7 +676,9 @@ class _MediaViewerViewState extends State<MediaViewerView> {
(canBeSeenUntil == null || progress.value >= 0))
GestureDetector(
onTap: onScreenTapped,
onDoubleTap: (videoController == null) ? null : onScreenTapped,
onDoubleTap: (videoController == null)
? null
: onScreenTapped,
child: MediaViewSizingHelper(
bottomNavigation: bottomNavigation(),
requiredHeight: 55,
@ -837,6 +770,7 @@ class _MediaViewerViewState extends State<MediaViewerView> {
],
),
),
),
);
}
}

View file

@ -80,11 +80,18 @@ class _EmojiReactionWidgetState extends State<EmojiReactionWidget> {
child: SizedBox(
width: 40,
child: Center(
child: widget.show
? EmojiAnimationComp(
child: AnimatedOpacity(
opacity: widget.show ? 1.0 : 0.0,
duration: widget.show
? const Duration(milliseconds: 150)
: Duration.zero,
child: Offstage(
offstage: !widget.show,
child: EmojiAnimationComp(
emoji: widget.emoji,
)
: const SizedBox.shrink(),
),
),
),
),
),
);

View file

@ -0,0 +1,42 @@
import 'package:flutter/material.dart';
/// Observes keyboard dismiss via viewInsets without causing the parent to
/// rebuild on every keyboard animation frame.
class KeyboardDismissObserver extends StatefulWidget {
const KeyboardDismissObserver({
required this.showSendTextMessageInput,
required this.onKeyboardDismissed,
required this.child,
super.key,
});
final bool showSendTextMessageInput;
final VoidCallback onKeyboardDismissed;
final Widget child;
@override
State<KeyboardDismissObserver> createState() =>
_KeyboardDismissObserverState();
}
class _KeyboardDismissObserverState extends State<KeyboardDismissObserver> {
double _maxBottomInset = 0;
@override
Widget build(BuildContext context) {
final bottomInset = MediaQuery.viewInsetsOf(context).bottom;
if (bottomInset > _maxBottomInset) {
_maxBottomInset = bottomInset;
} else if (bottomInset == 0 && _maxBottomInset > 0) {
_maxBottomInset = 0;
if (widget.showSendTextMessageInput) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) {
widget.onKeyboardDismissed();
}
});
}
}
return widget.child;
}
}

View file

@ -0,0 +1,110 @@
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:twonly/src/database/twonly.db.dart';
import 'package:twonly/src/services/mediafiles/mediafile.service.dart';
import 'package:twonly/src/visual/components/animate_icon.comp.dart';
import 'package:twonly/src/visual/elements/my_icon_button.element.dart';
/// Extracted bottom navigation bar widget to provide subtree isolation.
/// Flutter can skip rebuilding this widget when only the parent's unrelated
/// state changes (e.g. progress timer, keyboard insets).
class MediaViewerBottomNavigationBar extends StatelessWidget {
const MediaViewerBottomNavigationBar({
required this.currentMedia,
required this.currentMessage,
required this.imageSaving,
required this.imageSaved,
required this.showShortReactions,
required this.onSaveToGallery,
required this.onToggleReactions,
required this.onMessagePressed,
required this.onCameraPressed,
super.key,
});
final MediaFileService? currentMedia;
final Message? currentMessage;
final bool imageSaving;
final bool imageSaved;
final bool showShortReactions;
final VoidCallback onSaveToGallery;
final VoidCallback onToggleReactions;
final VoidCallback onMessagePressed;
final VoidCallback onCameraPressed;
/// Pre-built static icon for the emoji grid button so the 4 Lottie
/// animations are created only once.
static final Widget _emojiGridIcon = SizedBox(
width: 30,
height: 30,
child: GridView.count(
crossAxisCount: 2,
children: List.generate(
4,
(index) {
return SizedBox(
width: 8,
height: 8,
child: Center(
child: EmojiAnimationComp(
emoji: EmojiAnimationComp.animatedIconKeys[index],
),
),
);
},
),
),
);
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (currentMedia != null &&
currentMessage != null &&
!currentMedia!.mediaFile.requiresAuthentication &&
currentMedia!.mediaFile.displayLimitInMilliseconds == null)
MyIconButton(
variant: MyIconButtonVariant.secondary,
onPressed: (currentMedia == null || currentMessage == null)
? null
: onSaveToGallery,
icon: imageSaving
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator.adaptive(strokeWidth: 2),
)
: imageSaved
? const Icon(Icons.check)
: const FaIcon(FontAwesomeIcons.floppyDisk, size: 20),
),
const SizedBox(width: 10),
IconButton(
icon: _emojiGridIcon,
onPressed: onToggleReactions,
style: ButtonStyle(
padding: WidgetStateProperty.all<EdgeInsets>(
const EdgeInsets.symmetric(vertical: 10, horizontal: 20),
),
),
),
const SizedBox(width: 10),
MyIconButton(
variant: MyIconButtonVariant.secondary,
onPressed: onMessagePressed,
icon: const FaIcon(
FontAwesomeIcons.message,
size: 20,
),
),
const SizedBox(width: 10),
MyIconButton(
onPressed: onCameraPressed,
icon: const FaIcon(FontAwesomeIcons.camera, size: 24),
),
],
);
}
}

View file

@ -335,9 +335,10 @@ class _ParticlePainter extends CustomPainter {
_ParticlePainter(this.particles);
final List<_Particle> particles;
static final _textPainter = TextPainter(textDirection: TextDirection.ltr);
@override
void paint(Canvas canvas, Size size) {
final textPainter = TextPainter(textDirection: TextDirection.ltr);
for (final p in particles) {
final tp = TextSpan(
text: p.emoji,
@ -350,14 +351,17 @@ class _ParticlePainter extends CustomPainter {
: null,
),
);
textPainter
_textPainter
..text = tp
..layout();
canvas
..save()
..translate(p.x - textPainter.width / 2, p.y - textPainter.height / 2)
..translate(
p.x - _textPainter.width / 2,
p.y - _textPainter.height / 2,
)
..rotate(p.rotation);
textPainter.paint(canvas, Offset.zero);
_textPainter.paint(canvas, Offset.zero);
canvas.restore();
}
}