BlocBuilder() not being updated after BLoC yielding new state

Viewed 3412

I am new to the BLoC pattern on flutter and i'm trying to rebuild a messy flutter app using it. Currently, I intend to get a list of user's apps and display them with a ListView.builder(). The problem is that whenever the state of my AppsBloc changes, my StatelessWidget doesn't update to show the new state. I have tried:

  • Using MultiBlocProvider() from the main.dart instead of nesting this appsBloc inside a themeBloc that contains the whole app
  • Returning a list instead of a Map, even if my aux method returns a correct map
  • Using a StatefulWidget, using the BlocProvider() only on the ListView...

I have been reading about this problem on similar projects and the problem might be with the Equatable. However, I haven't been able to identify any error on that since I'm also new using Equatable. I have been debugging the project on VScode with a breakpoint on the yield* line, and it seems to be okay. In spite of that the widget doesn't get rebuilt: it keeps displaying the textcorresponding to the InitialState.

Moreover, the BLoC doesn't print anything on console even though all the states have an overwritten toString()

These are my 3 BLoC files:

apps_bloc.dart

import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:device_apps/device_apps.dart';
import 'package:equatable/equatable.dart';

part 'apps_event.dart';
part 'apps_state.dart';

class AppsBloc extends Bloc<AppsEvent, AppsState> {
  @override
  AppsState get initialState => AppsInitial();

  @override
  Stream<AppsState> mapEventToState(AppsEvent event) async* {
    yield AppsLoadInProgress();
    if (event is AppsLoadRequest) {
      yield* _mapAppsLoadSuccessToState();
      }
  }

  Stream<AppsState> _mapAppsLoadSuccessToState() async* {
    try {
      final allApps = await DeviceApps.getInstalledApplications(
          onlyAppsWithLaunchIntent: true, includeSystemApps: true);

      final listaApps = allApps
        ..sort((a, b) =>
            a.appName.toLowerCase().compareTo(b.appName.toLowerCase()));

      final Map<Application, bool> res =
          Map.fromIterable(listaApps, value: (e) => false);

      yield AppsLoadSuccess(res);
    } catch (_) {
      yield AppsLoadFailure();
    }
  }
}

apps_event.dart

part of 'apps_bloc.dart';

abstract class AppsEvent extends Equatable {
  const AppsEvent();

  @override
  List<Object> get props => [];
}

class AppsLoadRequest extends AppsEvent {}

apps_state.dart

part of 'apps_bloc.dart';

abstract class AppsState extends Equatable {
  const AppsState();

  @override
  List<Object> get props => [];
}

class AppsInitial extends AppsState {
  @override
  String toString() => "State: AppInitial";
}

class AppsLoadInProgress extends AppsState {
  @override
  String toString() => "State: AppLoadInProgress";
}

class AppsLoadSuccess extends AppsState {
  final Map<Application, bool> allApps;
  const AppsLoadSuccess(this.allApps);

  @override
  List<Object> get props => [allApps];

  @override
  String toString() => "State: AppLoadSuccess, ${allApps.length} entries";
}

class AppsLoadFailure extends AppsState {
  @override
  String toString() => "State: AppLoadFailure";
}

main_screen.dart

class MainScreen extends StatelessWidget {
  const MainScreen({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return TabBarView(
        children: <Widget>[
          HomeScreen(),
          BlocProvider(
            create: (BuildContext context) => AppsBloc(),
            child: AppsScreen(),
          )
          ,
        ],
      );
  }
}

apps_screen.dart

class AppsScreen extends StatelessWidget {
  const AppsScreen({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
          body: Container(
          margin: EdgeInsets.fromLTRB(30, 5, 10, 0),
          child: Column(children: <Widget>[
            Row(
              children: <Widget>[
                Text("Apps"),
              ],
            ),
            Row(children: <Widget>[
              Container(
                width: MediaQuery.of(context).size.width - 50,
                height: MediaQuery.of(context).size.height - 150,
                child: BlocBuilder<AppsBloc, AppsState>(
                  builder: (BuildContext context, AppsState state) {
                    if (state is AppsLoadSuccess)
                      return Text("LOADED");
                    else if (state is AppsInitial)
                      return GestureDetector(
                          onTap: () => AppsBloc().add(AppsLoadRequest()),
                          child: Text("INITIAL"));
                    else if (state is AppsLoadInProgress)
                      return Text("LOADING...");
                    else if (state is AppsLoadFailure)
                      return Text("LOADING FAILED");
                  },
                ),
              ),
            ])
          ])),
    );
  }
}
1 Answers

In GestureDetector.onTap() you create a new AppsBloc(), this is wrong. So, you need:

apps_screen.dart:

  AppsBloc _appsBloc;

  @override
  void initState() {
    super.initState();

    _appsBloc = BlocProvider.of<AppsBloc>(context);
  }

//...

  @override
  Widget build(BuildContext context) {
    //...
    return GestureDetector(
      onTap: () => _appsBloc.add(AppsLoadRequest()),
      child: Text("INITIAL")
    );
    //...
  }

Or you can do the same even without the _appsBloc field:

BlocProvider.of<AppsBloc>(context).add(AppsLoadRequest())
Related