I'm developing a clock widget in Flutter that displays the current time. I want to provide two methods for updating the time asynchronously: one using a continuous stream of time updates, and the other using a timer that updates the time at regular intervals.
Code Explanation:
clock() Method:
- This method returns a continuous stream of time updates asynchronously.
- It uses a while loop to continuously update the current time using DateTime.now() and formats it using DateFormat.
- The time is yielded as a String and printed to the console.
- It includes a delay using Future.delayed() to control the update frequency
timer() Method:
- This method returns a stream of time updates asynchronously using a timer.
- It initializes the current time and formats it.
- Inside a while loop, it checks if the current time differs from the last recorded time. If so, it updates the time and yields it. Otherwise, it repeats the same time for a maximum of 5 iterations.
- This method also includes a delay using Future.delayed().
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
class Clock extends StatefulWidget {
const Clock({super.key});
@override
State<Clock> createState() => _ClockState();
}
class _ClockState extends State<Clock> {
//first methode, returns time as String
Stream<String> clock() async* {
DateTime time;
String current;
while (true) {
time = DateTime.now();
current = DateFormat('hh : mm : ss').format(time);
yield current;
print(current);
await Future.delayed(
Duration(milliseconds: 100),
);
}
}
//seconde one
Stream<String> timer() async* {
DateTime time = DateTime.now();
String current = DateFormat('hh : mm : ss').format(time);
while (true) {
if (current != DateFormat('hh : mm : ss').format(DateTime.now())) {
current = DateFormat('hh : mm : ss').format(DateTime.now());
yield current;
print(current);
await Future.delayed(
Duration(milliseconds: 200),
);
} else {
yield current;
//this command repeats 5 time maximum
print(current);
await Future.delayed(
Duration(milliseconds: 200),
);
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: StreamBuilder(
stream: timer(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
return Container(
height: 350,
width: 350,
decoration: BoxDecoration(
border: Border.all(
color: Colors.blue,
width: 4,
),
shape: BoxShape.circle),
child: Center(
child: Text(
'${snapshot.data}',
style: TextStyle(
fontSize: 30,
fontWeight: FontWeight.w500,
),
),
),
);
} else {
return Text('waiting...');
}
},
),
),
);
}
}
both methods rely on while loops where print statement in clock() repeats 10 times maximum and 5 times maximum in timer methode