在 BLoC 中触发初始事件

ven*_*ick 11 dart flutter bloc flutter-bloc

示例状态:

abstract class ExampleState extends Equatable {
  const ExampleState();
}

class LoadingState extends ExampleState {
  //
}

class LoadedState extends ExampleState {
  //
}

class FailedState extends ExampleState {
  //
}
Run Code Online (Sandbox Code Playgroud)

示例_事件:

abstract class ExampleEvent extends Equatable {
  //
}

class SubscribeEvent extends ExampleEvent {
  //
}

class UnsubscribeEvent extends ExampleEvent {
  //
}

class FetchEvent extends ExampleEvent {
  // 
}
Run Code Online (Sandbox Code Playgroud)

示例_块:

class ExampleBloc extends Bloc<ExampleEvent, ExampleState> {
  @override
  ExampleState get initialState => LoadingState();

  @override
  Stream<ExampleState> mapEventToState(
    ExampleEvent event,
  ) async* {
    if (event is SubscribeEvent) {
      //
    } else if (event is UnsubscribeEvent) {
      //
    } else if (event is FetchEvent) {
      yield LoadingState();
      try {
        // network calls
        yield LoadedState();
      } catch (_) {
        yield FailedState();
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

示例_屏幕:

class ExampleScreenState extends StatelessWidget {
  // ignore: close_sinks
  final blocA = ExampleBloc();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: BlocBuilder<ExampleBloc, ExampleState>(
        bloc: blocA,
        // ignore: missing_return
        builder: (BuildContext context, state) {
          if (state is LoadingState) {
            blocA.add(Fetch());
            return CircularProgressBar();
          }

          if (state is LoadedState) {
            //...
          }

          if (state is FailedState) {
            //...
          }
        },
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

正如您在 example_bloc 中看到的,初始状态是 LoadingState() 并且在构建中它显示圆形进度条。我使用 Fetch() 事件来触发下一个状态。但我在那里使用它感觉不舒服。我想做的是:

当应用程序启动时,它应该显示 LoadingState 并开始网络调用,然后当它全部完成时,它应该显示 LoadedState 和网络调用结果,如果出现问题,它应该显示 FailedState。我想在不做的情况下实现这些

if (state is LoadingState) {
  blocA.add(Fetch());
  return CircularProgressBar();
}
Run Code Online (Sandbox Code Playgroud)

Ser*_*kov 30

您的不适确实是有原因的 - 不应从build()方法中触发任何事件(build() 可以根据 Flutter 框架的需要触发多次)

我们的案例是在创建 Bloc 时触发初始事件

可能性概述

  1. 使用 BlocProvider 插入 Bloc 的情况 - 这是首选方式

create: 回调仅在 BlocProvider 挂载时触发一次,而 BlocProvider 在卸载 BlocProvider 时将 close() bloc

    class ExampleScreenState extends StatelessWidget {
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: BlocProvider(
            create: (context) => ExampleBloc()..add(Fetch()), // <-- first event, 
            child: BlocBuilder<ExampleBloc, ExampleState>(
              builder: (BuildContext context, state) {
                ...
              },
            ),
          ),
        );
      }
    }
Run Code Online (Sandbox Code Playgroud)
  1. StateStatefull 小部件中创建 Bloc 的情况
class _ExampleScreenStateState extends State<ExampleScreenState> {
  ExampleBloc _exampleBloc;

  @override
  void initState() {
    super.initState();
    _exampleBloc = ExampleBloc();
    _exampleBloc.add(Fetch());
    // or use cascade notation
    // _exampleBloc = ExampleBloc()..add(Fetch());
  }

  @override
  void dispose() {
    super.dispose();
    _exampleBloc.close(); // do not forget to close, prefer use BlocProvider - it would handle it for you
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: BlocBuilder<ExampleBloc, ExampleState>(
        bloc: _exampleBloc,
        builder: (BuildContext context, state) {
         ...
        },
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)
  1. 在 Bloc 实例创建时添加第一个事件 - 这种方式在测试时有缺点,因为第一个事件是隐式的
class ExampleBloc extends Bloc<ExampleEvent, ExampleState> {

  ...

  ExampleBloc() {
    add(Fetch());
  }
}

// insert it to widget tree with BlocProvider or create in State
BlocProvider( create: (_) => ExampleBloc(), ...

// or in State

class _ExampleScreenStateState extends State<ExampleScreenState> {
  final _exampleBloc = ExampleBloc(); 
...
Run Code Online (Sandbox Code Playgroud)

PS请随时在评论中联系我

  • 当我尝试第二种情况时,BlocListener 不起作用。 (2认同)

小智 10

谢尔盖·萨尔尼科夫有一个很好的答案。不过我想我可以添加另一个建议。

在我的 main.dart 文件中,我使用 MultiBlocProvider 创建所有块以供在树中进一步使用。像这样

Widget build(BuildContext context) {
    return MultiBlocProvider(
      providers: <BlocProvider<dynamic>>[
        BlocProvider<OneBloc>(create: (_) => OneBloc()),
        BlocProvider<TwoBloc>(create: (_) => TwoBloc()),
      ],
      child: MaterialApp( // Rest of your app )
Run Code Online (Sandbox Code Playgroud)

然后,当我加载页面时需要调用事件时,在这种情况下,我想根据所选的列表图块获取一些数据,并且我需要比 FutureBuilder 可以提供的更多选项,我简单地使用了 initState(); 并致电集团提供商并添加了一个事件。

class _ExampleScreenState extends State<ExampleScreen> {
    

  @override
  void initState() {
    super.initState();
    BlocProvider.of<OneBloc>(context)
        .add(FetchData);
  }
Run Code Online (Sandbox Code Playgroud)

它之所以有效,是因为该块已经从根小部件提供了。


kri*_*yaa 7

简单来说:

1. 使用BlocProvider,在创建时调用。

   BlocProvider(create: (context) => ExampleBloc()..add(Fetch()))
Run Code Online (Sandbox Code Playgroud)

2. 使用BlocState,将其用作

   class _ExampleScreenStateState extends State<ExampleScreenState> {
      ExampleBloc _exampleBloc;

      @override
     void initState() {
     super.initState();
     _exampleBloc = ExampleBloc()..add(Fetch());
   }

   @override
   void dispose() {
     super.dispose();
     _exampleBloc.close();
  }
Run Code Online (Sandbox Code Playgroud)