iT邦幫忙

2021 iThome 鐵人賽

DAY 28
0
Mobile Development

30天 - Flutter 日常系列 第 28

[Day28] Flutter - Application Click Game (part12)

  • 分享至 

  • xImage
  •  

前言

Hi, 我是魚板伯爵今天要把按下螢幕時觸發的事件接上去,教學內容只會擷取片段程式碼,建議大家搭配完整程式碼來練習。

完整程式碼

需要具備知識

Count:Event

按下螢幕時IncrementEvent事件觸發並把數字傳進來。

part of 'count_bloc.dart';

abstract class CountEvent extends Equatable {
  const CountEvent();

  @override
  List<Object> get props => [];
}

class IncrementEvent extends CountEvent {
  final int count;

  const IncrementEvent(this.count);

  @override
  List<Object> get props => [count];
}

Count:State

將計數器切成三個階段,初始數字、計數成功和計數失敗,成功的時候就會回傳加一的結果。

part of 'count_bloc.dart';

abstract class CountState extends Equatable {
  const CountState();

  @override
  List<Object> get props => [];
}

class CountInitial extends CountState {
  final int count = 0;

  @override
  List<Object> get props => [count];
}

class CountSuccess extends CountState {
  final int count;

  const CountSuccess(this.count);

  @override
  List<Object> get props => [count];
}

class CountFailure extends CountState {}

Count:Bloc

IncrementEvent事件觸發時把數字傳進來加一然後回傳加一結果。

import 'dart:async';
import 'dart:developer';

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:stunning_tribble/infrastructure/count/count_repository.dart';

part 'count_event.dart';
part 'count_state.dart';

class CountBloc extends Bloc<CountEvent, CountState> {
  CountRepository _countRepository;
  CountBloc({required CountRepository countRepository})
      : _countRepository = countRepository,
        super(CountInitial());

  @override
  Stream<CountState> mapEventToState(
    CountEvent event,
  ) async* {
    if (event is IncrementEvent) {
      yield* _mapIncrementToState(event.count);
    }
  }

  Stream<CountState> _mapIncrementToState(int _count) async* {
    final increment = await _countRepository.increment(_count);
    yield* increment.fold(
      (countFailure) async* {
        log("$countFailure");
        yield CountFailure();
      },
      (count) async* {
        yield CountSuccess(count);
      },
    );
  }
}

Note

距離遊戲完成就剩最後幾步了。


上一篇
[Day27] Flutter - Infrastructure Click Game (part11)
下一篇
[Day29] Flutter - Presentation Click Game Screen (part13)
系列文
30天 - Flutter 日常30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言