【问题标题】:Dispatch Bloc Event outside Widget Flutter在 Widget Flutter 之外调度 Bloc 事件
【发布时间】:2020-03-23 05:54:49
【问题描述】:

我是 Flutter 的新手,我正在尝试创建我的第一个应用程序。 在我的应用中,我为网络调用创建了一个单例类。

class NetworkUtil {
  Config configuration;
  Dio dio;
  static NetworkUtil _instance = new NetworkUtil._internal();
  NetworkUtil._internal();
  factory NetworkUtil(Config config){
    _instance.configuration = config;
    _instance.dio = new Dio();
    return _instance;
  }

  final JsonDecoder _decoder = new JsonDecoder();

  Future<dynamic> post(String url, {Map headers, body, encoding}) {
    url = _instance.configuration.url+url;

    return dio.post(url, data: body).then((response) {
      final String res = response.data;
      return res;
    }).catchError((e){
      if(e.response.data.containsKey("message")){
        //I Need to dispatch event in blocClass
         final _classBloc = BlocProvider.of<classBloc>(context); //I haven't context here 
         _classBloc .dispatch(ErrorMessage(message: e.response.data["message"]));

      }else{
        throw new Exception("System Error");
      }
    });
  }
}

我的问题是我没有上下文,所以我无法在 Bloc 中调度事件。

我一直在考虑将上下文作为参数传递,但我不知道这是否是一个不好的做法,在 Android 框架上是非常糟糕的实践将上下文作为参数传递,我不知道在 Flutter 中。

是否可以使用 BlocProvider outisde 小部件?

【问题讨论】:

    标签: flutter bloc


    【解决方案1】:

    我认为你看错了。您想进行网络调用作为对bloc 事件的响应,因此在您的处理函数中-我假设它将在mapEventToState 中,因为您使用的是flutter_bloc-您想要类似的东西:

    // event case
    yield LoadingEvent();
    try {
      var post = await NetworkUtil.post(...);
      yield CompleteState(post);
    } catch (error) {
      // handle errors
      yield ErrorState(error.message);
    }
    

    【讨论】:

    • 是的,但是这样,如果我的应用程序中有100个网络调用,我需要在所有yeld中写入。然后,如果我有一个 repositoryPattern ,那么网络调用是在类存储库中完成的?
    猜你喜欢
    • 2020-12-07
    • 2019-12-06
    • 2020-02-18
    • 2021-08-28
    • 2020-11-12
    • 2022-07-26
    • 2023-02-17
    • 2021-12-07
    • 2020-12-06
    相关资源
    最近更新 更多