Dart中的流与未来

时间:2019-04-21 08:03:43

标签: asynchronous dart flutter async-await future

我使用基本异步/等待一段时间了,没有很多问题,我以为我知道它是如何工作的。不能说我是该领域的专家,但我对它的要点理解不足。我只是无法理解Streams。在今天之前,我以为我了解它们的工作原理(基本上是Reactive Programming),但是我无法让它们在Dart中工作。

我正在处理一个持久层,可能会保存和检索(json)文件。我一直在使用fileManager example作为指导。

import 'dart:io';
import 'dart:async';
import 'package:intl/intl.dart'; //date
import 'package:markdowneditor/model/note.dart';//Model
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as p;
import 'package:flutter/foundation.dart'; //log
import 'package:simple_permissions/simple_permissions.dart';//OS permissions

class FileManager {
  static final FileManager _singleton = new FileManager._internal();

  factory FileManager() {
    return _singleton;
  }

  FileManager._internal();

  Future<String> get _localPath async {
    final directory = (await getApplicationDocumentsDirectory()).toString();
    return p.join(directory, "notes"); //path takes strings and not Path objects
  }

  Future<File> writeNote(Note note) async {
    var file = await _localPath;
    file = p.join(
        file,
        DateFormat('kk:mm:ssEEEMMd').format(DateTime.now()) +
            " " +
            note.title); //add timestamp to title
    // Write the file

    SimplePermissions.requestPermission(Permission.WriteExternalStorage)
        .then((value) {
      if (value == PermissionStatus.authorized) {
        return File(file).writeAsString('$note');
      } else {
        SimplePermissions.openSettings();
        return null;
      }
    });

  }

  Future<List<Note>> getNotes() async {
    //need file access permission on android. use https://pub.dartlang.org/packages/simple_permissions#-example-tab-
    final file = await _localPath;

    SimplePermissions.requestPermission(Permission.ReadExternalStorage)
        .then((value) {
      if (value == PermissionStatus.authorized) {
        try {
          Stream<FileSystemEntity> fileList =
              Directory(file).list(recursive: false, followLinks: false);

          // await for(FileSystemEntity s in fileList) { print(s); }
          List<Note> array = [];
          fileList.forEach((x) {

            if (x is File) {
              var res1 = ((x as File).readAsString()).then((value2) {
                Note note = Note.fromJsonResponse(value2);
                return note;
              }).catchError((error) {
                debugPrint('is not file content futurestring getNoteError: $x');
                return null;
              });
              var array2 = res1.then((value3) {
                array.add(value3);
                return array;
              });
            //?
            } else {
              debugPrint('is not file getNoteError: $x');
            }
          });


          // Add the file to the files array
          //Return the Future<List<Note>>
          return array;

        } catch (e) {
          debugPrint('getNoteError: $e');
          // If encountering an error, return 0
          return null;
        }
      } else {
        SimplePermissions.openSettings();
        return null;
      }
    });
  }
}

很明显它是行不通的,但是即使尝试使用注释掉的部分来等待循环也会产生错误。

在“ getNotes”中,检查权限后,我要获取目录中所有文件的数组,将它们解析为Note对象并返回结果数组。

我得到文件列表:

Stream<FileSystemEntity> fileList =
          Directory(file).list(recursive: false, followLinks: false);

对于流中的每个对象,我想将文件解析为一个对象,并将其附加到数组中以最后返回。

       List<Note> array = [];
      fileList.forEach((x) {

        if (x is File) {
          var res1 = ((x as File).readAsString()).then((value2) {
            Note note = Note.fromJsonResponse(value2);
            return note;
          }).catchError((error) {
            debugPrint('is not file content futurestring getNoteError: $x');
            return null;
          });
          var array2 = res1.then((value3) {
            array.add(value3);
            return array;
          });
        //?
        } else {
          debugPrint('is not file getNoteError: $x');
        }
      });


      // Add the file to the files array
      //Return the Future<List<Note>>
      return array;

1 个答案:

答案 0 :(得分:0)

Stream.forEach()返回一个Future。您的最后一个return语句在for-each调用之后立即运行,但应该await

await fileList.forEach((x) {
  ...

https://api.dartlang.org/stable/2.2.0/dart-async/Stream/forEach.html