屏幕加载时如何仅一次调用bloc事件

时间:2020-08-21 15:06:04

标签: flutter bloc

我正在使用flutter_bloc库。我的屏幕小部件代码看起来像这样:

class RegisterScreen extends StatefulWidget {
  RegisterScreen();

  @override
  _RegisterScreenState createState() => _RegisterScreenState();
}

class _RegisterScreenState extends State<RegisterScreen> {
  @override
  Widget build(BuildContext context) {
    return BlocProvider<RegisterBloc>(
      create: (BuildContext context) {
        // RegisterBloc.get(context).add(RegisterGetCitiesEvent());<=== This gives me error `BlocProvider.of() called with a context that does not contain a Cubit of type RegisterBloc. \n No ancestor could be found starting from the context that was passed to BlocProvider.of<RegisterBloc>().`
        return RegisterBloc();
      },
      child: BlocConsumer<RegisterBloc, RegisterState>(
        listener: (BuildContext context, RegisterState state) {},
        builder: (BuildContext context, RegisterState state) {
          // RegisterBloc.get(context).add(RegisterGetCitiesEvent());<=== This line is executed infinite times
          return Scaffold(
            floatingActionButton: FloatingActionButton(
              onPressed: () {
                RegisterBloc.get(context).add(RegisterGetCitiesEvent());
              },
              child: new Icon(Icons.refresh),
            ),
            body: Conteiner(
              child: Text(RegisterBloc.get(context).cities==null?'':RegisterBloc.get(context).cities,)
            ),
          );
        },
      ),
    );
  }
}

bloc文件如下:

class RegisterBloc extends Bloc<RegisterEvent, RegisterState> {
  static RegisterBloc get(BuildContext context) => BlocProvider.of(context);
  RegisterBloc() : super(RegisterInitial());

  String cities = '';

  @override
  Stream<RegisterState> mapEventToState(
    RegisterEvent event,
  ) async* {
    if (event is RegisterGetCitiesEvent) {
      yield* getCities();
    }
  }

  Stream<RegisterGetCitiesState> getCities() async* {
    yield await (CustomerServer.getCities()).then((res) {
      cities = res;
      return RegisterGetCitiesState();
    });
  }
}

在我的代码中,我必须单击FAB来调用RegisterGetCitiesEvent bloc事件。如何在不要求用户单击任何按钮的情况下立即RegisterBloc.get(context).add(RegisterGetCitiesEvent())调用该事件?

我尝试过的事情:

我试图在BlocConsumer构建器函数中添加该行,但是该函数执行了无数次。
我试图在BlocProvider创建函数中添加该行,但它给了我一个错误BlocProvider.of() called with a context that does not contain a Cubit of type RegisterBloc.

我应该在哪里放置此行RegisterBloc.get(context).add(RegisterGetCitiesEvent()),以便在屏幕显示时自动调用RegisterGetCitiesEvent事件(无需单击任何按钮)?

1 个答案:

答案 0 :(得分:1)

我建议您完整阅读BLoC文档。但是,这里是此问题的快速答案:您应该在 int x = 10; if(x<1) cout<<"done"; else if(x> 20) for(int i=0;i<n;i++){ cout<<"done"; } else for(int i=0;i<n;i++){ cout<<"done"; } 的create函数中执行此操作。像这样:

BlocProvider