I am glad that you like and you asked a valid question.
- Why there is not 59 second?
Stream<int> _stream() {
Duration interval = Duration(seconds: 1);
Stream<int> stream = Stream<int>.periodic(interval, transform);
stream = stream.take(59);
return stream;
}int transform(int value) {
print(value); // add this line
return value;
}
Provides at most the first count
(59 in our case) data events of this stream (Source)
It starts with 0 seconds and goes to 58 seconds, which should be i.e start with 1 second and goes till 59 seconds. So we need to transform the value
- This is how you can transform the value.
How to fix this issue?
int transform(int value) {
return value + 1;
}
}
Here is full source code
import 'package:flutter/material.dart';void main() {
runApp(MaterialApp(
home: HomePage(),
title: 'Stream Demo',
));
}class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Stream Demo'),
),
body: Center(
child: StreamBuilder(
builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return Text(
'Done : 00:${(snapshot.data).toString().padLeft(2,'0')}', //updated
style: TextStyle(
fontSize: 30.0,
),
);
} else if (snapshot.connectionState == ConnectionState.waiting) {
return Text(
'Waiting For Stream',
style: TextStyle(
fontSize: 30.0,
),
);
}
return Text(
'Active: 00:${(snapshot.data).toString().padLeft(2,'0')}', //updated
style: TextStyle(
fontSize: 30.0,
),
);
},
initialData: 0,
stream: _stream(),
),
),
);
}Stream<int> _stream() {
Duration interval = Duration(seconds: 1);
Stream<int> stream = Stream<int>.periodic(interval, transform);
stream = stream.take(59);
return stream;
}int transform(int value) {
return value + 1; // updated
}
}
One important thing is there which I totally forget to mention that the last data of stream comes in Done State