Stream provides you a sequence of data. It can become memory leaks, if you don't dispose them correctly.
Use tip: At first, you'll have to install Pulse-X package. Here's the installation tip.
Usage
Stream data management is difficult. With Pulse-X, you won't have to use StreamController or Stream, or listen to StreamController. Pulse-X provides you with PulseXStreamViewModel class that you can extend and PulseXStreamBuilder for reactive UI.
Now, we'll create a realtime clock project that uses Stream data with Pulse-X.
First, you'll need to install intl package to convert date format.
Then, start creating a TimerViewModel class like this.
classTimerViewModelextendsPulseXStreamViewModel<String> { // specify stream data typelateTimer _timer;finalDateFormat formattedDate =DateFormat('h:mm:ss a'); // convert date formatvoidaddDateTime() { _timer =Timer.periodic(constDuration(seconds:1), (timer) {String currentTime = formattedDate.format(DateTime.now());addValue(currentTime); // Pulse will automatically add data via sink }, ); }@overridevoidonDispose() { _timer.cancel(); // cancel your timer or it'll probably make memory leak }}
See! You don't even use stream here. Because Pulse is handling Stream automatically.
Then, it's time to create TimerView class.
final amber500 =Colors.amber.shade500;classTimerViewextendsStatefulWidget {constTimerView({Key? key}) : super(key: key);@overrideState<TimerView> createState() =>_TimerViewState();}class_TimerViewStateextendsState<TimerView> {final timerViewModel =TimerViewModel(); // create timer view model@overridevoidinitState() { super.initState(); timerViewModel.addDateTime(); // add stream data }@overridevoiddispose() { timerViewModel.onDispose(); // dispose view model to cancel timer super.dispose(); }@overrideWidgetbuild(BuildContext context) {returnScaffold( appBar:AppBar( title:constText('Timer'), ), body:Center( child:PulseXStreamBuilder( // for reactive UI viewModel: timerViewModel, builder: (_, viewModel, snapshot) { // three parameters -context,view model, snapshot// you have to use snapshot to retrieve stream dataif (snapshot.hasData) {returnTimerLabel(time: snapshot.data.toString()); } elseif (snapshot.hasError) {returnconstText('Something went wrong'); }returnCupertinoActivityIndicator( radius:20, color: amber500, ); }, ), ), ); }}classTimerLabelextendsStatelessWidget {constTimerLabel({Key? key, required this.time}) : super(key: key);finalString time;@overrideWidgetbuild(BuildContext context) {returnText( time, style:Theme.of(context).textTheme.displayLarge?.copyWith( color: amber500, ), ); }}