Dart中的流与未来

问题描述 投票:1回答:1

我已经使用基本的异步/等待一段时间没有太多问题,我想我明白它是如何工作的。不能说我是它的专家,但我不知道它的主旨。我只是无法绕过Streams。在今天之前,我以为我理解它们是如何工作的(基本上是ala 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;
asynchronous dart flutter async-await future
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.