skip to Main Content

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

2

Answers


  1. 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.

    Login or Signup to reply.
  2. An async function in dart can only return a Future.

    Your readContent function signature doesn’t declare a return value:

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

    If you explicitly declare the return value as String you’ll get a compilation error. Async methods can only return a future:

    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 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.

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

    To address the issue described in your question, you might call readAsString synchronously:

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

    Or use await on the calling side

    var val = await readContent(path);
    

    Or

    var txt = "";
    readContent(path).then((value) {
      txt = value;
      setState(() {});
    });
    

    Or use the FutureBuilder widget

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search