14

私は BLoC パターンに従い、ストリームをサブスクライブし、ビルド メソッドの状態変化に反応しています。データが読み込まれたら画面を閉じたい。

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Bloc'),
      ),
      body: SafeArea(
        child: StreamBuilder<UserState>(
          stream: _userBloc.user,
          initialData: UserInitState(),
          builder: (context, snapshot) {
            if (snapshot.data is UserInitState) {
              return _buildInit();
            }
            if (snapshot.data is UserDataState) {
              Navigator.pop(context, true);
              return Container();
            }
            if (snapshot.data is UserLoadingState) {
              return _buildLoading();
            }
          },
        ),
      ),
    );
  } 

メソッドで行うNavigator.pop(context, true);と、次のようになります。build()

I/flutter ( 4360): ══╡ EXCEPTION CAUGHT BY ANIMATION LIBRARY ╞═════════════════════════════════════════════════════════
I/flutter ( 4360): The following assertion was thrown while notifying status listeners for AnimationController:
I/flutter ( 4360): setState() or markNeedsBuild() called during build.
I/flutter ( 4360): This Overlay widget cannot be marked as needing to build because the framework is already in the
I/flutter ( 4360): process of building widgets. A widget can be marked as needing to be built during the build phase
I/flutter ( 4360): only if one of its ancestors is currently building. This exception is allowed because the framework
I/flutter ( 4360): builds parent widgets before children, which means a dirty descendant will always be built.
I/flutter ( 4360): Otherwise, the framework might not visit this widget during this build phase.

BLoCパターンでそのようなケースを処理する正しい方法は何ですか?

私が思いついた解決策の 1 つは、でストリームを聴き始めることですinitState()。この場合broadcast()、2 人のサブスクライバーがいるため、ストリームが必要です。

これに対するより良い解決策はありますか?

4

3 に答える 3

1
bool hasPop = false;

  @override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      title: const Text('Bloc'),
    ),
    body: SafeArea(
      child: StreamBuilder<UserState>(
        stream: _userBloc.user,
        initialData: UserInitState(),
        builder: (context, snapshot) {
          if (snapshot.data is UserInitState) {
            return _buildInit();
          }
          if (snapshot.data is UserDataState) {
            if(!hasPop){
               hasPop = true;
               Navigator.pop(context, true);
             }
            
            return Container();
          }
          if (snapshot.data is UserLoadingState) {
            return _buildLoading();
          }
        },
      ),
    ),
  );
} ```
于 2021-02-23T18:29:40.413 に答える