0

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

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 调用时我就可以重用这个函数。为此,我需要一个与每个错误代码对应的自定义错误消息列表。在我看来,全局函数 switch 案例看起来像这样,传递_customMessageas 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"]
    }
  }
}

所以问题就出在这里,上面肯定是错误的,但就是这样。如何制作动态切换案例,以便它可以根据我传递给此函数的错误消息列表生成切换案例?任何帮助是极大的赞赏!

编辑:编辑代码以显示我将如何应用该功能errorDialogs

4

1 回答 1

1

像这样的东西会起作用吗?

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
于 2021-03-01T15:09:54.197 回答