Stream is one of the asynchronous programming in flutter. Streams can deliver one or more values and errors instead of single value.
There are two types of Streams available
We can create streams in different ways
Is Stream and Future are the same?
Both Stream and Future works asynchronously
Both will have some values in its.
Stream is a combination of multiple Futures where are Future contains only single response
Lets create a Stream with Periodic
void main() async { Duration interval = Duration(seconds: 1); Stream<int> stream = Stream<int>.periodic(interval, (it)=>it+1); await for(int i in stream){ print(i); } } |
check above code, there the Stream.periodic creates a stream which will emits the stream data periodically based on time interval.
This will print the data like below
1 |
Listen the Stream
void main() async { Duration interval = Duration(seconds: 2); late StreamSubscription _sub; Stream<int> stream = Stream<int>.periodic(interval, (value)=>value+1); _sub= stream.listen((event) { print("Stream Data ${event}"); }); } |
Create Stream with Stream.take
void main() async { Duration interval = Duration(seconds: 2); Stream<int> stream = Stream<int>.periodic(interval, (value)=>value+1); stream=stream.take(5); stream.listen((event) { print("Stream Data ${event}"); }); } |
The above stream will emits only 5, we created stream with limited count as 5
Stream.take will be based on count passed as argument
Output:
Stream Data 1
Stream Data 2
Stream Data 3
Stream Data 4
Stream Data 5
|
Create Stream with condition While
We can also create stream by applying the takeWhile condition
void main() async { Duration interval = Duration(seconds: 2); Stream<int> stream = Stream<int>.periodic(interval, (value)=>value+1); stream=stream.takeWhile(condition); stream.listen((event) { print("Stream Data ${event}"); }); } bool condition(int x){ return x <= 5; } |
Here it stream will emits until the condition true. So this will print the stream data until it reaches 5.
Stream with skip()
By using skip, we can skip some of stream data
void main() async { Duration interval = Duration(seconds: 2); Stream<int> stream = Stream<int>.periodic(interval, (value)=>value+1); stream = stream.take(8); stream = stream.skip(3); stream.listen((event) { print("Stream Data ${event}"); }); } |
This will skip the first 3 events and takes other events
Output:
Stream Data 4
Stream Data 5
Stream Data 6
Stream Data 7
Stream Data 8
|
Other Stream functions
Stream.toList() → Future<List>
Stream. forEach()
Stream .length
Create Simple Flutter example with StreamBuilder
import 'package:flutter/material.dart'; void main() { runApp(MaterialApp( home: HomePage(), title: 'Flutter Stream Example', )); } class HomePage extends StatefulWidget { @override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { bool quizStart=false; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Flutter Stream Example'), ), body: Padding( padding: const EdgeInsets.all(12.0), child: Center( child: (!quizStart)? TextButton( onPressed: (){ setState(() { quizStart=true; }); }, child: Text("Start Timer"), style: ButtonStyle( padding: MaterialStateProperty.all(EdgeInsets.symmetric(horizontal: 8)), backgroundColor: MaterialStateProperty.all(Colors.pink), foregroundColor: MaterialStateProperty.all(Colors.white), minimumSize: MaterialStateProperty.all(Size(double.infinity,40) ), )):StreamBuilder( builder: (BuildContext context, AsyncSnapshot<int> snapshot) { if (snapshot.connectionState == ConnectionState.done) { return Text( 'Quize TimeUp!', style: TextStyle( fontSize: 30.0, ), ); } else if (snapshot.connectionState == ConnectionState.waiting) { return Text( 'Waiting For Stream', style: TextStyle( fontSize: 30.0, ), ); } return Text( '00:${snapshot.data.toString().padLeft(2,'0')}', 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; } } |
How do i close the Stream
To close the stream we will use the StreamSubscription and call the cancel() method
Duration interval = Duration(seconds: 1); Stream<int> stream = Stream<int>.periodic(interval, transform); stream = stream.take(59); late StreamSubscription<int> sub; sub=stream.listen((event) { if(event==4) { sub.cancel(); } }); |
Article Contributed By :
|
|
|
|
2182 Views |