"InProgress" 的 Flutter Bloc 与供应商状态管理

Flutter Bloc vs Provider State Manament for "InProgress"

我可以通过 Flutter Bloc

中的 "yield" 运算符管理 InProgress 状态

我的集团:

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

页数:

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

(状态:InitState、ContentLoadInProgress、ContentLoadSuccess、ContentLoadFailure)

如何在 Provider State Management 中管理 "ContentLoadInProgress" 状态?

您可以将状态保持为 enum

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

在您的提供商中 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();
  } 
}

在您的小部件中,您可以使用 Consumer(假设您已经在上面的小部件树中使用了 ChangeNotifierProvider

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