@ashyr96

Как сохранить состояние в flutter bloc?

Здравствуйте, я начал изучать BLoC паттерн ( flutter_bloc plugin ) и не могу понять как сохранить выбранную состоянию.
Я начал делать приложения, а именно прогноз погоды. Конкретно в моем примере initialState будет один город.
После того как пользователь выберет другой город, нужно чтобы при открытии приложения ( после закрытии ), в экране показывался именно выбранный город. Как мне этого добиться с Bloc паттерном.

Мой код:

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();
      }
    }
  }
}


UI:
@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');
              },
            )));
  }
}
  • Вопрос задан
  • 188 просмотров
Пригласить эксперта
Ответы на вопрос 1
@mayken
Сохранить куда-нибудь(например, во shared preferences) выбранный город.
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы