Skip to content

Instantly share code, notes, and snippets.

@felangel felangel/main.dart
Created Mar 21, 2019

Embed
What would you like to do?
BlocBuilder Race Condition Test
import 'package:flutter/material.dart';
import 'package:bloc/bloc.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
abstract class DataState {}
class InitialDataState extends DataState {}
class LoadedDataState extends DataState {
final String data;
LoadedDataState({@required this.data});
}
abstract class DataEvent {}
class FetchData extends DataEvent {}
class DataBloc extends Bloc<DataEvent, DataState> {
@override
DataState get initialState => InitialDataState();
@override
void onTransition(Transition<DataEvent, DataState> transition) {
print(transition);
}
@override
Stream<DataState> mapEventToState(
DataState currentState,
DataEvent event,
) async* {
if (event is FetchData) {
yield LoadedDataState(data: 'Cool Data');
}
}
}
DataBloc dataBloc = DataBloc();
void main() async {
dataBloc.dispatch(FetchData());
await Future.delayed(Duration(seconds: 1));
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
print('building HomePage');
return Scaffold(
appBar: AppBar(
title: Text('Flutter Demo'),
),
body: BlocBuilder(
bloc: dataBloc,
builder: (BuildContext context, DataState state) {
if (state is InitialDataState) {
return Center(child: CircularProgressIndicator());
}
if (state is LoadedDataState) {
return Center(child: Text(state.data));
}
return Container();
},
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.