I’m calling an async function that has the file path as a parameter and reads and displays the content in the file.
this is the place where I’m invoking the function.
this is the function.
After reading the contents in the file, the data is printed in the console.
But when I try to use the same value to display in the emulator I’m getting error.
Why actual string value is not returned from the function??
error.
2
Answers
readContent
is a future method, you need to wait to complete the fetching.For future method, try using FutureBuilder.
Find more about using
FutureBuilder
.An async function in dart can only return a Future.
Your readContent function signature doesn’t declare a return value:
If you explicitly declare the return value as String you’ll get a compilation error. Async methods can only return a future:
The await keyword allows you to access the value returned by a Future, it is not the same as calling the function synchronously.
The only reason you need the await keyword in your code is because you’re printing the value to console when the Future completes. You could do this instead, which is the same function without printing to console and without async await.
To address the issue described in your question, you might call readAsString synchronously:
Or use await on the calling side
Or
Or use the FutureBuilder widget