Flutter 在窗口小部件颤振外部分派Bloc事件
我是新来的,我正在尝试创建我的第一个应用程序。 在我的应用程序中,我为网络呼叫创建了一个singleton类Flutter 在窗口小部件颤振外部分派Bloc事件,flutter,bloc,Flutter,Bloc,我是新来的,我正在尝试创建我的第一个应用程序。 在我的应用程序中,我为网络呼叫创建了一个singleton类 class NetworkUtil { Config configuration; Dio dio; static NetworkUtil _instance = new NetworkUtil._internal(); NetworkUtil._internal(); factory NetworkUtil(Config config){ _instance
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");
}
});
}
}
类NetworkUtil{
配置配置;
迪奥迪奥;
静态NetworkUtil _instance=新NetworkUtil._internal();
NetworkUtil._internal();
factory NetworkUtil(配置){
_instance.configuration=config;
_instance.dio=新的dio();
返回_实例;
}
最终JsonDecoder_解码器=新JsonDecoder();
Future post(字符串url,{Map headers,body,encoding}){
url=\u instance.configuration.url+url;
返回dio.post(url,数据:body)。然后((响应){
最终字符串res=response.data;
返回res;
}).catchError((e){
if(如响应、数据、容器(“消息”)){
//我需要在blocClass中调度事件
final _classBloc=BlocProvider.of(context);//我这里没有上下文
_classBloc.dispatch(ErrorMessage(消息:e.response.data[“message”]);
}否则{
抛出新异常(“系统错误”);
}
});
}
}
我的问题是,我并没有上下文,所以我不能整体发送事件
我一直在考虑将上下文作为参数传递,但我不知道这是否是一种糟糕的做法,在Android框架上,将上下文作为参数传递是一种糟糕的做法,而在Flatter中我不知道
是否可以使用BlocProvider outisde小部件?我认为您看错了。您希望进行网络调用作为对
bloc
事件的响应,因此在您的处理函数中-我假设它将位于mapEventToState
中,因为您使用的是flatter\u bloc
-您希望有如下内容:
//事件案例
屈服加载事件();
试一试{
var post=等待NetworkUtil.post(…);
成品率(post);
}捕获(错误){
//处理错误
产生错误状态(error.message);
}
是的,但这样,如果我的应用程序中有100个网络呼叫,我需要写入所有的yeld。然后,如果我有一个repositoryPattern,那么newwork调用是在类存储库中完成的?