Flutter Bloc vs Provider State Manament for "InProgress"

Issue

I can manage InProgress state via “yield” operator in Flutter Bloc,

My bloc:

@override
  Stream<ContentState> mapEventToState(
    ContentEvent event,
  ) async* {
    if (event is ContentStarted) {
      yield ContentLoadInProgress(); //yeah
      var content= await repository.getContent();
      yield ContentLoadSuccess(content);
    }
    ...
 }

page:

      builder: (context, state) {
         if (state is ContentInProgress) {
          return LoadingWidget();         //showing CircularProgressIndicator Widget
        } else if (state is ContentLoadSuccess) {
         return Text(state.content); 
         }

(States : InitState,ContentLoadInProgress, ContentLoadSuccess, ContentLoadFailure)

How can I manage “ContentLoadInProgress” state in Provider State Management?

Solution

You can keep your states as enum

enum ContentStates { 
  InitState, 
  ContentLoadInProgress, 
  ContentLoadSuccess, 
  ContentLoadFailure,
}

In your provider class:

class ContentProvider with ChangeNotifier {
  ContentState state = ContentStates.InitState;
  Content content;

  yourEvent() {
    state = ContentStates.ContentLoadInProgress;
    notifyListeners(); // This will notify your listeners to update ui

    yourOperations();
    updateYourContent();
    state = ContentStates.ContentLoadSuccess;
    notifyListeners();
  } 
}

Inside your widget you can use Consumer (Assuming you already used ChangeNotifierProvider above in your widget tree)

Consumer(
  builder: (context, ContentProvider provider, _) {
    if (provider.state == ContentStates.ContentLoadInProgress) {
      return LoadingWidget();
    } else if (provider.state == ContentStates.ContentLoadSucces) {
      // use provider.content to get your content
      return correspondingWidget();
    } else if .... // widgets for other states
  }
)

Answered By – Selim Kundakçıoğlu

Answer Checked By – David Goodson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *