Home > front end >  Value returning from an async function is not the actual value
Value returning from an async function is not the actual value

Time:01-31

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.

enter image description here

this is the function.

enter image description here

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.

enter image description here

CodePudding user response:

readContent is a future method, you need to wait to complete the fetching. For future method, try using FutureBuilder.

 late Future future = readContent();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder(
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return Text("${snapshot.data}");
          }
          return CircularProgressIndicator();
        },
      ),
    );
  }

Find more about using FutureBuilder.

CodePudding user response:

An async function in dart can only return a Future.

Your readContent function is defined without a return value:

readContent(String path) async {
    var result = await File(path).readAsString();
    print(result);
    return result
}

Which is the same as:

Future<String> readContent(String path) async {
    var result = await File(path).readAsString();
    print(result);
    return result
}

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 here is because you're printing the value to console when the Future completes. You could do this, which is the same function without printing to console

readContent(String path) {
    return File(path).readAsString();
}

To fix this, either call readAsString synchronously:

readContent(String path) {
    return File(path).readAsStringSync();
}

Or use await on the calling side

var val = await readContent();

Or use the FutureBuilder widget as stated in other answers

  • Related