Created
May 8, 2019 15:43
-
-
Save lbv/786521ed1ac7afe8741875ddb67691c6 to your computer and use it in GitHub Desktop.
This file contains 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:bloc/bloc.dart'; | |
class SomeState { | |
final bool isLoading; | |
final int data; | |
SomeState({this.isLoading = false, this.data = 0}); | |
SomeState copyWith({bool isLoading, int data}) { | |
return SomeState( | |
isLoading: isLoading ?? this.isLoading, | |
data: data ?? this.data, | |
); | |
} | |
@override | |
String toString() => 'SomeState { isLoading: $isLoading, data: $data }'; | |
} | |
Future<int> slowComputation(int input) async { | |
return Future.delayed(Duration(seconds: 5), () { | |
return input + 1; | |
}); | |
} | |
class MyBloc extends Bloc<String, SomeState> { | |
@override | |
SomeState get initialState => SomeState(); | |
@override | |
Stream<SomeState> mapEventToState(String event) async* { | |
yield currentState.copyWith(isLoading: true); | |
try { | |
int result = await slowComputation(currentState.data); | |
yield currentState.copyWith(data: result); | |
} | |
finally { | |
yield currentState.copyWith(isLoading: false); | |
} | |
} | |
} | |
void main() { | |
final bloc = MyBloc(); | |
bloc.dispatch('something'); | |
bloc.state.forEach((state) { | |
print('State received: $state'); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
try this instead