Share
Embed
Transcript
23 slides
-
2018ͷDartConfʹͯɺ Google Adwords (ݱGoogleࠂ) ΞϓϦΛ։ൃ͍ͯͨ͠ Paolo Soares ࢯ͕ൃද MVVMʹ੍Λͨ͠Α͏ͳσβΠϯύλʔϯ ւ֎Ͱݱࡏࠜڧ͍ਓؾʢຊͰ໊Ίʣ
BLoCύλʔϯͱ https://www.youtube.com/watch?v=PLHln7wHgPE -
FlutterΞϓϦ։ൃʹ͓͚Δઃܭͷ՝ UI Component (Widget) Event (ϘλϯλοϓͳͲ) Business Logic (ܭࢉॲཧ) D
a t a Logic (σʔλͷಡࠐͱอଘɺ௨৴) EntityͳͲ Model View ઃܭͷجຊʮViewͱModelͷʯ -
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Λ͑ͨΒ… -
FlutterΞϓϦ։ൃʹ͓͚Δઃܭͷ՝ View͕ෳࡶԽ͠ɺModelͷڥք͕ᐆດʹ Business Logic D a t a Logic EntityͳͲ
Model View buildϝιουͷreturnͷલʹ ෳࡶͳ UI Logic ͕… UI Logic ͷॲཧʹԠͯ͡Eventൃੜ buildϝιουͷreturnதʹLogic -
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 -
2018൛ BLoC ViewͱBLoCͷΓͱΓ StreamͱSink͚ͩͰߦ͏ UI Logic ViewͷEventͷॲཧ ModelͷΛมܗͯ͠ ViewʹૹΔ UI
Component Event View BLoC Cl a ss ViewStreamͰૹΒΕ͖ͯͨΛͦͷ··WidgetͷҾʹͯ͠දࣔ͢Δ͔ɺ boolʹΑΔذͷΈߦ͏ͷ͕ཧ (Logicͷഉআ) SinkͰૹΓ StreamͰड͚औΔ -
2018൛ BLoC BLoC ≒ ViewModel ViewͷEventͷॲཧ ModelͷΛView༻ʹม UI Logic UI
Component Event UI Logic View ViewModel Model ͨͩ͠MVVMʹView͔ΒLogicΛഉআ͢Δͱ͍͏نଇͳ͍ -
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ύοέʔδΛ෦Ͱ͍ͬͯΔͷͰɺ ͠ํجຊతʹಉ͡ -
// ঢ়ଶΛఆٛ 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ঢ়ଶͱΠϕϯτΛηοτͰ࣋ͭ ঢ়ଶʹԠͯ͡อ࣋͢ΔΛม͑ΒΕΔ -
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ΫϥεͰΠϕϯτॲཧΛ࣮ -
୯Ұͷঢ়ଶ͚ͩͰྑ͍ͳΒCubitͱ͍͏؆қ൛BLoC͋Δ class CounterCubit extends Cubit<int> { CounterCubit() : super(0); void
increment() => emit(state + 1); }