Created
September 14, 2021 15:32
-
-
Save andantonyan/aa5d2e69e52623e0b024f00e08cc8f12 to your computer and use it in GitHub Desktop.
Example using inversion of control with flutter bloc
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
import 'package:flutter_bloc/flutter_bloc.dart'; | |
abstract class AbstractBloc<Event, State> implements Bloc<Event, State> {} | |
@immutable | |
class TestState { | |
final int value; | |
const TestState(this.value); | |
} | |
@immutable | |
abstract class TestEvent {} | |
class TestIncrement extends TestEvent {} | |
class TestBloc extends Bloc<TestEvent, TestState> implements AbstractBloc<TestEvent, TestState> { | |
@override | |
TestState get initialState => const TestState(0); | |
@override | |
Stream<TestState> mapEventToState(TestEvent event) async* { | |
if (event is TestIncrement) { | |
yield TestState(state.value + 1); | |
} | |
} | |
} | |
class TestScreen extends StatelessWidget { | |
const TestScreen({Key key}) : super(key: key); | |
@override | |
Widget build(BuildContext context) { | |
return BlocProvider<AbstractBloc<TestEvent, TestState>>( | |
create: (context) => TestBloc(), | |
child: Builder( | |
builder: (context) { | |
return Scaffold( | |
appBar: AppBar(title: Text('Test Screen')), | |
body: Center( | |
child: Column( | |
children: [ | |
BlocBuilder<AbstractBloc<TestEvent, TestState>, TestState>( | |
builder: (context, state) => Text('Value ${state.value}'), | |
), | |
TextButton( | |
child: Text('Increment'), | |
onPressed: () => context.bloc<AbstractBloc<TestEvent, TestState>>().add(TestIncrement()), | |
), | |
], | |
), | |
), | |
); | |
}, | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment