Upgrade to Pro — share decks privately, control downloads, hide ads and more …

BLoCパターンとflutter_bloc

 BLoCパターンとflutter_bloc

SODA Flutter Talk #2 オフライン開催

Avatar for Hayami Shuhei

Hayami Shuhei

May 09, 2025
Tweet

More Decks by Hayami Shuhei

Other Decks in Programming

Transcript

  1. FlutterΞϓϦ։ൃʹ͓͚Δઃܭͷ՝୊ UI Component (Widget) Event (ϘλϯλοϓͳͲ) Business Logic (ܭࢉॲཧ) D

    a t a Logic (σʔλͷಡࠐͱอଘɺ௨৴) EntityͳͲ Model View ઃܭͷجຊ͸ʮViewͱModelͷ෼཭ʯ
  2. FlutterΞϓϦ։ൃʹ͓͚Δઃܭͷ՝୊ UI Component (Widget) Event (ϘλϯλοϓͳͲ) UIʹؔ͢Δ Business Logic (UI

    Logic) Business Logic (ܭࢉॲཧ) D a t a Logic (σʔλͷಡࠐͱอଘɺ௨৴) EntityͳͲ Model View ࠷ॳ͸໰୊ͳ͍͕ɺஈʑͱViewʹLogic͕ࠞͬͯ͘͟Δ if (Pl a tform.isIOS)… if (Pl a tform.isAndroid)… if (kIsWeb)… ը໘ͷԣ෯͕ԿpxҎԼͩͬͨΒ… εΫϩʔϧ࠲ඪ͕ԿpxΛ௒͑ͨΒ…
  3. FlutterΞϓϦ։ൃʹ͓͚Δઃܭͷ՝୊ View͕ෳࡶԽ͠ɺModelͷڥք͕ᐆດʹ Business Logic D a t a Logic EntityͳͲ

    Model View buildϝιουͷreturnͷલʹ ෳࡶͳ UI Logic ͕… UI Logic ͷॲཧʹԠͯ͡Eventൃੜ buildϝιουͷreturnதʹ΋Logic
  4. 2018೥൛ BLoC ߴػೳԽͨ͠View (Page, Component) Λ UI Componentͱ Business Logic

    Component (BLoC)ʹ෼཭ UI Logic ViewͷEventͷॲཧ Modelͷ஋Λมܗͯ͠ ViewʹૹΔ UI Component Event View BLoC Cl a ss Model
  5. 2018೥൛ BLoC ViewͱBLoCͷ΍ΓͱΓ͸ StreamͱSink͚ͩͰߦ͏ UI Logic ViewͷEventͷॲཧ Modelͷ஋Λมܗͯ͠ ViewʹૹΔ UI

    Component Event View BLoC Cl a ss View͸StreamͰૹΒΕ͖ͯͨ஋Λͦͷ··WidgetͷҾ਺ʹ౉ͯ͠දࣔ͢Δ͔ɺ bool஋ʹΑΔ෼ذͷΈߦ͏ͷ͕ཧ૝ (Logicͷഉআ) SinkͰૹΓ StreamͰड͚औΔ
  6. 2018೥൛ BLoC BLoC ≒ ViewModel ViewͷEventͷॲཧ Modelͷ஋ΛView༻ʹม׵ UI Logic UI

    Component Event UI Logic View ViewModel Model ͨͩ͠MVVMʹ͸View͔ΒLogicΛഉআ͢Δͱ͍͏نଇ͸ͳ͍
  7. return MaterialApp( home: BlocProvider( create: (context) => CounterBloc(), child: CounterPage(),

    ), ); // CounterPage಺ final state = context.watch<CounterBloc>().state; return Scaffold( body: Center(child: Text('Count: ${state.count}’)), floatingActionButton: FloatingActionButton( child: Icon(Icons.add), onPressed: () => context.read<CounterBloc>().add(IncrementEvent()), ), ); providerύοέʔδΛ಺෦Ͱ࢖͍ͬͯΔͷͰɺ ౉͠ํ΋جຊతʹಉ͡
  8. // ঢ়ଶΛఆٛ sealed class CounterState {} class CounterInitial extends CounterState

    {} class CounterLoaded extends CounterState { final int count; CounterLoaded(this.count); } // ΠϕϯτΛఆٛ sealed class CounterEvent {} class IncrementEvent extends CounterEvent {} BLoC͸ঢ়ଶͱΠϕϯτΛηοτͰ࣋ͭ ঢ়ଶʹԠͯ͡อ࣋͢Δ஋Λม͑ΒΕΔ
  9. class CounterBloc extends Bloc<CounterEvent, CounterState> { CounterBloc() : super(CounterInitial()) {

    // ΠϕϯτΛొ࿥ on<IncrementEvent>(_onIncrement); } void _onIncrement(IncrementEvent event, Emitter<CounterState> emit) { final currentState = state; // ݱࡏͷঢ়ଶʹԠͯ͡෼ذ switch (currentState) { case CounterInitial(): ɹɹɹ // ঢ়ଶͷߋ৽͸emitΛ࢖͏ emit(CounterLoaded(1)); case CounterLoaded currentState: emit(CounterLoaded(currentState.count + 1)); } } } BlocΫϥε಺ͰΠϕϯτॲཧΛ࣮૷