我很抱歉,我认为这是一个很基本的问题,但我很难理解这个问题。我知道什么是未来,我该如何利用它?但我不认为这适用于这种情况,或者如果它是适用的,我甚至比我想象的更困惑!
我正在尝试使用Logger包中的FileOutput记录到设备存储。这需要file
对象作为参数。
为了获得正确的路径,我使用path_provider包中的getApplicationDocumentsDirectory()。这将返回一个Future,我可以用await操作它,使之成为异步函数中的Future。
不过,我不清楚如何从中提取一个文件,以及如何确保这些对象在需要之前可供记录器使用。在我调用runApp()之前,是否需要这样做?我假设我不需要也不应该将async推到main()?
我就在这里。x2()是一个测试函数,我可以在调用runApp()后从main()中成功调用,并给出正确的结果。
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
print("directory: $directory");
return directory.path;
}
Future<File> get _localFile async {
final path = await _localPath;
print("path: $path");
return File('$path/logger.out');
}
var logger2 = Logger(
output: MultiOutput([
ConsoleOutput(),
FileOutput(
file: _localFile,
overrideExisting: true,
),
]),
printer: PrettyPrinter(
printBox: false,
printTime: true,
),
filter: ProductionFilter(),
);
void x2() async {
var f = await _localFile;
print("_localFile: $f");
}
您应该能够在runApp之前设置记录器,但您不需要等待它,您可以创建一个记录器,然后使用提供程序或单个实例进行访问,您可以简单地使用一个getLogger方法来检查实例是否可用,如果不可用,则调用那里的await
这样,您只调用future一次,并在类中缓存实例。