【问题标题】:Flutter Bloc: Why is a child BlocBuilder built with new state before parent BlocListener is notified?Flutter Bloc:为什么在通知父 BlocListener 之前使用新状态构建子 BlocBuilder?
【发布时间】:2021-02-14 16:58:20
【问题描述】:

我有一个根级 BlocListener,它监听我的全局 AuthBloc 以了解身份验证状态的变化,并在用户退出时使用 Navigator 返回登录页面。

一个后代HomePage 小部件也使用该身份验证状态,假设AuthBloc 处于AuthenticatedState 中(如果它正在构建)。但是,在退出后,子 HomePage 会在根 BlocListener 有机会导航回登录之前使用新的 UnauthenticatedState 构建。

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // assume AuthBloc has already been provided
    return BlocBuilder<AuthBloc, AuthState>(
      listener: (context, state) {
        if (state is! AuthenticatedState) {
          Navigator.pushNamed(context, '/login');
          // ^--- I expect this to be called before HomePage gets UnauthenticatedState
        }
      },
      child: HomePage(),
    );
  }
}


class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext) {
    return BlocBuilder<AuthBloc, AuthState>(
      builder: (context, state) {
        // state == Unauthenticated after signing out  <------
      }
    );
  }
}

这是预期的行为还是应该有保证的parent-&gt;child 更新顺序?处理此问题的推荐模式是什么?

【问题讨论】:

    标签: flutter bloc flutter-bloc


    【解决方案1】:

    在 HomePage 的 BlocBuilder 中添加 condition,如下所示:

    class HomePage extends StatelessWidget {
     @override
    
     Widget build(BuildContext) {
      return BlocBuilder<AuthBloc, AuthState>(
        condition: (AuthState previousState, AuthState currentState) => currentState is AuthenticatedState,
        builder: (context, state) {
         /// Build your home page screen here
        }
      );
    }
    

    }

    【讨论】:

    • 我认为现在是buildWhen,而不是condition。但我认为这不能解决我的问题,因为这只是决定了何时应该重建小部件。如果状态不是我需要的,我可以有条件地在 HomeScreen 中渲染一个空容器,但这会导致一个短暂的空白屏幕,因为新状态最终会到达导航器。
    猜你喜欢
    • 2019-12-28
    • 2022-01-06
    • 2021-10-30
    • 2021-03-19
    • 2021-04-17
    • 2021-02-11
    • 2020-07-20
    • 1970-01-01
    • 2021-03-19
    相关资源
    最近更新 更多