In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-07 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Editor to share with you how to achieve the timer of Flutter state management Bloc. I hope you will get something after reading this article. Let's discuss it together.
The details are as follows
1. Dependence
Dependencies: flutter_bloc: ^ 2.1.1 equatable: ^ 1.0.1 wave: ^ 0.0.8
2. Ticker
Ticker is used to generate the data stream of timers.
/ / timer data source class Ticker {/ / timer data source / / @ param ticks time Stream tick ({int ticks}) {return Stream.periodic (Duration (seconds: 1), (x) = > ticks-x-1) .take (ticks);}}
3. TimerBloc
To create a TimerBloc for consuming Ticker, we need to create two helper classes, timer state and timer event. The status of the timer is
Ready (ready to count down from the specified duration)
Running (decrement count from specified duration)
Paused (paused for the rest of the duration)
Finished completed, remaining duration is 0
Import 'package:equatable/equatable.dart';import' package:meta/meta.dart'; / / timer status @ immutableabstract class TimerState extends Equatable {/ / time final int duration; / constructor const TimerState (this.duration); @ override List get props = > [this.duration];} / / ready status class Ready extends TimerState {const Ready (int duration): super (duration); @ override String toString () = > 'Ready {duration: $duration}' } / / pause status class Paused extends TimerState {const Paused (int duration): super (duration); @ override String toString () = > 'Paused {duration: $duration}';} / running status class Running extends TimerState {const Running (int duration): super (duration); @ override String toString () = > 'Running {duration: $duration}';} / / completion status class Finished extends TimerState {const Finished (): super (0);}
All State inherits from the abstract class TimerState, because no matter what state we are in, we need to know the remaining time.
4. TimerEvent
The events we need to deal with are
Start (informs TimerBloc that the timer should start)
Pause (informs TimerBloc that the timer should be paused)
Resume (notifies TimerBloc that the timer should be restored)
Reset (informs TimerBloc that the timer should be reset to its original state)
Tick (notifies TimerBloc that time remaining for update is required)
Import 'package:equatable/equatable.dart';import' package:meta/meta.dart'; / / timer event @ immutableabstract class TimerEvent extends Equatable {const TimerEvent (); @ override List get props = > [];} / / start time class Start extends TimerEvent {/ timer time final int duration; const Start ({@ required this.duration}); @ override String toString () = > 'Start {duration: $duration}' } / / pause event class Paused extends TimerEvent {} / / resume status class Resumed extends TimerEvent {} / / reset status class Reset extends TimerEvent {} / / timer event class Tick extends TimerEvent {/ current time final int duration; const Tick ({@ required this.duration}); @ override List get props = > [this.duration]; @ override String toString () = > 'Tick {duration: $duration}';}
5. TimerBloc implementation
1. Initialization state Ready (_ duration)
two。 Create a Ticker object, and the user gets the data stream
3. Implement the mapEventToState method
4. When event is Start, the data stream needs to be enabled
5. Create a StreamSubscription, handle the different states of the flow, and close it in the close method of the bloc
6. When event is Tick, you need to update the data.
7. When event is Pause, you need to stop the timer
8. When event is Resume, you need to restart the timer
9. When event is reset, you need to reset the timer
Import 'dart:async';import' package:bloc/bloc.dart';import 'package:flutter/material.dart';import' package:state_manage/timer/ticker.dart';import'. / bloc.dart'; / / timer Blocclass TimerBloc extends Bloc {/ timer time final int _ duration = 60; / / timer data stream final Ticker _ ticker; / / stream subscription StreamSubscription _ tickerSubscription TimerBloc ({@ required Ticker ticker}): assert (ticker! = null), _ ticker = ticker; / / initialization state @ override TimerState get initialState = > Ready (_ duration); @ override Stream mapEventToState (TimerEvent event,) async* {print ('$event'); if (event is Start) {yield* _ mapStartToState (event);} else if (event is Tick) {yield* _ mapTickToState (event) } else if (event is Pause) {yield* _ mapPauseToState (event);} else if (event is Resume) {yield* _ mapResumeToState (event);} else if (event is Reset) {yield* _ mapResetToState (event);}} @ override Future close () {_ tickerSubscription?.cancel (); return super.close () } / / process the start event Stream _ mapStartToState (Start start) async* {/ / running status yield Running (start.duration); / / unsubscribe _ tickerSubscription?.cancel (); / / create a subscription _ tickerSubscription = _ ticker.tick (ticks: start.duration). Listen ((duration) {add (Tick (duration: duration));}) } / / handle timer event Stream _ mapTickToState (Tick tick) async* {yield tick.duration > 0? Running (tick.duration): Finished ();} / / handle pause event Stream _ mapPauseToState (Pause pause) async* {if (state is Running) {_ tickerSubscription?.pause (); yield Paused (state.duration);}} / / process recovery status Stream _ mapResumeToState (Resume resume) async* {if (state is Paused) {_ tickerSubscription?.resume (); yield Running (state.duration) }} / / process reset status Stream _ mapResetToState (Reset reset) async* {_ tickerSubscription?.cancel (); yield Ready (_ duration);}}
6. Interface realization
Realize timer display
Timer_test.dart
Import 'package:flutter/material.dart';import' package:flutter_bloc/flutter_bloc.dart';import 'package:state_manage/timer/bloc/bloc.dart';import' package:state_manage/timer/ticker.dart' / / timer class TimerTest extends StatelessWidget {@ override Widget build (BuildContext context) {return MaterialApp (theme: ThemeData (primaryColor: Color.fromRGBO (109,234,255,1), accentColor: Color.fromRGBO (72,74,126,1), brightness: Brightness.dark,), title: 'Flutter Timer', home: BlocProvider (create: (ctx) = > TimerBloc (ticker: Ticker ()) Child: Timer (),) }} / timer page class Timer extends StatelessWidget {/ font style static const TextStyle timerTextStyle = TextStyle (fontSize: 60, fontWeight: FontWeight.bold) Override Widget build (BuildContext context) {return Scaffold (appBar: AppBar (title: Text ('Flutter Time')), body: Column (mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [Padding (padding: EdgeInsets.symmetric (vertical: 100.0), child: Center (child: BlocBuilder (builder: (ctx) State) {/ / minute format final String minuteStr = (state.duration / 60)% 60) .floor () .toString () .padLeft (2,'0') / / format final String secondStr = (state.duration% 60). Floor (). ToString (). PadLeft (2,'0'); return Text ('$minuteStr: $secondStr', style: Timer.timerTextStyle,) },)],),);}}
Add background
Timer_background.dart
Import 'package:flutter/material.dart';import' package:wave/config.dart';import 'package:wave/wave.dart' / / timer background class Background extends StatelessWidget {@ override Widget build (BuildContext context) {return WaveWidget (config: CustomConfig (gradients: [[Color.fromRGBO (72,74,126,1), Color.fromRGBO (125,170,206,1), Color.fromRGBO (184,189,245,0.7)] [Color.fromRGBO (72,74,126,1), Color.fromRGBO (125,170,206,1), Color.fromRGBO (172,182,219,0.7)], [Color.fromRGBO (72,73,126,1), Color.fromRGBO (125,170,206,1), Color.fromRGBO (190,238,246) ], durations: [19440, 10800, 6000], heightPercentages: [0.03,0.01,0.02], gradientBegin: Alignment.bottomCenter, gradientEnd: Alignment.topCenter), size: Size (double.infinity, double.infinity), waveAmplitude: 25, backgroundColor: Colors.blue [50],) }}
Timer_test.dart
/ / timer page class Timer extends StatelessWidget {/ Font style static const TextStyle timerTextStyle = TextStyle (fontSize: 60, fontWeight: FontWeight.bold); @ override Widget build (BuildContext context) {return Scaffold (appBar: AppBar (title: Text ('Flutter Time')), body: Stack (children: [Background (), Column (/ /... Omit the content)],),);}}
Add timer action
Timer_actions.dart
Import 'package:flutter/material.dart';import' package:flutter_bloc/flutter_bloc.dart';import 'package:state_manage/timer/bloc/bloc.dart'; / / Action class TimerActions extends StatelessWidget {@ override Widget build (BuildContext context) {return Row (mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: _ mapStateToActionButtons (timerBloc: BlocProvider.of (context)),) } / create action button / @ param timerBloc timer Bloc List _ mapStateToActionButtons ({TimerBloc timerBloc}) {/ / timer current state final TimerState currentState = timerBloc.state / / return different views according to different states if (currentState is Ready) {return [FloatingActionButton (child: Icon (Icons.play_arrow), onPressed: () = > timerBloc.add (Start (duration: currentState.duration)),)] } else if (currentState is Running) {return [FloatingActionButton (child: Icon (Icons.pause), onPressed: () = > timerBloc.add (Pause ()), FloatingActionButton (child: Icon (Icons.replay), onPressed: () = > timerBloc.add (Reset ()),)] } else if (currentState is Paused) {return [FloatingActionButton (child: Icon (Icons.play_arrow), onPressed: () = > timerBloc.add (Resume ()), FloatingActionButton (child: Icon (Icons.replay), onPressed: () = > timerBloc.add (Reset ()),)] } else if (currentState is Finished) {return [FloatingActionButton (child: Icon (Icons.replay), onPressed: () = > timerBloc.add (Reset ()),)];} else {return [];}
Set actions in the interface
Timer_test.dart
/ / timer page class Timer extends StatelessWidget {/ Font style static const TextStyle timerTextStyle = TextStyle (fontSize: 60, fontWeight: FontWeight.bold) @ override Widget build (BuildContext context) {return Scaffold (appBar: AppBar (title: Text ('Flutter Timer')), body: Stack (children: [Background (), Column (mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [Padding (/ /...)) BlocBuilder (condition: (previousState, currentState) = > currentState.runtimeType! = previousState.runtimeType, builder: (ctx, state) = > TimerActions ()],)],)) }}
Effect picture
After reading this article, I believe you have a certain understanding of "how to realize the timer of Flutter state management Bloc". If you want to know more about it, you are welcome to follow the industry information channel. Thank you for your reading!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.