此函数的返回类型为,但不以return语句结尾

时间:2020-07-30 10:13:35

标签: flutter dart

我有警告:“此函数的返回类型为'FutureOr ',但不以return语句结尾。”

我的代码

  Future<List<Task>> getAllTasks() async {
    _readTaskList().then((dynamic value) {
      if (value != null) {
        final List<Task> tasks = <Task>[];
        final List<Task> _tasks = value as List<Task>;
        tasks.forEach((dynamic element) {
          _tasks.add(_convertFromJsonToTask(element as Map<String, dynamic>));
        });
        return tasks;
      } else {
        return null;
      }
    });
  }

2 个答案:

答案 0 :(得分:2)

问题在于,_readTaskList()函数完全执行之前,不会返回getAllTasks()中的值。只需将.then替换为await就可以解决此问题

Future<List<Task>> getAllTasks() async {
    var value = await _readTaskList();
    if (value != null) {
      final List<Task> tasks = <Task>[];
      final List<Task> _tasks = value as List<Task>;
      tasks.forEach((dynamic element) {
        _tasks.add(_convertFromJsonToTask(element as Map<String, dynamic>));
      });
      return tasks;
    } else {
      return null;
    }
  }

答案 1 :(得分:0)

请尝试执行以下操作:

Future<List<Task>> getAllTasks() async {
  final dynamic value = await _readTaskList();
  
  if (value != null) {
    final List<Task> tasks = <Task>[];
    final List<Task> _tasks = value as List<Task>;
    tasks.forEach((dynamic element) {
      _tasks.add(_convertFromJsonToTask(element as Map<String, dynamic>));
    });
    return tasks;
  } else {
    return null;
  }
}

或者如果您真的想使用then

Future<List<Task>> getAllTasks() {
  return _readTaskList().then((dynamic value) {
    if (value != null) {
      final List<Task> tasks = <Task>[];
      final List<Task> _tasks = value as List<Task>;
      tasks.forEach((dynamic element) {
        _tasks.add(_convertFromJsonToTask(element as Map<String, dynamic>));
      });
      return tasks;
    } else {
      return null;
    }
  });
}