【问题标题】:Flutter Bloc vs Provider State Manament for "InProgress"Flutter Bloc 与“InProgress”的提供者状态管理
【发布时间】:2020-06-15 12:22:00
【问题描述】:

我可以通过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”状态?

【问题讨论】:

  • 使用“inProgress”布尔值,您在开始操作时设置为 true,在操作完成时设置回 false。

标签: flutter flutter-provider flutter-bloc


【解决方案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
  }
)

【讨论】:

  • 这个例子省略了内容加载成功后实际内容的传递。仅使用枚举。
猜你喜欢
  • 2021-03-04
  • 2020-05-23
  • 2019-08-04
  • 2020-03-10
  • 2021-04-14
  • 2020-04-29
  • 2020-02-28
  • 2021-12-23
  • 2023-01-05
相关资源
最近更新 更多