Answer the question
In order to leave comments, you need to log in
How to save state in flutter bloc?
Hello, I started to study BLoC pattern ( flutter_bloc plugin ) and I can't figure out how to save the selected state.
I started making applications, namely the weather forecast. Specifically, in my example, initialState will be one city.
After the user selects another city, it is necessary that when the application is opened (after closing), the selected city is shown on the screen. How can I achieve this with the Bloc pattern.
My Code:
WeatherBloc
class WeatherBloc extends Bloc<WeatherEvent, WeatherState> {
final WeatherRepository weatherRepository;
WeatherBloc({this.weatherRepository}) : super(Weatherinitial());
@override
Stream<WeatherState> mapEventToState(
WeatherEvent event,
) async* {
if (event is FetchWeather) {
yield WeatherLoading();
try {
WeatherModel weatherModel =
await weatherRepository.getWeather(event.latlan);
yield WeatherLoaded(weatherModel: weatherModel);
} catch (_) {
yield WeatherError();
}
}
}
}
@override
Widget build(BuildContext context) {
return BlocProvider<WeatherBloc>(
create: (context) =>
WeatherBloc(weatherRepository: WeatherRepository()),
child: Scaffold(
backgroundColor: HexColor('ffffff'),
body: BlocBuilder<WeatherBloc, WeatherState>(
builder: (context, state) {
if (state is Weatherinitial) {
return WeatherUI();
}
if (state is WeatherLoading) {
return Center(
child: CircularProgressIndicator(),
);
}
if (state is WeatherLoaded) {
return Center(
child: Column(
children: [
Container(
child: Text(state.weatherModel.temp.toString()),
),
Container(
child: Text(state.weatherModel.isDay.toString()),
)
],
),
);
}
return Text('Error');
},
)));
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question