mars_dev
mars_dev

Reputation: 639

Bloc state not being received in BlocBuilder in Flutter

I have a page where I want to display a list. I am getting data from an api and want to show a loader for the loading time. I am able to show the loader because of initial state but I am trying to emit a different state from bloc it is not reaching in my Page. Blocbuilder is only running for default Initial state. Following is my Page:

    class _WeatherInfoPageState extends State<WeatherInfoPage> {
  late WeatherInfoBloc _weatherInfoBloc;

  @override
  void initState() {
    super.initState();
    _weatherInfoBloc = locator<WeatherInfoBloc>();
    _weatherInfoBloc.add(WeatherInfoFetchEvent());
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<WeatherInfoBloc, WeatherInfoState>(
        builder: (context, state) {
          if (state is WeatherInfoInitial || state is WeatherInfoFetchingState) {
            return _buildLoading();
          } else if (state is WeatherInfoFetchingSuccessState) {
            return _buildWeatherForcastView(context, state.response);
          }
          return Container();
        }
    );
  }

  Widget _buildWeatherForcastView(BuildContext context, WeatherInfo model) {
    return Container();
  }

  Widget _buildLoading() => const Center(child: CircularProgressIndicator());
}

This is my bloc:

WeatherInfoBloc(this._weatherInfoUseCase) : super(WeatherInfoInitial()) {
on<WeatherInfoFetchEvent>((event, emit) async {
  emit(WeatherInfoFetchingState());
  final response = await _weatherInfoUseCase.getWeatherInfo(
      "52.521992", "13.413244");
  response.fold(
          (failure) =>
      {
        emit(WeatherInfoFetchingFailureState(failure.message))
      },
          (success) =>
      {
        emit(WeatherInfoFetchingSuccessState(success))
      });
});

}

my main page:

Widget build(BuildContext context) {
return BlocProvider<WeatherInfoBloc>(
    create: (context) => locator<WeatherInfoBloc>(),
    child: MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      themeMode: ThemeMode.system,
      theme: AppTheme.lightTheme,
      darkTheme: AppTheme.darkTheme,
      home: const Scaffold(
        backgroundColor: Colors.white,
        body: SafeArea(
          child: WeatherInfoPage(),
        ),
      ),
    ));

} }

Upvotes: 0

Views: 40

Answers (1)

S Sharanya Bharghavi
S Sharanya Bharghavi

Reputation: 179

In Your Build Function after init

return BlocBuilder<WeatherInfoBloc, WeatherInfoState>(
        bloc: _weatherInfoBloc // Add this line
        builder: (context, state) {
          // Rest of your code
       }

Upvotes: 1

Related Questions