I have issues with the path on the getApplicationDocumentsDirectory() function

Viewed 2736

I get an error message over the path provider that says error: The getter 'path' isn't defined for the class 'Future'.

I am trying to generate a PDF file following the https://pub.dev/packages/pdf#-example-tab- and this example https://github.com/javico2609/flutter-challenges/blob/master/lib/pages/code_examples/pdf_and_csv/pdf.dart

But as I go on I get the error that path isn't defined on the Future. But as I see on the web I am doing it right. Here is the code:

final String dir = (getApplicationDocumentsDirectory()).path;
final String path = '$dir/receta.pdf';
final File file = File(path);
file.writeAsBytesSync(newpdf.save());

As I said. I can't run the app because I get the message error: The getter 'path' isn't defined for the class 'Future'.

Also tried to write

final Future<Directory> directory = getApplicationDocumentsDirectory();
final String dir = directory.path;
final String path = '$dir/receta.pdf';
final File file = File(path);
file.writeAsBytesSync(newpdf.save()); 

But it doesn't work, path on the variable dir shows the error

3 Answers

In final Future<Directory> directory = getApplicationDocumentsDirectory(); getApplicationDocumentsDirectory() is any async function which means it will return the directory asynchronously , So then when you are trying to read directory.path;, directory is not initialized yet, its null.

Instead returning a future directory wait till it is initialized,

final Directory directory = await getApplicationDocumentsDirectory();

Import this.. it solves the issue

 import 'package:path_provider/path_provider.dart';

You must put await keyword like this:

final directory = await getApplicationDocumentsDirectory();
final path = join(directory.path, 'db_todolist_sqflite');
Related