Flutter Bloc 与“InProgress”的提供者状态管理

Posted

技术标签:

【中文标题】Flutter Bloc 与“InProgress”的提供者状态管理【英文标题】:Flutter Bloc vs Provider State Manament for "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。 【参考方案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
  
)

【讨论】:

这个例子省略了内容加载成功后实际内容的传递。仅使用枚举。

以上是关于Flutter Bloc 与“InProgress”的提供者状态管理的主要内容,如果未能解决你的问题,请参考以下文章

Flutter Bloc 与新闻 api

将flutter_bloc与tabview一起使用

如何将 Flutter Bloc 与 Firebase 电话身份验证一起使用

在 Flutter 中使用 BLoC - 在有状态小部件与无状态小部件中的使用

Flutter Bloc 与 firebase 查询有多种关系

flutter_bloc/provider RepositoryProvider vs Provider