Dart中的动态开关盒 [英] Dynamic switch cases in Dart

查看:61
本文介绍了Dart中的动态开关盒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无论如何,我们可以在Dart中生成动态切换案例吗?我正在为我的API响应状态代码创建错误处理程序.一个示例如下所示:

Is there anyway we can generate dynamic switch cases in Dart? I am making error handler for my API response status code. An example would look like this:

http.Response response = await http.post("api url here", body: jsonMap);
switch (response.statusCode) {
  case (200):
    await showSuccessDialog();
    // handles on success
  case (400):
    // show error message for status code 400
  case (500):
    // show error message for status code 500
  default:
    break;
}

我想创建一个全局函数,以便每当有API调用时都可以重用此函数.为此,我需要一个与每个错误代码相对应的错误消息的自定义列表.在我看来,全局功能开关的情况将如下所示,将 _customMessage 作为 List< map>

I want to make a global function of sort so I can reuse this function whenever there is an API call. To do this, I would need a custom List of error messages corresponding to each error code. In my mind, the global function switch case would look like this, with passing of _customMessage as List<map>.

List<Map> customMessages = [
  {"error_code": 400, "message": "Error 400"},
  {"error_code": 402, "message": "Error 402"}
];

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: Center(
      child: RaisedButton(
        onPressed: () async {
          var jsonMap; // handle jsonMap here
          http.Response response =
              await http.post("api url here", body: jsonMap);
          errorDialogs(context, response.statusCode, customMessages);
        },
      ),
    ),
  );
}

void errorDialogs(BuildContext _context, int _statusCode, List<Map> _customMessages) {
  // below switch statement is wrong but putting it here to get the idea across
  switch (_statusCode) {
    _customMessages.forEach((error){
      case (error["error_code"]): 
        //show dialog with error["error_message"]
    }
  }
}

所以问题就在于此,以上内容绝对是错误的,但这就是主意.如何制作动态切换案例,以便它可以根据传递给此功能的错误消息列表生成切换案例?任何帮助,我们将不胜感激!

So the problem lies in this, the above is definitely wrong but that's the idea. How do I make dynamic switch cases so it can generate switch cases based on a List of error message that I pass in to this function? Any help is greatly appreciated!

编辑后的代码以显示如何应用功能 errorDialogs .

Edited code to show how I would apply the function errorDialogs.

推荐答案

这样的作品行吗?

Map<String, void Function()> functionMap = {
  'a': () => print('A'),
  'b': () => print('B'),
  'c': () => print('C'),
  'd': () => print('D'),
  'e': () => print('E'),
};

void main() {
  final x = 'c';
  print('CASE $x:');
  functionMap[x].call();
}

结果:

CASE c:
C

这篇关于Dart中的动态开关盒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆