Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[flutter_bloc_hydrated_weather] WeatherBloc
class WeatherBloc extends HydratedBloc<WeatherEvent, WeatherState> {
final WeatherRepository weatherRepository;
WeatherBloc({@required this.weatherRepository})
: assert(weatherRepository != null);
@override
WeatherState get initialState => super.initialState ?? WeatherEmpty();
@override
Stream<WeatherState> mapEventToState(WeatherEvent event) async* {
if (event is FetchWeather) {
yield WeatherLoading();
try {
final Weather weather = await weatherRepository.getWeather(event.city);
yield WeatherLoaded(weather: weather);
} catch (_) {
yield WeatherError();
}
}
if (event is RefreshWeather) {
try {
final Weather weather = await weatherRepository.getWeather(event.city);
yield WeatherLoaded(weather: weather);
} catch (_) {
yield currentState;
}
}
}
@override
WeatherState fromJson(Map<String, dynamic> json) {
return WeatherLoaded(
weather: Weather(
condition: WeatherCondition.values[json['condition'] as int],
formattedCondition: json['formattedCondition'],
minTemp: json['minTemp'],
temp: json['temp'],
maxTemp: json['maxTemp'],
locationId: json['locationId'],
created: json['created'],
lastUpdated: DateTime.parse(json['lastUpdated']),
location: json['location'],
),
);
}
@override
Map<String, dynamic> toJson(WeatherState state) {
if (state is WeatherLoaded) {
return {
'condition': state.weather.condition.index,
'formattedCondition': state.weather.formattedCondition,
'minTemp': state.weather.minTemp,
'temp': state.weather.temp,
'maxTemp': state.weather.maxTemp,
'locationId': state.weather.locationId,
'created': state.weather.created,
'lastUpdated': state.weather.lastUpdated.toIso8601String(),
'location': state.weather.location,
};
}
return null;
}
}
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.