首页 > 解决方案 > Dart how to acces directly to a Map awaited data

问题描述

I have a function that return a Future<Map<String, dynamic>> and I would like to return one of the map values instead of the whole map. For the moment I have to do it like this:

  static Future<bool> fileClearCompleted() async {
    var res = await rsApiCall('/rsFiles/FileDownloads');
    return res['retval'];
  }

rsApiCall return a valid JSON object. So what I would like to find is a more elegant way to return the parameter res['retval'] like:

  static Future<bool> fileClearCompleted() async => await rsApiCall('/rsFiles/FileDownloads')['retval'];

But this don't work, neither with cascade operator like: await rsApiCall('/rsFiles/FileDownloads')..['retval'];

标签: dart

解决方案


The correct syntax would be (see the added parenthesis):

  static Future<bool> fileClearCompleted() async =>
      (await rsApiCall('/rsFiles/FileDownloads'))['retval'];

Since we want to await the rsApiCall and then use the [] operator on that result.


推荐阅读