1

I am a beginner to flutter and I don't quite understand how to use Async functions in flutter. For example,

Future <String> readData() async {
  final file = await localFile;
  String body = await file.readAsString();
  return body;
}

So in this code, I retrieve some data from a local file. But I want to run this function at the start of the app and want to display the result.

Unfortunately, my build function in main.dart is a synchronous one and when I do:

child : Text(readData());

It does not work due to the fact that it returns a Future . I can't use the await keyword either because it Build is not async. How do I go about waiting to get this string and display it?

2 Answers 2

1

You can try using FutureBuilder

  child: FutureBuilder<String>(
      builder: (context, data) {
        return Text(data.hasData ? data.data : '');
      },
      future: readData(),
  ),
Sign up to request clarification or add additional context in comments.

1 Comment

You can also using a variable in State of StatefullWidget and setState when file.readAsString() completed.
0

Dart Streams - Flutter in Focus

This is very well explained I think should help you

1 Comment

Thanks for this, can you give me some context in terms of code as to what I can do?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.