iT邦幫忙

2022 iThome 鐵人賽

DAY 22
0
Mobile Development

在 Flutter 開發旅程的手札系列 第 22

Flutter Package - Bloc(二)

  • 分享至 

  • xImage
  •  

今天要開始介紹Bloc,建構Bloc最重要的兩個要素就是事件(event)跟狀態(state),今天的說明會將Flutter Package - Bloc(一)從Cubit改寫成Bloc的寫法

建立counter_management_bloc.dart檔案
為了讓昨天做的Counter有不同的狀態,在數值方面我會限制最大值10,及最小值0,來讓大家更了解Bloc的使用

import 'package:flutter_bloc/flutter_bloc.dart';

class CounterManagementBloc extends Bloc<CounterManagementEvent, CounterManagementState> {
  CounterManagementBloc() : super(CounterManagementInitial()) {
    //當新增事件發生時做的事
    on<CounterManagementIncreased>((event, emit) async {
      if (state.count + 1 <= 10) {
        state.count += 1;
        emit(CounterManagementIncreasedSuccess(count: state.count));
      } else {
        emit(CounterManagementIncreasedFailure(count: state.count, reason: "數值最大10"));
      }
    });
    //當減少事件發生時做的事
    on<CounterManagementDecreased>((event, emit) async {
      if (state.count - 1 >= 0) {
        state.count -= 1;
        emit(CounterManagementDecreasedSuccess(count: state.count));
      } else {
        emit(CounterManagementDecreasedFailure(count: state.count, reason: "數值最小0"));
      }
    });
    //當重置事件發生時做的事
    on<CounterManagementReset>((event, emit) async {
      emit(CounterManagementResetSuccess(count: 0));
    });
  }
}

//EVENT:事件都是發生了才進到Bloc,所以最後面的動作要放上過去分詞
abstract class CounterManagementEvent {}

class CounterManagementIncreased extends CounterManagementEvent {
  CounterManagementIncreased();
}

class CounterManagementDecreased extends CounterManagementEvent {
  CounterManagementDecreased();
}

class CounterManagementReset extends CounterManagementEvent {
  CounterManagementReset();
}

//STATES
//定義state的內容
abstract class CounterManagementState {
  int count;
  CounterManagementState({required this.count});
}

//初始狀況
class CounterManagementInitial extends CounterManagementState {
  CounterManagementInitial() : super(count: 0);
}

//定義Event的狀態
class CounterManagementIncreasedSuccess extends CounterManagementState {
  CounterManagementIncreasedSuccess({required int count}) : super(count: count);
}

//當失敗時顯示reason
class CounterManagementIncreasedFailure extends CounterManagementState {
  final String reason;
  CounterManagementIncreasedFailure({required int count, required this.reason}) : super(count: count);
}

class CounterManagementDecreasedSuccess extends CounterManagementState {
  CounterManagementDecreasedSuccess({required int count}) : super(count: count);
}

class CounterManagementDecreasedFailure extends CounterManagementState {
  final String reason;
  CounterManagementDecreasedFailure({required int count, required this.reason}) : super(count: count);
}

//Reset的狀態只會有成功所以不用寫Failure的狀態
class CounterManagementResetSuccess extends CounterManagementState {
  CounterManagementResetSuccess({required int count}) : super(count: count);
}


建立bloc_screen.dart

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import 'counter_management_bloc.dart';

class BlocScreen extends StatelessWidget {
  const BlocScreen({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: const Text('Counter')),
        body: BlocProvider(
          create: (_) => CounterManagementBloc(),
          child: BlocBuilder<CounterManagementBloc, CounterManagementState>(builder: (context, state) {
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      ElevatedButton(
                        onPressed: () {
                          context.read<CounterManagementBloc>().add(CounterManagementDecreased());
                        },
                        child: const Icon(Icons.remove),
                      ),
                      Text(state.count.toString()),
                      ElevatedButton(
                        onPressed: () {
                          context.read<CounterManagementBloc>().add(CounterManagementIncreased());
                        },
                        child: const Icon(Icons.add),
                      ),
                    ],
                  ),
                  const SizedBox(
                    height: 20,
                  ),
                  ElevatedButton(
                    onPressed: () {
                      context.read<CounterManagementBloc>().add(CounterManagementReset());
                    },
                    child: const Text("reset"),
                  ),
                  const SizedBox(
                    height: 100,
                  ),
                  //當狀態是CounterManagementDecreasedFailure會顯示出state.reason
                  Text(
                    state is CounterManagementDecreasedFailure ? state.reason : "",
                    style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                  ),
                  //當狀態是CounterManagementIncreasedFailure會顯示出state.reason
                  Text(
                    state is CounterManagementIncreasedFailure ? state.reason : "",
                    style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                  ),
                ],
              ),
            );
          }),
        ));
  }
}

Bloc Demo


上一篇
Flutter Package - Bloc(一)
下一篇
Flutter Package - Bloc(三)
系列文
在 Flutter 開發旅程的手札30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言