1+ import 'dart:async' ;
12import 'dart:convert' ;
23
34import 'package:flutter/material.dart' ;
@@ -315,7 +316,7 @@ class _UserWidget extends StatelessWidget {
315316}
316317
317318/// The text of current time in [user] 's timezone.
318- class UserLocalTimeText extends StatelessWidget {
319+ class UserLocalTimeText extends StatefulWidget {
319320 const UserLocalTimeText ({
320321 super .key,
321322 required this .user,
@@ -333,15 +334,32 @@ class UserLocalTimeText extends StatelessWidget {
333334 tz.initializeDatabase (blob);
334335 }
335336
336- Stream <String > _getDisplayLocalTimeFor (User user, ZulipLocalizations zulipLocalizations) async * {
337- if (! tz.timeZoneDatabase.isInitialized) await initializeTimezonesUsingAssets ();
337+ @override
338+ State <UserLocalTimeText > createState () => _UserLocalTimeTextState ();
339+ }
338340
339- Stream <DateTime > timer (Duration duration) async * {
340- yield DateTime .timestamp ();
341- yield * Stream .periodic (duration, (_) => DateTime .timestamp ());
342- }
341+ class _UserLocalTimeTextState extends State <UserLocalTimeText > {
342+ late final Timer _timer;
343+ final StreamController <DateTime > _streamController = StreamController ();
344+ Stream <DateTime > get _stream => _streamController.stream;
345+
346+ @override
347+ void initState () {
348+ _streamController.add (DateTime .timestamp ());
349+ _timer = Timer (const Duration (seconds: 1 ), () { _streamController.add (DateTime .timestamp ()); });
350+ super .initState ();
351+ }
352+
353+ @override
354+ void dispose () {
355+ _timer.cancel ();
356+ super .dispose ();
357+ }
358+
359+ Stream <String > _getDisplayLocalTimeFor (User user, ZulipLocalizations zulipLocalizations) async * {
360+ if (! tz.timeZoneDatabase.isInitialized) await UserLocalTimeText .initializeTimezonesUsingAssets ();
343361
344- await for (final DateTime time in timer ( Duration (seconds : 1 )) ) {
362+ await for (final DateTime time in _stream ) {
345363 final location = tz.getLocation (user.timezone);
346364 final localTime = tz.TZDateTime .from (time, location);
347365 yield zulipLocalizations.userLocalTime (localTime);
@@ -351,7 +369,7 @@ class UserLocalTimeText extends StatelessWidget {
351369 @override
352370 Widget build (BuildContext context) {
353371 return StreamBuilder (
354- stream: _getDisplayLocalTimeFor (user, ZulipLocalizations .of (context)),
372+ stream: _getDisplayLocalTimeFor (widget. user, ZulipLocalizations .of (context)),
355373 builder: (context, snapshot) {
356374 if (snapshot.hasError) Error .throwWithStackTrace (snapshot.error! , snapshot.stackTrace! );
357375 return Text (snapshot.data ?? '' );
0 commit comments