前言
Hi, 今天要來創建一個CountBloc,然後就可以開始製作我們的CountButton了,我加了讓數字有彈跳的效果寫了一些動畫,有興趣的可以看原本程式碼。
完整程式碼
需要具備知識
CountBloc
創建一個CountBloc,把我們的按鈕畫面放進去。
1 2 3 4 5 6 7 8
| ... BlocProvider( create: (context) => CountBloc( countRepository: CountRepository(), ), child: CountButton(), ), ...
|
然後創建一個BlocBuilder來檢查每次累加數字的狀態。
1 2 3 4 5 6 7 8 9 10
| @override Widget build(BuildContext context) { return BlocBuilder<CountBloc, CountState>( builder: (context, state) { return AnimatedContainer( ..... ); }, ); }
|
在按下按鈕時觸發CountIncrementEvent的事件,並將我們現在count的數字傳進去做累加。
1 2 3 4 5 6 7 8 9 10 11
| ... Material( color: Colors.transparent, child: InkWell( highlightColor: Colors.transparent, splashColor: Colors.transparent, onTap: () => _tapUp(), // onTapUp onTapDown: (TapDownDetails details) => _tapDown(state.count), ), ), ...
|
1 2 3 4 5 6 7
| ... void _tapDown(int count) { _animationController.forward(); HapticFeedback.heavyImpact(); BlocProvider.of<CountBloc>(context).add(CountIncrementEvent(count)); } ...
|
