Flutter Cubit state does not leave the starting point (MyInitialState)

Viewed 3099

I'm learning cubit / bloc but when I have a page that loads information from a json file, my status doesn't change.

I have no idea what is happening because it does not return any error, but through a print I can follow the current states. I also did not find a source of information that uses this way, without the need for a click or something

my cubit

   class AgentesCubit extends Cubit<AgentesState> {
      final AgentesRepository _agentesRepository = JsonAgentesRepository();
      AgentesCubit() : super(AgentesInitial());
      List<Agentes> listAgentes;
    
      getAgentes() async {
        try {
          emit(AgentesLoading());
          _agentesRepository.loadAgentes().then((data) => listAgentes = data);
          print(listAgentes);
          emit(AgentesLoaded(listAgentes));
        } on NetworkError {
          emit(AgentesError('Ocorreu algo inesperado, tente novamente mais tarde'));
        }
      }
    }
    
    class NetworkError {}

my states

part of 'agentes_cubit.dart';

@immutable
abstract class AgentesState {
  const AgentesState();
}

class AgentesInitial extends AgentesState {
  const AgentesInitial();
}

class AgentesLoading extends AgentesState {
  const AgentesLoading();
}

class AgentesLoaded extends AgentesState {
  final List<Agentes> agentes;
  const AgentesLoaded(this.agentes);

  @override
  bool operator ==(Object o) {
    if (identical(this, o)) return true;
    return o is AgentesLoaded && o.agentes == agentes;
  }

  @override
  int get hashCode => agentes.hashCode;
}

class AgentesError extends AgentesState {
  final String message;
  const AgentesError(this.message);

  @override
  bool operator ==(Object o) {
    if (identical(this, o)) return true;

    return o is AgentesError && o.message == message;
  }

  @override
  int get hashCode => message.hashCode;
}

my page

class AgentesPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
          child: BlocBuilder<AgentesCubit, AgentesState>(
        cubit: AgentesCubit(),
        builder: (context, state) {
          if (state is AgentesInitial) {
            print('initial');
            return buildLoading();
          } else if (state is AgentesLoading) {
            print('loading');
            return buildLoading();
          } else if (state is AgentesLoaded) {
            print('loaded');
            return buildAgentesList(state.agentes, context);
          }
          return Container();
        },
      )),
    );
  }

  buildLoading() {
    return Center(
      child: CircularProgressIndicator(),
    );
  }

  buildAgentesList(agentes, context) {
    print(agentes);
    return Container(
      width: MediaQuery.of(context).size.width,
      child: ListView.builder(
          itemCount: agentes.length,
          itemBuilder: (context, index) => CustomAgenteItem(agentes[index])),
    );
  }

  void loadAgentes(BuildContext context) {
    final agentesCubit = context.bloc<AgentesCubit>();
    agentesCubit.getAgentes();
  }
}

my agentes item widget

class CustomAgenteItem extends StatelessWidget {
  final Agentes agente;
  CustomAgenteItem(this.agente);

  @override
  Widget build(BuildContext context) {
    return InkWell(
        highlightColor: mainColor,
        splashColor: mainColor,
        onTap: () => print(''),
        child: Container(
          width: MediaQuery.of(context).size.width,
          child: new ParallaxImage(
            child: Padding(
              padding: const EdgeInsets.only(top: 16.0, left: 16),
              child: Text(
                agente.nome,
                style: listAgents,
              ),
            ),
            extent: 100.0,
            image: new AssetImage(
              'assets/images/bg.jpg',
            ),
          ),
        ));
  }
}

my repository

class AgentesRepository {
  loadAgentes() async {
    return agentesFromJson(
        await rootBundle.loadString('assets/infos/agentes.json'));
  }
}
1 Answers

It looks like you need to await the result of _agentesRepository.loadAgentes() since it is an asynchronous function, otherwise the code block will continue to run the next line of code. You could also move all the code after that line into the function you pass to .then but it won't read as well.

Also it doesn't look like you need listAgentes defined on the AgentesCubit class

...
var data = await _agentesRepository.loadAgentes();
emit(AgentesLoaded(data));
...
Related