1

我可以通过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)

如何在提供者状态管理中管理“ContentLoadInProgress”状态?

4

1 回答 1

1

你可以保持你的状态为enum

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

在您的提供者类中:

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
  }
)
于 2020-03-03T10:57:38.347 回答